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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1041  ! raeburn     4: # $Id: lonnet.pm,v 1.1040 2009/10/31 23:37:00 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    79:             $_64bit %env %protocol);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.676     albertel   98: 
1.195     www        99: my $readit;
1.550     foxr      100: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  101: 
1.977     amueller  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.993     raeburn   200: sub get_server_loncaparev {
                    201:     my ($dom,$lonhost) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             undef($lonhost);
                    205:         }
                    206:     }
                    207:     if (!defined($lonhost)) {
                    208:         if (defined(&domain($dom,'primary'))) {
                    209:             $lonhost=&domain($dom,'primary');
                    210:             if ($lonhost eq 'no_host') {
                    211:                 undef($lonhost);
                    212:             }
                    213:         }
                    214:     }
                    215:     if (defined($lonhost)) {
                    216:         my $cachetime = 24*3600;
                    217:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    218:         if (defined($cached)) {
                    219:             return $loncaparev;
                    220:         } else {
                    221:             my $loncaparev = &reply('serverloncaparev',$lonhost);
                    222:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    223:         }
                    224:     }
                    225: }
                    226: 
1.1       albertel  227: # -------------------------------------------------- Non-critical communication
                    228: sub subreply {
                    229:     my ($cmd,$server)=@_;
1.838     albertel  230:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      231:     #
                    232:     #  With loncnew process trimming, there's a timing hole between lonc server
                    233:     #  process exit and the master server picking up the listen on the AF_UNIX
                    234:     #  socket.  In that time interval, a lock file will exist:
                    235: 
                    236:     my $lockfile=$peerfile.".lock";
                    237:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    238: 	sleep(1);
                    239:     }
                    240:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      241:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      242:     #
1.550     foxr      243:     #   We'll give the connection a few tries before abandoning it.  If
                    244:     #   connection is not possible, we'll con_lost back to the client.
                    245:     #   
                    246:     my $client;
                    247:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    248: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    249: 				      Type    => SOCK_STREAM,
                    250: 				      Timeout => 10);
1.869     albertel  251: 	if ($client) {
1.550     foxr      252: 	    last;		# Connected!
1.850     albertel  253: 	} else {
1.853     albertel  254: 	    &create_connection(&hostname($server),$server);
1.550     foxr      255: 	}
1.850     albertel  256:         sleep(1);		# Try again later if failed connection.
1.550     foxr      257:     }
                    258:     my $answer;
                    259:     if ($client) {
1.704     albertel  260: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      261: 	$answer=<$client>;
                    262: 	if (!$answer) { $answer="con_lost"; }
                    263: 	chomp($answer);
                    264:     } else {
                    265: 	$answer = 'con_lost';	# Failed connection.
                    266:     }
1.1       albertel  267:     return $answer;
                    268: }
                    269: 
                    270: sub reply {
                    271:     my ($cmd,$server)=@_;
1.838     albertel  272:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  273:     my $answer=subreply($cmd,$server);
1.65      www       274:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  275:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       276:                 " $cmd to $server returned $answer</font>");
                    277:     }
1.1       albertel  278:     return $answer;
                    279: }
                    280: 
                    281: # ----------------------------------------------------------- Send USR1 to lonc
                    282: 
                    283: sub reconlonc {
1.891     albertel  284:     my ($lonid) = @_;
                    285:     my $hostname = &hostname($lonid);
                    286:     if ($lonid) {
                    287: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    288: 	if ($hostname && -e $peerfile) {
                    289: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    290: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    291: 					     Type    => SOCK_STREAM,
                    292: 					     Timeout => 10);
                    293: 	    if ($client) {
                    294: 		print $client ("reset_retries\n");
                    295: 		my $answer=<$client>;
                    296: 		#reset just this one.
                    297: 	    }
                    298: 	}
                    299: 	return;
                    300:     }
                    301: 
1.836     www       302:     &logthis("Trying to reconnect lonc");
1.1       albertel  303:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  304:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  305: 	my $loncpid=<$fh>;
                    306:         chomp($loncpid);
                    307:         if (kill 0 => $loncpid) {
                    308: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    309:             kill USR1 => $loncpid;
                    310:             sleep 1;
1.836     www       311:          } else {
1.12      www       312: 	    &logthis(
1.672     albertel  313:                "<font color=\"blue\">WARNING:".
1.12      www       314:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  315:         }
                    316:     } else {
1.836     www       317: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  318:     }
                    319: }
                    320: 
                    321: # ------------------------------------------------------ Critical communication
1.12      www       322: 
1.1       albertel  323: sub critical {
                    324:     my ($cmd,$server)=@_;
1.838     albertel  325:     unless (&hostname($server)) {
1.672     albertel  326:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       327:                " Critical message to unknown server ($server)</font>");
                    328:         return 'no_such_host';
                    329:     }
1.1       albertel  330:     my $answer=reply($cmd,$server);
                    331:     if ($answer eq 'con_lost') {
                    332: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  333: 	my $answer=reply($cmd,$server);
1.1       albertel  334:         if ($answer eq 'con_lost') {
                    335:             my $now=time;
                    336:             my $middlename=$cmd;
1.5       www       337:             $middlename=substr($middlename,0,16);
1.1       albertel  338:             $middlename=~s/\W//g;
                    339:             my $dfilename=
1.305     www       340:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    341:             $dumpcount++;
1.1       albertel  342:             {
1.448     albertel  343: 		my $dfh;
                    344: 		if (open($dfh,">$dfilename")) {
                    345: 		    print $dfh "$cmd\n"; 
                    346: 		    close($dfh);
                    347: 		}
1.1       albertel  348:             }
                    349:             sleep 2;
                    350:             my $wcmd='';
                    351:             {
1.448     albertel  352: 		my $dfh;
                    353: 		if (open($dfh,"<$dfilename")) {
                    354: 		    $wcmd=<$dfh>; 
                    355: 		    close($dfh);
                    356: 		}
1.1       albertel  357:             }
                    358:             chomp($wcmd);
1.7       www       359:             if ($wcmd eq $cmd) {
1.672     albertel  360: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       361:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  362:                 &logperm("D:$server:$cmd");
                    363: 	        return 'con_delayed';
                    364:             } else {
1.672     albertel  365:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       366:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  367:                 &logperm("F:$server:$cmd");
                    368:                 return 'con_failed';
                    369:             }
                    370:         }
                    371:     }
                    372:     return $answer;
1.405     albertel  373: }
                    374: 
1.755     albertel  375: # ------------------------------------------- check if return value is an error
                    376: 
                    377: sub error {
                    378:     my ($result) = @_;
1.756     albertel  379:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  380: 	if ($2 == 2) { return undef; }
                    381: 	return $1;
                    382:     }
                    383:     return undef;
                    384: }
                    385: 
1.783     albertel  386: sub convert_and_load_session_env {
                    387:     my ($lonidsdir,$handle)=@_;
                    388:     my @profile;
                    389:     {
1.917     albertel  390: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    391: 	if (!$opened) {
1.915     albertel  392: 	    return 0;
                    393: 	}
1.783     albertel  394: 	flock($idf,LOCK_SH);
                    395: 	@profile=<$idf>;
                    396: 	close($idf);
                    397:     }
                    398:     my %temp_env;
                    399:     foreach my $line (@profile) {
1.786     albertel  400: 	if ($line !~ m/=/) {
                    401: 	    return 0;
                    402: 	}
1.783     albertel  403: 	chomp($line);
                    404: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    405: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    406:     }
                    407:     unlink("$lonidsdir/$handle.id");
                    408:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    409: 	    0640)) {
                    410: 	%disk_env = %temp_env;
                    411: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    412: 	untie(%disk_env);
                    413:     }
1.786     albertel  414:     return 1;
1.783     albertel  415: }
                    416: 
1.374     www       417: # ------------------------------------------- Transfer profile into environment
1.780     albertel  418: my $env_loaded;
                    419: sub transfer_profile_to_env {
1.788     albertel  420:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    421:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       422: 
1.720     albertel  423:     if (!defined($lonidsdir)) {
                    424: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    425:     }
                    426:     if (!defined($handle)) {
                    427:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    428:     }
                    429: 
1.786     albertel  430:     my $convert;
                    431:     {
1.917     albertel  432:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    433: 	if (!$opened) {
1.915     albertel  434: 	    return;
                    435: 	}
1.786     albertel  436: 	flock($idf,LOCK_SH);
                    437: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    438: 		&GDBM_READER(),0640)) {
                    439: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    440: 	    untie(%disk_env);
                    441: 	} else {
                    442: 	    $convert = 1;
                    443: 	}
                    444:     }
                    445:     if ($convert) {
                    446: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    447: 	    &logthis("Failed to load session, or convert session.");
                    448: 	}
1.374     www       449:     }
1.783     albertel  450: 
1.786     albertel  451:     my %remove;
1.783     albertel  452:     while ( my $envname = each(%env) ) {
1.433     matthew   453:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    454:             if ($time < time-300) {
1.783     albertel  455:                 $remove{$key}++;
1.433     matthew   456:             }
                    457:         }
                    458:     }
1.783     albertel  459: 
1.619     albertel  460:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  461:     $env_loaded=1;
1.783     albertel  462:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   463:         &delenv($expired_key);
1.374     www       464:     }
1.1       albertel  465: }
                    466: 
1.916     albertel  467: # ---------------------------------------------------- Check for valid session 
                    468: sub check_for_valid_session {
                    469:     my ($r) = @_;
                    470:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    471:     my $lonid=$cookies{'lonID'};
                    472:     return undef if (!$lonid);
                    473: 
                    474:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    475:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    476:     return undef if (!-e "$lonidsdir/$handle.id");
                    477: 
1.917     albertel  478:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    479:     return undef if (!$opened);
1.916     albertel  480: 
                    481:     flock($idf,LOCK_SH);
                    482:     my %disk_env;
                    483:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    484: 	    &GDBM_READER(),0640)) {
                    485: 	return undef;	
                    486:     }
                    487: 
                    488:     if (!defined($disk_env{'user.name'})
                    489: 	|| !defined($disk_env{'user.domain'})) {
                    490: 	return undef;
                    491:     }
                    492:     return $handle;
                    493: }
                    494: 
1.830     albertel  495: sub timed_flock {
                    496:     my ($file,$lock_type) = @_;
                    497:     my $failed=0;
                    498:     eval {
                    499: 	local $SIG{__DIE__}='DEFAULT';
                    500: 	local $SIG{ALRM}=sub {
                    501: 	    $failed=1;
                    502: 	    die("failed lock");
                    503: 	};
                    504: 	alarm(13);
                    505: 	flock($file,$lock_type);
                    506: 	alarm(0);
                    507:     };
                    508:     if ($failed) {
                    509: 	return undef;
                    510:     } else {
                    511: 	return 1;
                    512:     }
                    513: }
                    514: 
1.5       www       515: # ---------------------------------------------------------- Append Environment
                    516: 
                    517: sub appenv {
1.949     raeburn   518:     my ($newenv,$roles) = @_;
                    519:     if (ref($newenv) eq 'HASH') {
                    520:         foreach my $key (keys(%{$newenv})) {
                    521:             my $refused = 0;
                    522: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    523:                 $refused = 1;
                    524:                 if (ref($roles) eq 'ARRAY') {
                    525:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    526:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    527:                         $refused = 0;
                    528:                     }
                    529:                 }
                    530:             }
                    531:             if ($refused) {
                    532:                 &logthis("<font color=\"blue\">WARNING: ".
                    533:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    534:                          .'</font>');
                    535: 	        delete($newenv->{$key});
                    536:             } else {
                    537:                 $env{$key}=$newenv->{$key};
                    538:             }
                    539:         }
                    540:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    541:         if ($opened
                    542: 	    && &timed_flock($env_file,LOCK_EX)
                    543: 	    &&
                    544: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    545: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    546: 	    while (my ($key,$value) = each(%{$newenv})) {
                    547: 	        $disk_env{$key} = $value;
                    548: 	    }
                    549: 	    untie(%disk_env);
1.35      www       550:         }
1.191     harris41  551:     }
1.56      www       552:     return 'ok';
                    553: }
                    554: # ----------------------------------------------------- Delete from Environment
                    555: 
                    556: sub delenv {
1.987     raeburn   557:     my ($delthis,$regexp) = @_;
1.56      www       558:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  559:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       560:                 "Attempt to delete from environment ".$delthis);
                    561:         return 'error';
                    562:     }
1.917     albertel  563:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    564:     if ($opened
1.915     albertel  565: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  566: 	&&
                    567: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    568: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  569: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   570: 	    if ($regexp) {
                    571:                 if ($key=~/^$delthis/) {
                    572:                     delete($env{$key});
                    573:                     delete($disk_env{$key});
                    574:                 } 
                    575:             } else {
                    576:                 if ($key=~/^\Q$delthis\E/) {
                    577: 		    delete($env{$key});
                    578: 		    delete($disk_env{$key});
                    579: 	        }
                    580:             }
1.448     albertel  581: 	}
1.783     albertel  582: 	untie(%disk_env);
1.5       www       583:     }
                    584:     return 'ok';
1.369     albertel  585: }
                    586: 
1.790     albertel  587: sub get_env_multiple {
                    588:     my ($name) = @_;
                    589:     my @values;
                    590:     if (defined($env{$name})) {
                    591:         # exists is it an array
                    592:         if (ref($env{$name})) {
                    593:             @values=@{ $env{$name} };
                    594:         } else {
                    595:             $values[0]=$env{$name};
                    596:         }
                    597:     }
                    598:     return(@values);
                    599: }
                    600: 
1.958     www       601: # ------------------------------------------------------------------- Locking
                    602: 
                    603: sub set_lock {
                    604:     my ($text)=@_;
                    605:     $locknum++;
                    606:     my $id=$$.'-'.$locknum;
                    607:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    608:              'session.lock.'.$id => $text});
                    609:     return $id;
                    610: }
                    611: 
                    612: sub get_locks {
                    613:     my $num=0;
                    614:     my %texts=();
                    615:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    616:        if ($lock=~/\w/) {
                    617:           $num++;
                    618:           $texts{$lock}=$env{'session.lock.'.$lock};
                    619:        }
                    620:    }
                    621:    return ($num,%texts);
                    622: }
                    623: 
                    624: sub remove_lock {
                    625:     my ($id)=@_;
                    626:     my $newlocks='';
                    627:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    628:        if (($lock=~/\w/) && ($lock ne $id)) {
                    629:           $newlocks.=','.$lock;
                    630:        }
                    631:     }
                    632:     &appenv({'session.locks' => $newlocks});
                    633:     &delenv('session.lock.'.$id);
                    634: }
                    635: 
                    636: sub remove_all_locks {
                    637:     my $activelocks=$env{'session.locks'};
                    638:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    639:        if ($lock=~/\w/) {
                    640:           &remove_lock($lock);
                    641:        }
                    642:     }
                    643: }
                    644: 
                    645: 
1.369     albertel  646: # ------------------------------------------ Find out current server userload
                    647: sub userload {
                    648:     my $numusers=0;
                    649:     {
                    650: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    651: 	my $filename;
                    652: 	my $curtime=time;
                    653: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  654: 	    next if ($filename eq '.' || $filename eq '..');
                    655: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  656: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  657: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  658: 	}
                    659: 	closedir(LONIDS);
                    660:     }
                    661:     my $userloadpercent=0;
                    662:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    663:     if ($maxuserload) {
1.371     albertel  664: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  665:     }
1.372     albertel  666:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  667:     return $userloadpercent;
1.283     www       668: }
                    669: 
                    670: # ------------------------------------------ Fight off request when overloaded
                    671: 
                    672: sub overloaderror {
                    673:     my ($r,$checkserver)=@_;
                    674:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    675:     my $loadavg;
                    676:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  677:        open(my $loadfile,'/proc/loadavg');
1.283     www       678:        $loadavg=<$loadfile>;
                    679:        $loadavg =~ s/\s.*//g;
1.285     matthew   680:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  681:        close($loadfile);
1.283     www       682:     } else {
                    683:        $loadavg=&reply('load',$checkserver);
                    684:     }
1.285     matthew   685:     my $overload=$loadavg-100;
1.283     www       686:     if ($overload>0) {
1.285     matthew   687: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       688:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       689:         return 413;
1.283     www       690:     }    
                    691:     return '';
1.5       www       692: }
1.1       albertel  693: 
                    694: # ------------------------------ Find server with least workload from spare.tab
1.11      www       695: 
1.1       albertel  696: sub spareserver {
1.670     albertel  697:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  698:     my $spare_server;
1.370     albertel  699:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  700:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    701:                                                      :  $userloadpercent;
                    702:     
                    703:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    704: 	($spare_server, $lowest_load) =
                    705: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    706:     }
                    707: 
                    708:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    709: 
                    710:     if (!$found_server) {
                    711: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    712: 	    ($spare_server, $lowest_load) =
                    713: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    714: 	}
                    715:     }
                    716: 
                    717:     if (!$want_server_name) {
1.968     raeburn   718:         my $protocol = 'http';
                    719:         if ($protocol{$spare_server} eq 'https') {
                    720:             $protocol = $protocol{$spare_server};
                    721:         }
1.1001    raeburn   722:         if (defined($spare_server)) {
                    723:             my $hostname = &hostname($spare_server);
                    724:             if (defined($hostname)) {  
                    725: 	        $spare_server = $protocol.'://'.$hostname;
                    726:             }
                    727:         }
1.784     albertel  728:     }
                    729:     return $spare_server;
                    730: }
                    731: 
                    732: sub compare_server_load {
                    733:     my ($try_server, $spare_server, $lowest_load) = @_;
                    734: 
                    735:     my $loadans     = &reply('load',    $try_server);
                    736:     my $userloadans = &reply('userload',$try_server);
                    737: 
                    738:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    739: 	next; #didn't get a number from the server
                    740:     }
                    741: 
                    742:     my $load;
                    743:     if ($loadans =~ /\d/) {
                    744: 	if ($userloadans =~ /\d/) {
                    745: 	    #both are numbers, pick the bigger one
                    746: 	    $load = ($loadans > $userloadans) ? $loadans 
                    747: 		                              : $userloadans;
1.411     albertel  748: 	} else {
1.784     albertel  749: 	    $load = $loadans;
1.411     albertel  750: 	}
1.784     albertel  751:     } else {
                    752: 	$load = $userloadans;
                    753:     }
                    754: 
                    755:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    756: 	$spare_server = $try_server;
                    757: 	$lowest_load  = $load;
1.370     albertel  758:     }
1.784     albertel  759:     return ($spare_server,$lowest_load);
1.202     matthew   760: }
1.914     albertel  761: 
                    762: # --------------------------- ask offload servers if user already has a session
                    763: sub find_existing_session {
                    764:     my ($udom,$uname) = @_;
                    765:     foreach my $try_server (@{ $spareid{'primary'} },
                    766: 			    @{ $spareid{'default'} }) {
                    767: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    768:     }
                    769:     return;
                    770: }
                    771: 
                    772: # -------------------------------- ask if server already has a session for user
                    773: sub has_user_session {
                    774:     my ($lonid,$udom,$uname) = @_;
                    775:     my $result = &reply(join(':','userhassession',
                    776: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    777:     return 1 if ($result eq 'ok');
                    778: 
                    779:     return 0;
                    780: }
                    781: 
1.202     matthew   782: # --------------------------------------------- Try to change a user's password
                    783: 
                    784: sub changepass {
1.799     raeburn   785:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   786:     $currentpass = &escape($currentpass);
                    787:     $newpass     = &escape($newpass);
1.1030    raeburn   788:     my $lonhost = $perlvar{'lonHostID'};
                    789:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   790: 		       $server);
                    791:     if (! $answer) {
                    792: 	&logthis("No reply on password change request to $server ".
                    793: 		 "by $uname in domain $udom.");
                    794:     } elsif ($answer =~ "^ok") {
                    795:         &logthis("$uname in $udom successfully changed their password ".
                    796: 		 "on $server.");
                    797:     } elsif ($answer =~ "^pwchange_failure") {
                    798: 	&logthis("$uname in $udom was unable to change their password ".
                    799: 		 "on $server.  The action was blocked by either lcpasswd ".
                    800: 		 "or pwchange");
                    801:     } elsif ($answer =~ "^non_authorized") {
                    802:         &logthis("$uname in $udom did not get their password correct when ".
                    803: 		 "attempting to change it on $server.");
                    804:     } elsif ($answer =~ "^auth_mode_error") {
                    805:         &logthis("$uname in $udom attempted to change their password despite ".
                    806: 		 "not being locally or internally authenticated on $server.");
                    807:     } elsif ($answer =~ "^unknown_user") {
                    808:         &logthis("$uname in $udom attempted to change their password ".
                    809: 		 "on $server but were unable to because $server is not ".
                    810: 		 "their home server.");
                    811:     } elsif ($answer =~ "^refused") {
                    812: 	&logthis("$server refused to change $uname in $udom password because ".
                    813: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   814:     } elsif ($answer =~ "invalid_client") {
                    815:         &logthis("$server refused to change $uname in $udom password because ".
                    816:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   817:     }
                    818:     return $answer;
1.1       albertel  819: }
                    820: 
1.169     harris41  821: # ----------------------- Try to determine user's current authentication scheme
                    822: 
                    823: sub queryauthenticate {
                    824:     my ($uname,$udom)=@_;
1.456     albertel  825:     my $uhome=&homeserver($uname,$udom);
                    826:     if (!$uhome) {
                    827: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    828: 	return 'no_host';
                    829:     }
                    830:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    831:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    832: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  833:     }
1.456     albertel  834:     return $answer;
1.169     harris41  835: }
                    836: 
1.1       albertel  837: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       838: 
1.1       albertel  839: sub authenticate {
1.952     raeburn   840:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  841:     $upass=&escape($upass);
                    842:     $uname= &LONCAPA::clean_username($uname);
1.836     www       843:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   844:     my $newhome;
1.836     www       845:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    846: # Maybe the machine was offline and only re-appeared again recently?
                    847:         &reconlonc();
                    848: # One more
1.952     raeburn   849: 	$uhome=&homeserver($uname,$udom,1);
                    850:         if (($uhome eq 'no_host') && $checkdefauth) {
                    851:             if (defined(&domain($udom,'primary'))) {
                    852:                 $newhome=&domain($udom,'primary');
                    853:             }
                    854:             if ($newhome ne '') {
                    855:                 $uhome = $newhome;
                    856:             }
                    857:         }
1.836     www       858: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    859: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   860: 	    return 'no_host';
                    861:         }
1.1       albertel  862:     }
1.952     raeburn   863:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  864:     if ($answer eq 'authorized') {
1.952     raeburn   865:         if ($newhome) {
                    866:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    867:             return 'no_account_on_host'; 
                    868:         } else {
                    869:             &logthis("User $uname at $udom authorized by $uhome");
                    870:             return $uhome;
                    871:         }
1.471     albertel  872:     }
                    873:     if ($answer eq 'non_authorized') {
                    874: 	&logthis("User $uname at $udom rejected by $uhome");
                    875: 	return 'no_host'; 
1.9       www       876:     }
1.471     albertel  877:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  878:     return 'no_host';
                    879: }
                    880: 
                    881: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       882: 
1.599     albertel  883: my %homecache;
1.1       albertel  884: sub homeserver {
1.230     stredwic  885:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  886:     my $index="$uname:$udom";
1.426     albertel  887: 
1.599     albertel  888:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  889: 
                    890:     my %servers = &get_servers($udom,'library');
                    891:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  892:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  893: 		 exists($badServerCache{$tryserver}));
1.841     albertel  894: 
                    895: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    896: 	if ($answer eq 'found') {
                    897: 	    delete($badServerCache{$tryserver}); 
                    898: 	    return $homecache{$index}=$tryserver;
                    899: 	} elsif ($answer eq 'no_host') {
                    900: 	    $badServerCache{$tryserver}=1;
                    901: 	}
1.1       albertel  902:     }    
                    903:     return 'no_host';
1.70      www       904: }
                    905: 
                    906: # ------------------------------------- Find the usernames behind a list of IDs
                    907: 
                    908: sub idget {
                    909:     my ($udom,@ids)=@_;
                    910:     my %returnhash=();
                    911:     
1.841     albertel  912:     my %servers = &get_servers($udom,'library');
                    913:     foreach my $tryserver (keys(%servers)) {
                    914: 	my $idlist=join('&',@ids);
                    915: 	$idlist=~tr/A-Z/a-z/; 
                    916: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    917: 	my @answer=();
                    918: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    919: 	    @answer=split(/\&/,$reply);
                    920: 	}                    ;
                    921: 	my $i;
                    922: 	for ($i=0;$i<=$#ids;$i++) {
                    923: 	    if ($answer[$i]) {
                    924: 		$returnhash{$ids[$i]}=$answer[$i];
                    925: 	    } 
                    926: 	}
                    927:     } 
1.70      www       928:     return %returnhash;
                    929: }
                    930: 
                    931: # ------------------------------------- Find the IDs behind a list of usernames
                    932: 
                    933: sub idrget {
                    934:     my ($udom,@unames)=@_;
                    935:     my %returnhash=();
1.800     albertel  936:     foreach my $uname (@unames) {
                    937:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  938:     }
1.70      www       939:     return %returnhash;
                    940: }
                    941: 
                    942: # ------------------------------- Store away a list of names and associated IDs
                    943: 
                    944: sub idput {
                    945:     my ($udom,%ids)=@_;
                    946:     my %servers=();
1.800     albertel  947:     foreach my $uname (keys(%ids)) {
                    948: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    949:         my $uhom=&homeserver($uname,$udom);
1.70      www       950:         if ($uhom ne 'no_host') {
1.800     albertel  951:             my $id=&escape($ids{$uname});
1.70      www       952:             $id=~tr/A-Z/a-z/;
1.800     albertel  953:             my $esc_unam=&escape($uname);
1.70      www       954: 	    if ($servers{$uhom}) {
1.800     albertel  955: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       956:             } else {
1.800     albertel  957:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       958:             }
                    959:         }
1.191     harris41  960:     }
1.800     albertel  961:     foreach my $server (keys(%servers)) {
                    962:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  963:     }
1.344     www       964: }
                    965: 
1.1023    raeburn   966: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn   967: sub dump_dom {
1.1023    raeburn   968:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn   969:     if (!$udom) {
                    970:         $udom=$env{'user.domain'};
                    971:     }
                    972:     my %returnhash;
1.1023    raeburn   973:     if ($udom) {
                    974:         my $uname = &get_domainconfiguser($udom);
                    975:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn   976:     }
                    977:     return %returnhash;
                    978: }
                    979: 
1.1023    raeburn   980: # ------------------------------------------ get items from domain db files   
1.806     raeburn   981: 
                    982: sub get_dom {
1.860     raeburn   983:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   984:     my $items='';
                    985:     foreach my $item (@$storearr) {
                    986:         $items.=&escape($item).'&';
                    987:     }
                    988:     $items=~s/\&$//;
1.860     raeburn   989:     if (!$udom) {
                    990:         $udom=$env{'user.domain'};
                    991:         if (defined(&domain($udom,'primary'))) {
                    992:             $uhome=&domain($udom,'primary');
                    993:         } else {
1.874     albertel  994:             undef($uhome);
1.860     raeburn   995:         }
                    996:     } else {
                    997:         if (!$uhome) {
                    998:             if (defined(&domain($udom,'primary'))) {
                    999:                 $uhome=&domain($udom,'primary');
                   1000:             }
                   1001:         }
                   1002:     }
                   1003:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1004:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1005:         my %returnhash;
1.875     albertel 1006:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1007:             return %returnhash;
                   1008:         }
1.806     raeburn  1009:         my @pairs=split(/\&/,$rep);
                   1010:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1011:             return @pairs;
                   1012:         }
                   1013:         my $i=0;
                   1014:         foreach my $item (@$storearr) {
                   1015:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1016:             $i++;
                   1017:         }
                   1018:         return %returnhash;
                   1019:     } else {
1.880     banghart 1020:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1021:     }
                   1022: }
                   1023: 
                   1024: # -------------------------------------------- put items in domain db files 
                   1025: 
                   1026: sub put_dom {
1.860     raeburn  1027:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1028:     if (!$udom) {
                   1029:         $udom=$env{'user.domain'};
                   1030:         if (defined(&domain($udom,'primary'))) {
                   1031:             $uhome=&domain($udom,'primary');
                   1032:         } else {
1.874     albertel 1033:             undef($uhome);
1.860     raeburn  1034:         }
                   1035:     } else {
                   1036:         if (!$uhome) {
                   1037:             if (defined(&domain($udom,'primary'))) {
                   1038:                 $uhome=&domain($udom,'primary');
                   1039:             }
                   1040:         }
                   1041:     } 
                   1042:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1043:         my $items='';
                   1044:         foreach my $item (keys(%$storehash)) {
                   1045:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1046:         }
                   1047:         $items=~s/\&$//;
                   1048:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1049:     } else {
1.860     raeburn  1050:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1051:     }
                   1052: }
                   1053: 
1.1023    raeburn  1054: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1055: sub newput_dom {
1.1023    raeburn  1056:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1057:     my $result;
                   1058:     if (!$udom) {
                   1059:         $udom=$env{'user.domain'};
                   1060:     }
1.1023    raeburn  1061:     if ($udom) {
                   1062:         my $uname = &get_domainconfiguser($udom);
                   1063:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1064:     }
                   1065:     return $result;
                   1066: }
                   1067: 
1.1023    raeburn  1068: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1069: sub del_dom {
1.1023    raeburn  1070:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1071:     if (ref($storearr) eq 'ARRAY') {
                   1072:         if (!$udom) {
                   1073:             $udom=$env{'user.domain'};
                   1074:         }
1.1023    raeburn  1075:         if ($udom) {
                   1076:             my $uname = &get_domainconfiguser($udom); 
                   1077:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1078:         }
                   1079:     }
                   1080: }
                   1081: 
1.1023    raeburn  1082: # ----------------------------------construct domainconfig user for a domain 
                   1083: sub get_domainconfiguser {
                   1084:     my ($udom) = @_;
                   1085:     return $udom.'-domainconfig';
                   1086: }
                   1087: 
1.837     raeburn  1088: sub retrieve_inst_usertypes {
                   1089:     my ($udom) = @_;
                   1090:     my (%returnhash,@order);
1.989     raeburn  1091:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1092:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1093:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1094:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1095:         @order = @{$domdefs{'inststatusorder'}};
                   1096:     } else {
                   1097:         if (defined(&domain($udom,'primary'))) {
                   1098:             my $uhome=&domain($udom,'primary');
                   1099:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1100:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1101:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1102:                 return (\%returnhash,\@order);
                   1103:             }
                   1104:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1105:             my @pairs=split(/\&/,$hashitems);
                   1106:             foreach my $item (@pairs) {
                   1107:                 my ($key,$value)=split(/=/,$item,2);
                   1108:                 $key = &unescape($key);
                   1109:                 next if ($key =~ /^error: 2 /);
                   1110:                 $returnhash{$key}=&thaw_unescape($value);
                   1111:             }
                   1112:             my @esc_order = split(/\&/,$orderitems);
                   1113:             foreach my $item (@esc_order) {
                   1114:                 push(@order,&unescape($item));
                   1115:             }
                   1116:         } else {
                   1117:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1118:         }
                   1119:     }
                   1120:     return (\%returnhash,\@order);
                   1121: }
                   1122: 
1.868     raeburn  1123: sub is_domainimage {
                   1124:     my ($url) = @_;
                   1125:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1126:         if (&domain($1) ne '') {
                   1127:             return '1';
                   1128:         }
                   1129:     }
                   1130:     return;
                   1131: }
                   1132: 
1.899     raeburn  1133: sub inst_directory_query {
                   1134:     my ($srch) = @_;
                   1135:     my $udom = $srch->{'srchdomain'};
                   1136:     my %results;
                   1137:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1138:     my $outcome;
1.899     raeburn  1139:     if ($homeserver ne '') {
1.904     albertel 1140: 	my $queryid=&reply("querysend:instdirsearch:".
                   1141: 			   &escape($srch->{'srchby'}).':'.
                   1142: 			   &escape($srch->{'srchterm'}).':'.
                   1143: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1144: 	my $host=&hostname($homeserver);
                   1145: 	if ($queryid !~/^\Q$host\E\_/) {
                   1146: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1147: 	    return;
                   1148: 	}
                   1149: 	my $response = &get_query_reply($queryid);
                   1150: 	my $maxtries = 5;
                   1151: 	my $tries = 1;
                   1152: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1153: 	    $response = &get_query_reply($queryid);
                   1154: 	    $tries ++;
                   1155: 	}
                   1156: 
                   1157:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1158:             if ($response eq 'unavailable') {
                   1159:                 $outcome = $response;
                   1160:             } else {
                   1161:                 $outcome = 'ok';
                   1162:                 my @matches = split(/\n/,$response);
                   1163:                 foreach my $match (@matches) {
                   1164:                     my ($key,$value) = split(/=/,$match);
                   1165:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1166:                 }
1.899     raeburn  1167:             }
                   1168:         }
                   1169:     }
1.909     raeburn  1170:     return ($outcome,%results);
1.899     raeburn  1171: }
                   1172: 
                   1173: sub usersearch {
                   1174:     my ($srch) = @_;
                   1175:     my $dom = $srch->{'srchdomain'};
                   1176:     my %results;
                   1177:     my %libserv = &all_library();
                   1178:     my $query = 'usersearch';
                   1179:     foreach my $tryserver (keys(%libserv)) {
                   1180:         if (&host_domain($tryserver) eq $dom) {
                   1181:             my $host=&hostname($tryserver);
                   1182:             my $queryid=
1.911     raeburn  1183:                 &reply("querysend:".&escape($query).':'.
                   1184:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1185:                        &escape($srch->{'srchtype'}).':'.
                   1186:                        &escape($srch->{'srchterm'}),$tryserver);
                   1187:             if ($queryid !~/^\Q$host\E\_/) {
                   1188:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1189:                 next;
1.899     raeburn  1190:             }
                   1191:             my $reply = &get_query_reply($queryid);
                   1192:             my $maxtries = 1;
                   1193:             my $tries = 1;
                   1194:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1195:                 $reply = &get_query_reply($queryid);
                   1196:                 $tries ++;
                   1197:             }
                   1198:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1199:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1200:             } else {
1.911     raeburn  1201:                 my @matches;
                   1202:                 if ($reply =~ /\n/) {
                   1203:                     @matches = split(/\n/,$reply);
                   1204:                 } else {
                   1205:                     @matches = split(/\&/,$reply);
                   1206:                 }
1.899     raeburn  1207:                 foreach my $match (@matches) {
                   1208:                     my ($uname,$udom,%userhash);
1.911     raeburn  1209:                     foreach my $entry (split(/:/,$match)) {
                   1210:                         my ($key,$value) =
                   1211:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1212:                         $userhash{$key} = $value;
                   1213:                         if ($key eq 'username') {
                   1214:                             $uname = $value;
                   1215:                         } elsif ($key eq 'domain') {
                   1216:                             $udom = $value;
1.911     raeburn  1217:                         }
1.899     raeburn  1218:                     }
                   1219:                     $results{$uname.':'.$udom} = \%userhash;
                   1220:                 }
                   1221:             }
                   1222:         }
                   1223:     }
                   1224:     return %results;
                   1225: }
                   1226: 
1.912     raeburn  1227: sub get_instuser {
                   1228:     my ($udom,$uname,$id) = @_;
                   1229:     my $homeserver = &domain($udom,'primary');
                   1230:     my ($outcome,%results);
                   1231:     if ($homeserver ne '') {
                   1232:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1233:                            &escape($id).':'.&escape($udom),$homeserver);
                   1234:         my $host=&hostname($homeserver);
                   1235:         if ($queryid !~/^\Q$host\E\_/) {
                   1236:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1237:             return;
                   1238:         }
                   1239:         my $response = &get_query_reply($queryid);
                   1240:         my $maxtries = 5;
                   1241:         my $tries = 1;
                   1242:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1243:             $response = &get_query_reply($queryid);
                   1244:             $tries ++;
                   1245:         }
                   1246:         if (!&error($response) && $response ne 'refused') {
                   1247:             if ($response eq 'unavailable') {
                   1248:                 $outcome = $response;
                   1249:             } else {
                   1250:                 $outcome = 'ok';
                   1251:                 my @matches = split(/\n/,$response);
                   1252:                 foreach my $match (@matches) {
                   1253:                     my ($key,$value) = split(/=/,$match);
                   1254:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1255:                 }
                   1256:             }
                   1257:         }
                   1258:     }
                   1259:     my %userinfo;
                   1260:     if (ref($results{$uname}) eq 'HASH') {
                   1261:         %userinfo = %{$results{$uname}};
                   1262:     } 
                   1263:     return ($outcome,%userinfo);
                   1264: }
                   1265: 
                   1266: sub inst_rulecheck {
1.923     raeburn  1267:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1268:     my %returnhash;
                   1269:     if ($udom ne '') {
                   1270:         if (ref($rules) eq 'ARRAY') {
                   1271:             @{$rules} = map {&escape($_);} (@{$rules});
                   1272:             my $rulestr = join(':',@{$rules});
                   1273:             my $homeserver=&domain($udom,'primary');
                   1274:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1275:                 my $response;
                   1276:                 if ($item eq 'username') {                
                   1277:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1278:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1279:                                               $homeserver));
1.923     raeburn  1280:                 } elsif ($item eq 'id') {
                   1281:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1282:                                               ':'.&escape($id).':'.$rulestr,
                   1283:                                               $homeserver));
1.945     raeburn  1284:                 } elsif ($item eq 'selfcreate') {
                   1285:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1286:                                                &escape($udom).':'.&escape($uname).
                   1287:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1288:                 }
1.912     raeburn  1289:                 if ($response ne 'refused') {
                   1290:                     my @pairs=split(/\&/,$response);
                   1291:                     foreach my $item (@pairs) {
                   1292:                         my ($key,$value)=split(/=/,$item,2);
                   1293:                         $key = &unescape($key);
                   1294:                         next if ($key =~ /^error: 2 /);
                   1295:                         $returnhash{$key}=&thaw_unescape($value);
                   1296:                     }
                   1297:                 }
                   1298:             }
                   1299:         }
                   1300:     }
                   1301:     return %returnhash;
                   1302: }
                   1303: 
                   1304: sub inst_userrules {
1.923     raeburn  1305:     my ($udom,$check) = @_;
1.912     raeburn  1306:     my (%ruleshash,@ruleorder);
                   1307:     if ($udom ne '') {
                   1308:         my $homeserver=&domain($udom,'primary');
                   1309:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1310:             my $response;
                   1311:             if ($check eq 'id') {
                   1312:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1313:                                  $homeserver);
1.943     raeburn  1314:             } elsif ($check eq 'email') {
                   1315:                 $response=&reply('instemailrules:'.&escape($udom),
                   1316:                                  $homeserver);
1.923     raeburn  1317:             } else {
                   1318:                 $response=&reply('instuserrules:'.&escape($udom),
                   1319:                                  $homeserver);
                   1320:             }
1.912     raeburn  1321:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1322:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1323:                 ($response ne 'no_such_host')) {
                   1324:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1325:                 my @pairs=split(/\&/,$hashitems);
                   1326:                 foreach my $item (@pairs) {
                   1327:                     my ($key,$value)=split(/=/,$item,2);
                   1328:                     $key = &unescape($key);
                   1329:                     next if ($key =~ /^error: 2 /);
                   1330:                     $ruleshash{$key}=&thaw_unescape($value);
                   1331:                 }
                   1332:                 my @esc_order = split(/\&/,$orderitems);
                   1333:                 foreach my $item (@esc_order) {
                   1334:                     push(@ruleorder,&unescape($item));
                   1335:                 }
                   1336:             }
                   1337:         }
                   1338:     }
                   1339:     return (\%ruleshash,\@ruleorder);
                   1340: }
                   1341: 
1.976     raeburn  1342: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1343: 
                   1344: sub get_domain_defaults {
                   1345:     my ($domain) = @_;
                   1346:     my $cachetime = 60*60*24;
                   1347:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1348:     if (defined($cached)) {
                   1349:         if (ref($result) eq 'HASH') {
                   1350:             return %{$result};
                   1351:         }
                   1352:     }
                   1353:     my %domdefaults;
                   1354:     my %domconfig =
1.989     raeburn  1355:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
                   1356:                                   'requestcourses','inststatus'],$domain);
1.943     raeburn  1357:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1358:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1359:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1360:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1361:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1362:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1363:     } else {
                   1364:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1365:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1366:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1367:     }
1.976     raeburn  1368:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1369:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1370:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1371:         } else {
                   1372:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1373:         } 
                   1374:         my @usertools = ('aboutme','blog','portfolio');
                   1375:         foreach my $item (@usertools) {
                   1376:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1377:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1378:             }
                   1379:         }
                   1380:     }
1.985     raeburn  1381:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1382:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1383:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1384:         }
                   1385:     }
1.989     raeburn  1386:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1387:         foreach my $item ('inststatustypes','inststatusorder') {
                   1388:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1389:         }
                   1390:     }
1.943     raeburn  1391:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1392:                                   $cachetime);
                   1393:     return %domdefaults;
                   1394: }
                   1395: 
1.344     www      1396: # --------------------------------------------------- Assign a key to a student
                   1397: 
                   1398: sub assign_access_key {
1.364     www      1399: #
                   1400: # a valid key looks like uname:udom#comments
                   1401: # comments are being appended
                   1402: #
1.498     www      1403:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1404:     $kdom=
1.620     albertel 1405:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1406:     $knum=
1.620     albertel 1407:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1408:     $cdom=
1.620     albertel 1409:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1410:     $cnum=
1.620     albertel 1411:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1412:     $udom=$env{'user.name'} unless (defined($udom));
                   1413:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1414:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1415:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1416:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1417:                                                   # assigned to this person
                   1418:                                                   # - this should not happen,
1.345     www      1419:                                                   # unless something went wrong
                   1420:                                                   # the first time around
                   1421: # ready to assign
1.364     www      1422:         $logentry=$1.'; '.$logentry;
1.496     www      1423:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1424:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1425: # key now belongs to user
1.346     www      1426: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1427:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1428:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1429:                 return 'ok';
                   1430:             } else {
                   1431:                 return 
                   1432:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1433: 	    }
                   1434:         } else {
                   1435:             return 'error: Could not assign key, try again later.';
                   1436:         }
1.364     www      1437:     } elsif (!$existing{$ckey}) {
1.345     www      1438: # the key does not exist
                   1439: 	return 'error: The key does not exist';
                   1440:     } else {
                   1441: # the key is somebody else's
                   1442: 	return 'error: The key is already in use';
                   1443:     }
1.344     www      1444: }
                   1445: 
1.364     www      1446: # ------------------------------------------ put an additional comment on a key
                   1447: 
                   1448: sub comment_access_key {
                   1449: #
                   1450: # a valid key looks like uname:udom#comments
                   1451: # comments are being appended
                   1452: #
                   1453:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1454:     $cdom=
1.620     albertel 1455:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1456:     $cnum=
1.620     albertel 1457:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1458:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1459:     if ($existing{$ckey}) {
                   1460:         $existing{$ckey}.='; '.$logentry;
                   1461: # ready to assign
1.367     www      1462:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1463:                                                  $cdom,$cnum) eq 'ok') {
                   1464: 	    return 'ok';
                   1465:         } else {
                   1466: 	    return 'error: Count not store comment.';
                   1467:         }
                   1468:     } else {
                   1469: # the key does not exist
                   1470: 	return 'error: The key does not exist';
                   1471:     }
                   1472: }
                   1473: 
1.344     www      1474: # ------------------------------------------------------ Generate a set of keys
                   1475: 
                   1476: sub generate_access_keys {
1.364     www      1477:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1478:     $cdom=
1.620     albertel 1479:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1480:     $cnum=
1.620     albertel 1481:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1482:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1483:     unless (($cdom) && ($cnum)) { return 0; }
                   1484:     if ($number>10000) { return 0; }
                   1485:     sleep(2); # make sure don't get same seed twice
                   1486:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1487:     my $total=0;
                   1488:     for (my $i=1;$i<=$number;$i++) {
                   1489:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1490:                   sprintf("%lx",int(100000*rand)).'-'.
                   1491:                   sprintf("%lx",int(100000*rand));
                   1492:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1493:        $newkey=~s/0/h/g; # and also 0 and O
                   1494:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1495:        if ($existing{$newkey}) {
                   1496:            $i--;
                   1497:        } else {
1.364     www      1498: 	  if (&put('accesskeys',
                   1499:               { $newkey => '# generated '.localtime().
1.620     albertel 1500:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1501:                            '; '.$logentry },
                   1502: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1503:               $total++;
                   1504: 	  }
                   1505:        }
                   1506:     }
1.620     albertel 1507:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1508:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1509:     return $total;
                   1510: }
                   1511: 
                   1512: # ------------------------------------------------------- Validate an accesskey
                   1513: 
                   1514: sub validate_access_key {
                   1515:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1516:     $cdom=
1.620     albertel 1517:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1518:     $cnum=
1.620     albertel 1519:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1520:     $udom=$env{'user.domain'} unless (defined($udom));
                   1521:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1522:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1523:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1524: }
                   1525: 
                   1526: # ------------------------------------- Find the section of student in a course
1.652     albertel 1527: sub devalidate_getsection_cache {
                   1528:     my ($udom,$unam,$courseid)=@_;
                   1529:     my $hashid="$udom:$unam:$courseid";
                   1530:     &devalidate_cache_new('getsection',$hashid);
                   1531: }
1.298     matthew  1532: 
1.815     albertel 1533: sub courseid_to_courseurl {
                   1534:     my ($courseid) = @_;
                   1535:     #already url style courseid
                   1536:     return $courseid if ($courseid =~ m{^/});
                   1537: 
                   1538:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1539: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1540: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1541: 	return "/$cdom/$cnum";
                   1542:     }
                   1543: 
                   1544:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1545:     if (exists($courseinfo{'num'})) {
                   1546: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1547:     }
                   1548: 
                   1549:     return undef;
                   1550: }
                   1551: 
1.298     matthew  1552: sub getsection {
                   1553:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1554:     my $cachetime=1800;
1.551     albertel 1555: 
                   1556:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1557:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1558:     if (defined($cached)) { return $result; }
                   1559: 
1.298     matthew  1560:     my %Pending; 
                   1561:     my %Expired;
                   1562:     #
                   1563:     # Each role can either have not started yet (pending), be active, 
                   1564:     #    or have expired.
                   1565:     #
                   1566:     # If there is an active role, we are done.
                   1567:     #
                   1568:     # If there is more than one role which has not started yet, 
                   1569:     #     choose the one which will start sooner
                   1570:     # If there is one role which has not started yet, return it.
                   1571:     #
                   1572:     # If there is more than one expired role, choose the one which ended last.
                   1573:     # If there is a role which has expired, return it.
                   1574:     #
1.815     albertel 1575:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1576:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1577:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1578:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1579:         my $section=$1;
                   1580:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1581:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1582:         my $now=time;
1.548     albertel 1583:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1584:             $Expired{$end}=$section;
                   1585:             next;
                   1586:         }
1.548     albertel 1587:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1588:             $Pending{$start}=$section;
                   1589:             next;
                   1590:         }
1.599     albertel 1591:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1592:     }
                   1593:     #
                   1594:     # Presumedly there will be few matching roles from the above
                   1595:     # loop and the sorting time will be negligible.
                   1596:     if (scalar(keys(%Pending))) {
                   1597:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1598:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1599:     } 
                   1600:     if (scalar(keys(%Expired))) {
                   1601:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1602:         my $time = pop(@sorted);
1.599     albertel 1603:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1604:     }
1.599     albertel 1605:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1606: }
1.70      www      1607: 
1.599     albertel 1608: sub save_cache {
                   1609:     &purge_remembered();
1.722     albertel 1610:     #&Apache::loncommon::validate_page();
1.620     albertel 1611:     undef(%env);
1.780     albertel 1612:     undef($env_loaded);
1.599     albertel 1613: }
1.452     albertel 1614: 
1.599     albertel 1615: my $to_remember=-1;
                   1616: my %remembered;
                   1617: my %accessed;
                   1618: my $kicks=0;
                   1619: my $hits=0;
1.849     albertel 1620: sub make_key {
                   1621:     my ($name,$id) = @_;
1.872     albertel 1622:     if (length($id) > 65 
                   1623: 	&& length(&escape($id)) > 200) {
                   1624: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1625:     }
1.849     albertel 1626:     return &escape($name.':'.$id);
                   1627: }
                   1628: 
1.599     albertel 1629: sub devalidate_cache_new {
                   1630:     my ($name,$id,$debug) = @_;
                   1631:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1632:     $id=&make_key($name,$id);
1.599     albertel 1633:     $memcache->delete($id);
                   1634:     delete($remembered{$id});
                   1635:     delete($accessed{$id});
                   1636: }
                   1637: 
                   1638: sub is_cached_new {
                   1639:     my ($name,$id,$debug) = @_;
1.849     albertel 1640:     $id=&make_key($name,$id);
1.599     albertel 1641:     if (exists($remembered{$id})) {
                   1642: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1643: 	$accessed{$id}=[&gettimeofday()];
                   1644: 	$hits++;
                   1645: 	return ($remembered{$id},1);
                   1646:     }
                   1647:     my $value = $memcache->get($id);
                   1648:     if (!(defined($value))) {
                   1649: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1650: 	return (undef,undef);
1.416     albertel 1651:     }
1.599     albertel 1652:     if ($value eq '__undef__') {
                   1653: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1654: 	$value=undef;
                   1655:     }
                   1656:     &make_room($id,$value,$debug);
                   1657:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1658:     return ($value,1);
                   1659: }
                   1660: 
                   1661: sub do_cache_new {
                   1662:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1663:     $id=&make_key($name,$id);
1.599     albertel 1664:     my $setvalue=$value;
                   1665:     if (!defined($setvalue)) {
                   1666: 	$setvalue='__undef__';
                   1667:     }
1.623     albertel 1668:     if (!defined($time) ) {
                   1669: 	$time=600;
                   1670:     }
1.599     albertel 1671:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1672:     my $result = $memcache->set($id,$setvalue,$time);
                   1673:     if (! $result) {
1.872     albertel 1674: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1675: 	$memcache->disconnect_all();
1.872     albertel 1676:     }
1.600     albertel 1677:     # need to make a copy of $value
1.919     albertel 1678:     &make_room($id,$value,$debug);
1.599     albertel 1679:     return $value;
                   1680: }
                   1681: 
                   1682: sub make_room {
                   1683:     my ($id,$value,$debug)=@_;
1.919     albertel 1684: 
                   1685:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1686:                                     : $value;
1.599     albertel 1687:     if ($to_remember<0) { return; }
                   1688:     $accessed{$id}=[&gettimeofday()];
                   1689:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1690:     my $to_kick;
                   1691:     my $max_time=0;
                   1692:     foreach my $other (keys(%accessed)) {
                   1693: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1694: 	    $to_kick=$other;
                   1695: 	    $max_time=&tv_interval($accessed{$other});
                   1696: 	}
                   1697:     }
                   1698:     delete($remembered{$to_kick});
                   1699:     delete($accessed{$to_kick});
                   1700:     $kicks++;
                   1701:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1702:     return;
                   1703: }
                   1704: 
1.599     albertel 1705: sub purge_remembered {
1.604     albertel 1706:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1707:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1708:     undef(%remembered);
                   1709:     undef(%accessed);
1.428     albertel 1710: }
1.70      www      1711: # ------------------------------------- Read an entry from a user's environment
                   1712: 
                   1713: sub userenvironment {
                   1714:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1715:     my $items;
                   1716:     foreach my $item (@what) {
                   1717:         $items.=&escape($item).'&';
                   1718:     }
                   1719:     $items=~s/\&$//;
1.70      www      1720:     my %returnhash=();
1.1009    raeburn  1721:     my $uhome = &homeserver($unam,$udom);
                   1722:     unless ($uhome eq 'no_host') {
                   1723:         my @answer=split(/\&/, 
                   1724:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
                   1725:         my $i;
                   1726:         for ($i=0;$i<=$#what;$i++) {
                   1727: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1728:         }
1.70      www      1729:     }
                   1730:     return %returnhash;
1.1       albertel 1731: }
                   1732: 
1.617     albertel 1733: # ---------------------------------------------------------- Get a studentphoto
                   1734: sub studentphoto {
                   1735:     my ($udom,$unam,$ext) = @_;
                   1736:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1737:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1738:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1739:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1740:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1741:             } else {
                   1742:                 my ($result,$perm_reqd)=
1.707     albertel 1743: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1744:                 if ($result eq 'ok') {
                   1745:                     if (!($perm_reqd eq 'yes')) {
                   1746:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1747:                     }
                   1748:                 }
                   1749:             }
                   1750:         }
                   1751:     } else {
                   1752:         my ($result,$perm_reqd) = 
1.707     albertel 1753: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1754:         if ($result eq 'ok') {
                   1755:             if (!($perm_reqd eq 'yes')) {
                   1756:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1757:             }
                   1758:         }
                   1759:     }
                   1760:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1761: }
                   1762: 
                   1763: sub retrievestudentphoto {
                   1764:     my ($udom,$unam,$ext,$type) = @_;
                   1765:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1766:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1767:     if ($ret eq 'ok') {
                   1768:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1769:         if ($type eq 'thumbnail') {
                   1770:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1771:         }
                   1772:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1773:         return $tokenurl;
                   1774:     } else {
                   1775:         if ($type eq 'thumbnail') {
                   1776:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1777:         } else { 
                   1778:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1779:         }
1.617     albertel 1780:     }
                   1781: }
                   1782: 
1.263     www      1783: # -------------------------------------------------------------------- New chat
                   1784: 
                   1785: sub chatsend {
1.724     raeburn  1786:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1787:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1788:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1789:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1790:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1791: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1792: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1793: }
                   1794: 
                   1795: # ------------------------------------------ Find current version of a resource
                   1796: 
                   1797: sub getversion {
                   1798:     my $fname=&clutter(shift);
                   1799:     unless ($fname=~/^\/res\//) { return -1; }
                   1800:     return &currentversion(&filelocation('',$fname));
                   1801: }
                   1802: 
                   1803: sub currentversion {
                   1804:     my $fname=shift;
1.599     albertel 1805:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1806:     if (defined($cached)) { return $result; }
1.292     www      1807:     my $author=$fname;
                   1808:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1809:     my ($udom,$uname)=split(/\//,$author);
                   1810:     my $home=homeserver($uname,$udom);
                   1811:     if ($home eq 'no_host') { 
                   1812:         return -1; 
                   1813:     }
                   1814:     my $answer=reply("currentversion:$fname",$home);
                   1815:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1816: 	return -1;
                   1817:     }
1.599     albertel 1818:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1819: }
                   1820: 
1.1       albertel 1821: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1822: 
1.1       albertel 1823: sub subscribe {
                   1824:     my $fname=shift;
1.761     raeburn  1825:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1826:     $fname=~s/[\n\r]//g;
1.1       albertel 1827:     my $author=$fname;
                   1828:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1829:     my ($udom,$uname)=split(/\//,$author);
                   1830:     my $home=homeserver($uname,$udom);
1.335     albertel 1831:     if ($home eq 'no_host') {
                   1832:         return 'not_found';
1.1       albertel 1833:     }
                   1834:     my $answer=reply("sub:$fname",$home);
1.64      www      1835:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1836: 	$answer.=' by '.$home;
                   1837:     }
1.1       albertel 1838:     return $answer;
                   1839: }
                   1840:     
1.8       www      1841: # -------------------------------------------------------------- Replicate file
                   1842: 
                   1843: sub repcopy {
                   1844:     my $filename=shift;
1.23      www      1845:     $filename=~s/\/+/\//g;
1.607     raeburn  1846:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1847:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1848:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1849: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1850: 	return &repcopy_userfile($filename);
                   1851:     }
1.532     albertel 1852:     $filename=~s/[\n\r]//g;
1.8       www      1853:     my $transname="$filename.in.transfer";
1.828     www      1854: # FIXME: this should flock
1.607     raeburn  1855:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1856:     my $remoteurl=subscribe($filename);
1.64      www      1857:     if ($remoteurl =~ /^con_lost by/) {
                   1858: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1859:            return 'unavailable';
1.8       www      1860:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1861: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1862: 	   return 'not_found';
1.64      www      1863:     } elsif ($remoteurl =~ /^rejected by/) {
                   1864: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1865:            return 'forbidden';
1.20      www      1866:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1867:            return 'ok';
1.8       www      1868:     } else {
1.290     www      1869:         my $author=$filename;
                   1870:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1871:         my ($udom,$uname)=split(/\//,$author);
                   1872:         my $home=homeserver($uname,$udom);
                   1873:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1874:            my @parts=split(/\//,$filename);
                   1875:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1876:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1877:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1878: 	       return 'bad_request';
1.8       www      1879:            }
                   1880:            my $count;
                   1881:            for ($count=5;$count<$#parts;$count++) {
                   1882:                $path.="/$parts[$count]";
                   1883:                if ((-e $path)!=1) {
                   1884: 		   mkdir($path,0777);
                   1885:                }
                   1886:            }
                   1887:            my $ua=new LWP::UserAgent;
                   1888:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1889:            my $response=$ua->request($request,$transname);
                   1890:            if ($response->is_error()) {
                   1891: 	       unlink($transname);
                   1892:                my $message=$response->status_line;
1.672     albertel 1893:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1894:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1895:                return 'unavailable';
1.8       www      1896:            } else {
1.16      www      1897: 	       if ($remoteurl!~/\.meta$/) {
                   1898:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1899:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1900:                   if ($mresponse->is_error()) {
                   1901: 		      unlink($filename.'.meta');
                   1902:                       &logthis(
1.672     albertel 1903:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1904:                   }
                   1905: 	       }
1.8       www      1906:                rename($transname,$filename);
1.607     raeburn  1907:                return 'ok';
1.8       www      1908:            }
1.290     www      1909:        }
1.8       www      1910:     }
1.330     www      1911: }
                   1912: 
                   1913: # ------------------------------------------------ Get server side include body
                   1914: sub ssi_body {
1.381     albertel 1915:     my ($filelink,%form)=@_;
1.606     matthew  1916:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1917:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1918:     }
1.953     www      1919:     my $output='';
                   1920:     my $response;
1.980     raeburn  1921:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1922:        ($output,$response)=&externalssi($filelink);
1.953     www      1923:     } else {
1.1004    droeschl 1924:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   1925:        $filelink .= 'inhibitmenu=yes';
1.953     www      1926:        ($output,$response)=&ssi($filelink,%form);
                   1927:     }
1.778     albertel 1928:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1929:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1930:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1931:     if (wantarray) {
                   1932:         return ($output, $response);
                   1933:     } else {
                   1934:         return $output;
                   1935:     }
1.8       www      1936: }
                   1937: 
1.15      www      1938: # --------------------------------------------------------- Server Side Include
                   1939: 
1.782     albertel 1940: sub absolute_url {
                   1941:     my ($host_name) = @_;
                   1942:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1943:     if ($host_name eq '') {
                   1944: 	$host_name = $ENV{'SERVER_NAME'};
                   1945:     }
                   1946:     return $protocol.$host_name;
                   1947: }
                   1948: 
1.942     foxr     1949: #
                   1950: #   Server side include.
                   1951: # Parameters:
                   1952: #  fn     Possibly encrypted resource name/id.
                   1953: #  form   Hash that describes how the rendering should be done
                   1954: #         and other things.
1.944     foxr     1955: # Returns:
1.950     raeburn  1956: #   Scalar context: The content of the response.
                   1957: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1958: #     
1.15      www      1959: sub ssi {
                   1960: 
1.944     foxr     1961:     my ($fn,%form)=@_;
1.15      www      1962:     my $ua=new LWP::UserAgent;
1.23      www      1963:     my $request;
1.711     albertel 1964: 
                   1965:     $form{'no_update_last_known'}=1;
1.895     albertel 1966:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1967:     if (%form) {
1.782     albertel 1968:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  1969:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      1970:     } else {
1.782     albertel 1971:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1972:     }
                   1973: 
1.15      www      1974:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1975:     my $response=$ua->request($request);
                   1976: 
1.944     foxr     1977:     if (wantarray) {
                   1978: 	return ($response->content, $response);
                   1979:     } else {
                   1980: 	return $response->content;
1.942     foxr     1981:     }
1.324     www      1982: }
                   1983: 
                   1984: sub externalssi {
                   1985:     my ($url)=@_;
                   1986:     my $ua=new LWP::UserAgent;
                   1987:     my $request=new HTTP::Request('GET',$url);
                   1988:     my $response=$ua->request($request);
1.954     raeburn  1989:     if (wantarray) {
                   1990:         return ($response->content, $response);
                   1991:     } else {
                   1992:         return $response->content;
                   1993:     }
1.15      www      1994: }
1.254     www      1995: 
1.492     albertel 1996: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1997: 
                   1998: sub allowuploaded {
                   1999:     my ($srcurl,$url)=@_;
                   2000:     $url=&clutter(&declutter($url));
                   2001:     my $dir=$url;
                   2002:     $dir=~s/\/[^\/]+$//;
                   2003:     my %httpref=();
                   2004:     my $httpurl=&hreflocation('',$url);
                   2005:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2006:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2007: }
1.477     raeburn  2008: 
1.478     albertel 2009: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2010: # input: action, courseID, current domain, intended
1.637     raeburn  2011: #        path to file, source of file, instruction to parse file for objects,
                   2012: #        ref to hash for embedded objects,
                   2013: #        ref to hash for codebase of java objects.
                   2014: #
1.485     raeburn  2015: # output: url to file (if action was uploaddoc), 
                   2016: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2017: #
1.478     albertel 2018: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2019: # course.
1.477     raeburn  2020: #
1.478     albertel 2021: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2022: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2023: #          course's home server.
1.477     raeburn  2024: #
1.478     albertel 2025: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2026: #          be copied from $source (current location) to 
                   2027: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2028: #         and will then be copied to
                   2029: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2030: #         course's home server.
1.485     raeburn  2031: #
1.481     raeburn  2032: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2033: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2034: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2035: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2036: #         in course's home server.
1.637     raeburn  2037: #
1.477     raeburn  2038: 
                   2039: sub process_coursefile {
1.638     albertel 2040:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2041:     my $fetchresult;
1.638     albertel 2042:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2043:     if ($action eq 'propagate') {
1.638     albertel 2044:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2045: 			     $home);
1.481     raeburn  2046:     } else {
1.477     raeburn  2047:         my $fpath = '';
                   2048:         my $fname = $file;
1.478     albertel 2049:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2050:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2051:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2052:         if ($action eq 'copy') {
                   2053:             if ($source eq '') {
                   2054:                 $fetchresult = 'no source file';
                   2055:                 return $fetchresult;
                   2056:             } else {
                   2057:                 my $destination = $filepath.'/'.$fname;
                   2058:                 rename($source,$destination);
                   2059:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2060:                                  $home);
1.481     raeburn  2061:             }
                   2062:         } elsif ($action eq 'uploaddoc') {
                   2063:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2064:             print $fh $env{'form.'.$source};
1.481     raeburn  2065:             close($fh);
1.637     raeburn  2066:             if ($parser eq 'parse') {
1.1024    raeburn  2067:                 my $mm = new File::MMagic;
                   2068:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2069:                 if ($mime_type eq 'text/html') {
                   2070:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2071:                     unless ($parse_result eq 'ok') {
                   2072:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2073:                     }
1.637     raeburn  2074:                 }
                   2075:             }
1.477     raeburn  2076:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2077:                                  $home);
1.481     raeburn  2078:             if ($fetchresult eq 'ok') {
                   2079:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2080:             } else {
                   2081:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2082:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2083:                 return '/adm/notfound.html';
                   2084:             }
1.477     raeburn  2085:         }
                   2086:     }
1.485     raeburn  2087:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2088:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2089:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2090:     }
                   2091:     return $fetchresult;
                   2092: }
                   2093: 
1.637     raeburn  2094: sub build_filepath {
                   2095:     my ($fpath) = @_;
                   2096:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2097:     unless ($fpath eq '') {
                   2098:         my @parts=split('/',$fpath);
                   2099:         foreach my $part (@parts) {
                   2100:             $filepath.= '/'.$part;
                   2101:             if ((-e $filepath)!=1) {
                   2102:                 mkdir($filepath,0777);
                   2103:             }
                   2104:         }
                   2105:     }
                   2106:     return $filepath;
                   2107: }
                   2108: 
                   2109: sub store_edited_file {
1.638     albertel 2110:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2111:     my $file = $primary_url;
                   2112:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2113:     my $fpath = '';
                   2114:     my $fname = $file;
                   2115:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2116:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2117:     my $filepath = &build_filepath($fpath);
                   2118:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2119:     print $fh $content;
                   2120:     close($fh);
1.638     albertel 2121:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2122:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2123: 			  $home);
1.637     raeburn  2124:     if ($$fetchresult eq 'ok') {
                   2125:         return '/uploaded/'.$fpath.'/'.$fname;
                   2126:     } else {
1.638     albertel 2127:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2128: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2129:         return '/adm/notfound.html';
                   2130:     }
                   2131: }
                   2132: 
1.531     albertel 2133: sub clean_filename {
1.831     albertel 2134:     my ($fname,$args)=@_;
1.315     www      2135: # Replace Windows backslashes by forward slashes
1.257     www      2136:     $fname=~s/\\/\//g;
1.831     albertel 2137:     if (!$args->{'keep_path'}) {
                   2138:         # Get rid of everything but the actual filename
                   2139: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2140:     }
1.315     www      2141: # Replace spaces by underscores
                   2142:     $fname=~s/\s+/\_/g;
                   2143: # Replace all other weird characters by nothing
1.831     albertel 2144:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2145: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2146: # numbers
                   2147:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2148:     return $fname;
                   2149: }
1.984     neumanie 2150: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2151: sub resizeImage {
                   2152: 	my($img_url) = @_;	
                   2153: 	my $ima = Image::Magick->new;                       
                   2154:         $ima->Read($img_url);
                   2155: 	if($ima->Get('width') > 400)
                   2156: 	{
                   2157: 		my $factor = $ima->Get('width')/400;
                   2158:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2159: 	}
                   2160: 	if($ima->Get('height') > 500)
                   2161:         {
                   2162:         	my $factor = $ima->Get('height')/500;
                   2163:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2164:         } 
                   2165: 		
                   2166: 	$ima->Write($img_url);
                   2167: }
1.531     albertel 2168: 
1.977     amueller 2169: #Wrapper function for userphotoupload
                   2170: sub userphotoupload
                   2171: {
                   2172: 	my($formname,$subdir) = @_;
                   2173: 	$upload_photo_form = 1;
                   2174: 	return &userfileupload($formname,undef,$subdir);
                   2175: }
                   2176: 
1.608     albertel 2177: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2178: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2179: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2180: #        $coursedoc - if true up to the current course
                   2181: #                     if false
                   2182: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2183: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2184: #        $allfiles - reference to hash for embedded objects
                   2185: #        $codebase - reference to hash for codebase of java objects
                   2186: #        $desuname - username for permanent storage of uploaded file
                   2187: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2188: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2189: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2190: # 
1.686     albertel 2191: # output: url of file in userspace, or error: <message> 
                   2192: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2193: 
                   2194: 
1.531     albertel 2195: sub userfileupload {
1.860     raeburn  2196:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2197:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2198:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2199:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2200:     $fname=&clean_filename($fname);
1.315     www      2201: # See if there is anything left
1.257     www      2202:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2203:     chop($env{'form.'.$formname});
1.523     raeburn  2204:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2205:         my $now = time;
                   2206:         my $filepath = 'tmp/helprequests/'.$now;
                   2207:         my @parts=split(/\//,$filepath);
                   2208:         my $fullpath = $perlvar{'lonDaemons'};
                   2209:         for (my $i=0;$i<@parts;$i++) {
                   2210:             $fullpath .= '/'.$parts[$i];
                   2211:             if ((-e $fullpath)!=1) {
                   2212:                 mkdir($fullpath,0777);
                   2213:             }
                   2214:         }
                   2215:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2216:         print $fh $env{'form.'.$formname};
1.523     raeburn  2217:         close($fh);
1.741     raeburn  2218:         return $fullpath.'/'.$fname;
                   2219:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2220:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2221:                        '_'.$env{'user.domain'}.'/pending';
                   2222:         my @parts=split(/\//,$filepath);
                   2223:         my $fullpath = $perlvar{'lonDaemons'};
                   2224:         for (my $i=0;$i<@parts;$i++) {
                   2225:             $fullpath .= '/'.$parts[$i];
                   2226:             if ((-e $fullpath)!=1) {
                   2227:                 mkdir($fullpath,0777);
                   2228:             }
                   2229:         }
                   2230:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2231:         print $fh $env{'form.'.$formname};
                   2232:         close($fh);
                   2233:         return $fullpath.'/'.$fname;
1.523     raeburn  2234:     }
1.995     raeburn  2235:     if ($subdir eq 'scantron') {
                   2236:         $fname = 'scantron_orig_'.$fname;
                   2237:     } else {   
1.258     www      2238: # Create the directory if not present
1.995     raeburn  2239:         $fname="$subdir/$fname";
                   2240:     }
1.259     www      2241:     if ($coursedoc) {
1.638     albertel 2242: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2243: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2244:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2245:             return &finishuserfileupload($docuname,$docudom,
                   2246: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2247: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2248:         } else {
1.620     albertel 2249:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2250:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2251: 				       $fname,$formname,$parser,
                   2252: 				       $allfiles,$codebase);
1.481     raeburn  2253:         }
1.719     banghart 2254:     } elsif (defined($destuname)) {
                   2255:         my $docuname=$destuname;
                   2256:         my $docudom=$destudom;
1.860     raeburn  2257: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2258: 				     $parser,$allfiles,$codebase,
                   2259:                                      $thumbwidth,$thumbheight);
1.719     banghart 2260:         
1.259     www      2261:     } else {
1.638     albertel 2262:         my $docuname=$env{'user.name'};
                   2263:         my $docudom=$env{'user.domain'};
1.714     raeburn  2264:         if (exists($env{'form.group'})) {
                   2265:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2266:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2267:         }
1.860     raeburn  2268: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2269: 				     $parser,$allfiles,$codebase,
                   2270:                                      $thumbwidth,$thumbheight);
1.259     www      2271:     }
1.271     www      2272: }
                   2273: 
                   2274: sub finishuserfileupload {
1.860     raeburn  2275:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2276:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2277:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2278:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2279:   
1.860     raeburn  2280:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2281:     $file=$fname;
                   2282:     if ($fname=~m|/|) {
                   2283:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2284: 	$path.=$fnamepath.'/';
                   2285:     }
1.259     www      2286:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2287:     my $count;
                   2288:     for ($count=4;$count<=$#parts;$count++) {
                   2289:         $filepath.="/$parts[$count]";
                   2290:         if ((-e $filepath)!=1) {
                   2291: 	    mkdir($filepath,0777);
                   2292:         }
                   2293:     }
1.984     neumanie 2294: 
1.258     www      2295: # Save the file
                   2296:     {
1.701     albertel 2297: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2298: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2299: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2300: 	    return '/adm/notfound.html';
                   2301: 	}
                   2302: 	if (!print FH ($env{'form.'.$formname})) {
                   2303: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2304: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2305: 	    return '/adm/notfound.html';
                   2306: 	}
1.570     albertel 2307: 	close(FH);
1.977     amueller 2308: 	if($upload_photo_form==1)
                   2309: 	{
1.984     neumanie 2310: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2311: 		$upload_photo_form = 0;
                   2312: 	}
1.258     www      2313:     }
1.637     raeburn  2314:     if ($parser eq 'parse') {
1.1024    raeburn  2315:         my $mm = new File::MMagic;
                   2316:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2317:         if ($mime_type eq 'text/html') {
                   2318:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2319:                                                        $allfiles,$codebase);
                   2320:             unless ($parse_result eq 'ok') {
                   2321:                 &logthis('Failed to parse '.$filepath.$file.
                   2322: 	   	         ' for embedded media: '.$parse_result); 
                   2323:             }
1.637     raeburn  2324:         }
                   2325:     }
1.860     raeburn  2326:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2327:         my $input = $filepath.'/'.$file;
                   2328:         my $output = $filepath.'/'.'tn-'.$file;
                   2329:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2330:         system("convert -sample $thumbsize $input $output");
                   2331:         if (-e $filepath.'/'.'tn-'.$file) {
                   2332:             $fetchthumb  = 1; 
                   2333:         }
                   2334:     }
1.858     raeburn  2335:  
1.259     www      2336: # Notify homeserver to grep it
                   2337: #
1.984     neumanie 2338:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2339:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2340:     if ($fetchresult eq 'ok') {
1.860     raeburn  2341:         if ($fetchthumb) {
                   2342:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2343:             if ($thumbresult ne 'ok') {
                   2344:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2345:                          $docuhome.': '.$thumbresult);
                   2346:             }
                   2347:         }
1.259     www      2348: #
1.258     www      2349: # Return the URL to it
1.494     albertel 2350:         return '/uploaded/'.$path.$file;
1.263     www      2351:     } else {
1.494     albertel 2352:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2353: 		 ': '.$fetchresult);
1.263     www      2354:         return '/adm/notfound.html';
1.858     raeburn  2355:     }
1.493     albertel 2356: }
                   2357: 
1.637     raeburn  2358: sub extract_embedded_items {
1.961     raeburn  2359:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2360:     my @state = ();
                   2361:     my %javafiles = (
                   2362:                       codebase => '',
                   2363:                       code => '',
                   2364:                       archive => ''
                   2365:                     );
                   2366:     my %mediafiles = (
                   2367:                       src => '',
                   2368:                       movie => '',
                   2369:                      );
1.648     raeburn  2370:     my $p;
                   2371:     if ($content) {
                   2372:         $p = HTML::LCParser->new($content);
                   2373:     } else {
1.961     raeburn  2374:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2375:     }
1.641     albertel 2376:     while (my $t=$p->get_token()) {
1.640     albertel 2377: 	if ($t->[0] eq 'S') {
                   2378: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2379: 	    push(@state, $tagname);
1.648     raeburn  2380:             if (lc($tagname) eq 'allow') {
                   2381:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2382:             }
1.640     albertel 2383: 	    if (lc($tagname) eq 'img') {
                   2384: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2385: 	    }
1.886     albertel 2386: 	    if (lc($tagname) eq 'a') {
                   2387: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2388: 	    }
1.645     raeburn  2389:             if (lc($tagname) eq 'script') {
                   2390:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2391:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2392:                 } else {
                   2393:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2394:                 }
                   2395:             }
                   2396:             if (lc($tagname) eq 'link') {
                   2397:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2398:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2399:                 }
                   2400:             }
1.640     albertel 2401: 	    if (lc($tagname) eq 'object' ||
                   2402: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2403: 		foreach my $item (keys(%javafiles)) {
                   2404: 		    $javafiles{$item} = '';
                   2405: 		}
                   2406: 	    }
                   2407: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2408: 		my $name = lc($attr->{'name'});
                   2409: 		foreach my $item (keys(%javafiles)) {
                   2410: 		    if ($name eq $item) {
                   2411: 			$javafiles{$item} = $attr->{'value'};
                   2412: 			last;
                   2413: 		    }
                   2414: 		}
                   2415: 		foreach my $item (keys(%mediafiles)) {
                   2416: 		    if ($name eq $item) {
                   2417: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2418: 			last;
                   2419: 		    }
                   2420: 		}
                   2421: 	    }
                   2422: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2423: 		foreach my $item (keys(%javafiles)) {
                   2424: 		    if ($attr->{$item}) {
                   2425: 			$javafiles{$item} = $attr->{$item};
                   2426: 			last;
                   2427: 		    }
                   2428: 		}
                   2429: 		foreach my $item (keys(%mediafiles)) {
                   2430: 		    if ($attr->{$item}) {
                   2431: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2432: 			last;
                   2433: 		    }
                   2434: 		}
                   2435: 	    }
                   2436: 	} elsif ($t->[0] eq 'E') {
                   2437: 	    my ($tagname) = ($t->[1]);
                   2438: 	    if ($javafiles{'codebase'} ne '') {
                   2439: 		$javafiles{'codebase'} .= '/';
                   2440: 	    }  
                   2441: 	    if (lc($tagname) eq 'applet' ||
                   2442: 		lc($tagname) eq 'object' ||
                   2443: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2444: 		) {
                   2445: 		foreach my $item (keys(%javafiles)) {
                   2446: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2447: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2448: 			&add_filetype($allfiles,$file,$item);
                   2449: 		    }
                   2450: 		}
                   2451: 	    } 
                   2452: 	    pop @state;
                   2453: 	}
                   2454:     }
1.637     raeburn  2455:     return 'ok';
                   2456: }
                   2457: 
1.639     albertel 2458: sub add_filetype {
                   2459:     my ($allfiles,$file,$type)=@_;
                   2460:     if (exists($allfiles->{$file})) {
                   2461: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2462: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2463: 	}
                   2464:     } else {
                   2465: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2466:     }
                   2467: }
                   2468: 
1.493     albertel 2469: sub removeuploadedurl {
1.984     neumanie 2470:     my ($url)=@_;	
                   2471:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2472:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2473: }
                   2474: 
                   2475: sub removeuserfile {
                   2476:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2477:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2478:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2479:     if ($result eq 'ok') {	
1.798     raeburn  2480:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2481:             my $metafile = $fname.'.meta';
                   2482:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2483: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2484:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2485:             my $sqlresult = 
1.823     albertel 2486:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2487:                                         'portfolio_metadata',$group,
                   2488:                                         'delete');
1.798     raeburn  2489:         }
                   2490:     }
                   2491:     return $result;
1.257     www      2492: }
1.15      www      2493: 
1.530     albertel 2494: sub mkdiruserfile {
                   2495:     my ($docuname,$docudom,$dir)=@_;
                   2496:     my $home=&homeserver($docuname,$docudom);
                   2497:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2498: }
                   2499: 
1.531     albertel 2500: sub renameuserfile {
                   2501:     my ($docuname,$docudom,$old,$new)=@_;
                   2502:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2503:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2504:                         &escape("$old").':'.&escape("$new"),$home);
                   2505:     if ($result eq 'ok') {
                   2506:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2507:             my $oldmeta = $old.'.meta';
                   2508:             my $newmeta = $new.'.meta';
                   2509:             my $metaresult = 
                   2510:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2511: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2512:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2513:             my $sqlresult = 
1.823     albertel 2514:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2515:                                         'portfolio_metadata',$group,
                   2516:                                         'delete');
1.798     raeburn  2517:         }
                   2518:     }
                   2519:     return $result;
1.531     albertel 2520: }
                   2521: 
1.14      www      2522: # ------------------------------------------------------------------------- Log
                   2523: 
                   2524: sub log {
                   2525:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2526:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2527: }
                   2528: 
                   2529: # ------------------------------------------------------------------ Course Log
1.352     www      2530: #
                   2531: # This routine flushes several buffers of non-mission-critical nature
                   2532: #
1.157     www      2533: 
                   2534: sub flushcourselogs {
1.352     www      2535:     &logthis('Flushing log buffers');
                   2536: #
                   2537: # course logs
                   2538: # This is a log of all transactions in a course, which can be used
                   2539: # for data mining purposes
                   2540: #
                   2541: # It also collects the courseid database, which lists last transaction
                   2542: # times and course titles for all courseids
                   2543: #
                   2544:     my %courseidbuffer=();
1.921     raeburn  2545:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2546:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2547: 		          &escape($courselogs{$crsid}),
                   2548: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2549: 	    delete $courselogs{$crsid};
                   2550:         } else {
                   2551:             &logthis('Failed to flush log buffer for '.$crsid);
                   2552:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2553:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2554:                         " exceeded maximum size, deleting.</font>");
                   2555:                delete $courselogs{$crsid};
                   2556:             }
1.352     www      2557:         }
1.920     raeburn  2558:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2559:             'description' => $coursedescrbuf{$crsid},
                   2560:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2561:             'type'        => $coursetypebuf{$crsid},
                   2562:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2563:         };
1.191     harris41 2564:     }
1.352     www      2565: #
                   2566: # Write course id database (reverse lookup) to homeserver of courses 
                   2567: # Is used in pickcourse
                   2568: #
1.840     albertel 2569:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2570:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2571:                                     $courseidbuffer{$crs_home},
                   2572:                                     $crs_home,'timeonly');
1.352     www      2573:     }
                   2574: #
                   2575: # File accesses
                   2576: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2577: #
1.449     matthew  2578:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2579:         if ($entry =~ /___count$/) {
                   2580:             my ($dom,$name);
1.807     albertel 2581:             ($dom,$name,undef)=
1.811     albertel 2582: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2583:             if (! defined($dom) || $dom eq '' || 
                   2584:                 ! defined($name) || $name eq '') {
1.620     albertel 2585:                 my $cid = $env{'request.course.id'};
                   2586:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2587:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2588:             }
1.450     matthew  2589:             my $value = $accesshash{$entry};
                   2590:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2591:             my %temphash=($url => $value);
1.449     matthew  2592:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2593:             if ($result eq 'ok') {
                   2594:                 delete $accesshash{$entry};
                   2595:             } elsif ($result eq 'unknown_cmd') {
                   2596:                 # Target server has old code running on it.
1.450     matthew  2597:                 my %temphash=($entry => $value);
1.449     matthew  2598:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2599:                     delete $accesshash{$entry};
                   2600:                 }
                   2601:             }
                   2602:         } else {
1.811     albertel 2603:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2604:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2605:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2606:                 delete $accesshash{$entry};
                   2607:             }
1.185     www      2608:         }
1.191     harris41 2609:     }
1.352     www      2610: #
                   2611: # Roles
                   2612: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2613: #
1.800     albertel 2614:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2615:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2616: 	    split(/\:/,$entry);
                   2617:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2618:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2619:                 $rudom,$runame) eq 'ok') {
                   2620: 	    delete $userrolehash{$entry};
                   2621:         }
                   2622:     }
1.662     raeburn  2623: #
                   2624: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2625: #
                   2626:     my %domrolebuffer = ();
1.1000    raeburn  2627:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2628:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2629:         if ($domrolebuffer{$rudom}) {
                   2630:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2631:                       '='.&escape($domainrolehash{$entry});
                   2632:         } else {
                   2633:             $domrolebuffer{$rudom}.=&escape($entry).
                   2634:                       '='.&escape($domainrolehash{$entry});
                   2635:         }
                   2636:         delete $domainrolehash{$entry};
                   2637:     }
                   2638:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2639: 	my %servers = &get_servers($dom,'library');
                   2640: 	foreach my $tryserver (keys(%servers)) {
                   2641: 	    unless (&reply('domroleput:'.$dom.':'.
                   2642: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2643: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2644: 	    }
1.662     raeburn  2645:         }
                   2646:     }
1.186     www      2647:     $dumpcount++;
1.157     www      2648: }
                   2649: 
                   2650: sub courselog {
                   2651:     my $what=shift;
1.158     www      2652:     $what=time.':'.$what;
1.620     albertel 2653:     unless ($env{'request.course.id'}) { return ''; }
                   2654:     $coursedombuf{$env{'request.course.id'}}=
                   2655:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2656:     $coursenumbuf{$env{'request.course.id'}}=
                   2657:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2658:     $coursehombuf{$env{'request.course.id'}}=
                   2659:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2660:     $coursedescrbuf{$env{'request.course.id'}}=
                   2661:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2662:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2663:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2664:     $courseownerbuf{$env{'request.course.id'}}=
                   2665:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2666:     $coursetypebuf{$env{'request.course.id'}}=
                   2667:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2668:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2669: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2670:     } else {
1.620     albertel 2671: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2672:     }
1.620     albertel 2673:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2674: 	&flushcourselogs();
                   2675:     }
1.158     www      2676: }
                   2677: 
                   2678: sub courseacclog {
                   2679:     my $fnsymb=shift;
1.620     albertel 2680:     unless ($env{'request.course.id'}) { return ''; }
                   2681:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2682:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2683:         $what.=':POST';
1.583     matthew  2684:         # FIXME: Probably ought to escape things....
1.800     albertel 2685: 	foreach my $key (keys(%env)) {
                   2686:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2687:                 my $formitem = $1;
                   2688:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2689:                     $what.=':'.$formitem.'='.$env{$key};
                   2690:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2691:                     $what.=':'.$formitem.'='.$env{$key};
                   2692:                 }
1.158     www      2693:             }
1.191     harris41 2694:         }
1.583     matthew  2695:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2696:         # FIXME: We should not be depending on a form parameter that someone
                   2697:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2698:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2699:             $what.= ':POST';
                   2700:             # FIXME: Probably ought to escape things....
                   2701:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2702:                                  'crsdiscuss') {
1.620     albertel 2703:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2704:             }
                   2705:         }
1.158     www      2706:     }
                   2707:     &courselog($what);
1.149     www      2708: }
                   2709: 
1.185     www      2710: sub countacc {
                   2711:     my $url=&declutter(shift);
1.458     matthew  2712:     return if (! defined($url) || $url eq '');
1.620     albertel 2713:     unless ($env{'request.course.id'}) { return ''; }
                   2714:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2715:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2716:     $accesshash{$key}++;
1.185     www      2717: }
1.349     www      2718: 
1.361     www      2719: sub linklog {
                   2720:     my ($from,$to)=@_;
                   2721:     $from=&declutter($from);
                   2722:     $to=&declutter($to);
                   2723:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2724:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2725: }
                   2726:   
1.349     www      2727: sub userrolelog {
                   2728:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2729:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2730:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2731:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041  ! raeburn  2732:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2733:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2734:        $userrolehash
                   2735:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2736:                     =$tend.':'.$tstart;
1.662     raeburn  2737:     }
1.898     albertel 2738:     if (($env{'request.role'} =~ /dc\./) &&
                   2739: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2740: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041  ! raeburn  2741: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
        !          2742:          ($trole=~/^co/))) {
1.898     albertel 2743:        $userrolehash
                   2744:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2745:                     =$tend.':'.$tstart;
                   2746:     }
1.662     raeburn  2747:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2748:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2749:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2750:         ($trole=~/^sc/)) {
                   2751:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2752:        $domainrolehash
                   2753:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2754:                     = $tend.':'.$tstart;
                   2755:     }
1.351     www      2756: }
                   2757: 
1.957     raeburn  2758: sub courserolelog {
                   2759:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2760:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2761:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2762:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2763:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2764:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2765:             my $cdom = $1;
                   2766:             my $cnum = $2;
                   2767:             my $sec = $3;
                   2768:             my $namespace = 'rolelog';
                   2769:             my %storehash = (
                   2770:                                role    => $trole,
                   2771:                                start   => $tstart,
                   2772:                                end     => $tend,
                   2773:                                selfenroll => $selfenroll,
                   2774:                                context    => $context,
                   2775:                             );
                   2776:             if ($trole eq 'gr') {
                   2777:                 $namespace = 'groupslog';
                   2778:                 $storehash{'group'} = $sec;
                   2779:             } else {
                   2780:                 $storehash{'section'} = $sec;
                   2781:             }
                   2782:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2783:             if (($trole ne 'st') || ($sec ne '')) {
                   2784:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2785:             }
1.957     raeburn  2786:         }
                   2787:     }
                   2788:     return;
                   2789: }
                   2790: 
1.351     www      2791: sub get_course_adv_roles {
1.948     raeburn  2792:     my ($cid,$codes) = @_;
1.620     albertel 2793:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2794:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2795:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2796:     my %nothide=();
1.800     albertel 2797:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2798:         if ($user !~ /:/) {
                   2799: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2800:         } else {
                   2801:             $nothide{$user}=1;
                   2802:         }
1.470     www      2803:     }
1.351     www      2804:     my %returnhash=();
                   2805:     my %dumphash=
                   2806:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2807:     my $now=time;
1.997     raeburn  2808:     my %privileged;
1.1000    raeburn  2809:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2810: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2811:         if (($tstart) && ($tstart<0)) { next; }
                   2812:         if (($tend) && ($tend<$now)) { next; }
                   2813:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2814:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2815: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2816:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2817:             my %dompersonnel =
1.998     raeburn  2818:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2819:             $privileged{$domain} = {};
                   2820:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2821:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2822:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2823:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2824:                         $privileged{$udom}{$uname} = 1;
                   2825:                     }
                   2826:                 }
                   2827:             }
                   2828:         }
                   2829:         if ((exists($privileged{$domain}{$username})) && 
                   2830:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2831: 	if ($role eq 'cr') { next; }
1.948     raeburn  2832:         if ($codes) {
                   2833:             if ($section) { $role .= ':'.$section; }
                   2834:             if ($returnhash{$role}) {
                   2835:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2836:             } else {
                   2837:                 $returnhash{$role}=$username.':'.$domain;
                   2838:             }
1.351     www      2839:         } else {
1.988     raeburn  2840:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2841:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2842:             if ($returnhash{$key}) {
                   2843: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2844:             } else {
                   2845:                 $returnhash{$key}=$username.':'.$domain;
                   2846:             }
1.351     www      2847:         }
1.948     raeburn  2848:     }
1.400     www      2849:     return %returnhash;
                   2850: }
                   2851: 
                   2852: sub get_my_roles {
1.937     raeburn  2853:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2854:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2855:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2856:     my (%dumphash,%nothide);
1.858     raeburn  2857:     if ($context eq 'userroles') { 
                   2858:         %dumphash = &dump('roles',$udom,$uname);
                   2859:     } else {
                   2860:         %dumphash=
1.400     www      2861:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2862:         if ($hidepriv) {
                   2863:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2864:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2865:                 if ($user !~ /:/) {
                   2866:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2867:                 } else {
                   2868:                     $nothide{$user} = 1;
                   2869:                 }
                   2870:             }
                   2871:         }
1.858     raeburn  2872:     }
1.400     www      2873:     my %returnhash=();
                   2874:     my $now=time;
1.999     raeburn  2875:     my %privileged;
1.800     albertel 2876:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2877:         my ($role,$tend,$tstart);
                   2878:         if ($context eq 'userroles') {
                   2879: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2880:         } else {
                   2881:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2882:         }
1.400     www      2883:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2884:         my $status = 'active';
1.939     raeburn  2885:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2886:             $status = 'previous';
                   2887:         } 
                   2888:         if (($tstart) && ($now<$tstart)) {
                   2889:             $status = 'future';
                   2890:         }
                   2891:         if (ref($types) eq 'ARRAY') {
                   2892:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2893:                 next;
                   2894:             } 
                   2895:         } else {
                   2896:             if ($status ne 'active') {
                   2897:                 next;
                   2898:             }
                   2899:         }
1.867     raeburn  2900:         my ($rolecode,$username,$domain,$section,$area);
                   2901:         if ($context eq 'userroles') {
                   2902:             ($area,$rolecode) = split(/_/,$entry);
                   2903:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2904:         } else {
                   2905:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2906:         }
1.832     raeburn  2907:         if (ref($roledoms) eq 'ARRAY') {
                   2908:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2909:                 next;
                   2910:             }
                   2911:         }
                   2912:         if (ref($roles) eq 'ARRAY') {
                   2913:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2914:                 if ($role =~ /^cr\//) {
                   2915:                     if (!grep(/^cr$/,@{$roles})) {
                   2916:                         next;
                   2917:                     }
                   2918:                 } else {
                   2919:                     next;
                   2920:                 }
1.832     raeburn  2921:             }
1.867     raeburn  2922:         }
1.937     raeburn  2923:         if ($hidepriv) {
1.999     raeburn  2924:             if ($context eq 'userroles') {
                   2925:                 if ((&privileged($username,$domain)) &&
                   2926:                     (!$nothide{$username.':'.$domain})) {
                   2927:                     next;
                   2928:                 }
                   2929:             } else {
                   2930:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2931:                     my %dompersonnel =
                   2932:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2933:                     $privileged{$domain} = {};
                   2934:                     if (keys(%dompersonnel)) {
                   2935:                         foreach my $server (keys(%dompersonnel)) {
                   2936:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2937:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2938:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2939:                                     $privileged{$udom}{$uname} = $trole;
                   2940:                                 }
                   2941:                             }
                   2942:                         }
                   2943:                     }
                   2944:                 }
                   2945:                 if (exists($privileged{$domain}{$username})) {
                   2946:                     if (!$nothide{$username.':'.$domain}) {
                   2947:                         next;
                   2948:                     }
                   2949:                 }
1.937     raeburn  2950:             }
                   2951:         }
1.933     raeburn  2952:         if ($withsec) {
                   2953:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2954:                 $tstart.':'.$tend;
                   2955:         } else {
                   2956:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2957:         }
1.832     raeburn  2958:     }
1.373     www      2959:     return %returnhash;
1.399     www      2960: }
                   2961: 
                   2962: # ----------------------------------------------------- Frontpage Announcements
                   2963: #
                   2964: #
                   2965: 
                   2966: sub postannounce {
                   2967:     my ($server,$text)=@_;
1.844     albertel 2968:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2969:     unless ($text=~/\w/) { $text=''; }
                   2970:     return &reply('setannounce:'.&escape($text),$server);
                   2971: }
                   2972: 
                   2973: sub getannounce {
1.448     albertel 2974: 
                   2975:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2976: 	my $announcement='';
1.800     albertel 2977: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2978: 	close($fh);
1.399     www      2979: 	if ($announcement=~/\w/) { 
                   2980: 	    return 
                   2981:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2982:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2983: 	} else {
                   2984: 	    return '';
                   2985: 	}
                   2986:     } else {
                   2987: 	return '';
                   2988:     }
1.351     www      2989: }
1.353     www      2990: 
                   2991: # ---------------------------------------------------------- Course ID routines
                   2992: # Deal with domain's nohist_courseid.db files
                   2993: #
                   2994: 
                   2995: sub courseidput {
1.921     raeburn  2996:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2997:     my $outcome;
                   2998:     if ($caller eq 'timeonly') {
                   2999:         my $cids = '';
                   3000:         foreach my $item (keys(%$storehash)) {
                   3001:             $cids.=&escape($item).'&';
                   3002:         }
                   3003:         $cids=~s/\&$//;
                   3004:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3005:                           $coursehome);       
                   3006:     } else {
                   3007:         my $items = '';
                   3008:         foreach my $item (keys(%$storehash)) {
                   3009:             $items.= &escape($item).'='.
                   3010:                      &freeze_escape($$storehash{$item}).'&';
                   3011:         }
                   3012:         $items=~s/\&$//;
                   3013:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3014:                           $coursehome);
1.918     raeburn  3015:     }
                   3016:     if ($outcome eq 'unknown_cmd') {
                   3017:         my $what;
                   3018:         foreach my $cid (keys(%$storehash)) {
                   3019:             $what .= &escape($cid).'=';
1.921     raeburn  3020:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3021:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3022:             }
                   3023:             $what =~ s/\:$/&/;
                   3024:         }
                   3025:         $what =~ s/\&$//;  
                   3026:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3027:     } else {
                   3028:         return $outcome;
                   3029:     }
1.353     www      3030: }
                   3031: 
                   3032: sub courseiddump {
1.921     raeburn  3033:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3034:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3035:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
                   3036:         $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
1.918     raeburn  3037:     my $as_hash = 1;
                   3038:     my %returnhash;
                   3039:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3040:     my %libserv = &all_library();
                   3041:     foreach my $tryserver (keys(%libserv)) {
                   3042:         if ( (  $hostidflag == 1 
                   3043: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3044: 	     || (!defined($hostidflag)) ) {
                   3045: 
1.918     raeburn  3046: 	    if (($domfilter eq '') ||
                   3047: 		(&host_domain($tryserver) eq $domfilter)) {
                   3048:                 my $rep = 
                   3049:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3050:                          $sincefilter.':'.&escape($descfilter).':'.
                   3051:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3052:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3053:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3054:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3055:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3056:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3057:                          &escape($createdbefore).':'.&escape($createdafter).':'.
                   3058:                          &escape($creationcontext),$tryserver);
1.918     raeburn  3059:                 my @pairs=split(/\&/,$rep);
                   3060:                 foreach my $item (@pairs) {
                   3061:                     my ($key,$value)=split(/\=/,$item,2);
                   3062:                     $key = &unescape($key);
                   3063:                     next if ($key =~ /^error: 2 /);
                   3064:                     my $result = &thaw_unescape($value);
                   3065:                     if (ref($result) eq 'HASH') {
                   3066:                         $returnhash{$key}=$result;
                   3067:                     } else {
1.921     raeburn  3068:                         my @responses = split(/:/,$value);
                   3069:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3070:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3071:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3072:                         }
1.1008    raeburn  3073:                     }
1.353     www      3074:                 }
                   3075:             }
                   3076:         }
                   3077:     }
                   3078:     return %returnhash;
                   3079: }
                   3080: 
1.658     raeburn  3081: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3082: 
                   3083: sub dcmailput {
1.685     raeburn  3084:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3085:     my $status = &Apache::lonnet::critical(
1.740     www      3086:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3087:        &escape($message),$server);
1.662     raeburn  3088:     return $status;
                   3089: }
                   3090: 
1.658     raeburn  3091: sub dcmaildump {
                   3092:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3093:     my %returnhash=();
1.846     albertel 3094: 
                   3095:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3096:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3097:                                                          &escape($enddate).':';
                   3098: 	my @esc_senders=map { &escape($_)} @$senders;
                   3099: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3100: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3101:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3102:             if (($key) && ($value)) {
                   3103:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3104:             }
                   3105:         }
                   3106:     }
                   3107:     return %returnhash;
                   3108: }
1.662     raeburn  3109: # ---------------------------------------------------------- Domain roles
                   3110: 
                   3111: sub get_domain_roles {
                   3112:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3113:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3114:         $startdate = '.';
                   3115:     }
1.1018    raeburn  3116:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3117:         $enddate = '.';
                   3118:     }
1.922     raeburn  3119:     my $rolelist;
                   3120:     if (ref($roles) eq 'ARRAY') {
                   3121:         $rolelist = join(':',@{$roles});
                   3122:     }
1.662     raeburn  3123:     my %personnel = ();
1.841     albertel 3124: 
                   3125:     my %servers = &get_servers($dom,'library');
                   3126:     foreach my $tryserver (keys(%servers)) {
                   3127: 	%{$personnel{$tryserver}}=();
                   3128: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3129: 					    &escape($startdate).':'.
                   3130: 					    &escape($enddate).':'.
                   3131: 					    &escape($rolelist), $tryserver))) {
                   3132: 	    my ($key,$value) = split(/\=/,$line,2);
                   3133: 	    if (($key) && ($value)) {
                   3134: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3135: 	    }
                   3136: 	}
1.662     raeburn  3137:     }
                   3138:     return %personnel;
                   3139: }
1.658     raeburn  3140: 
1.149     www      3141: # ----------------------------------------------------------- Check out an item
                   3142: 
1.504     albertel 3143: sub get_first_access {
                   3144:     my ($type,$argsymb)=@_;
1.790     albertel 3145:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3146:     if ($argsymb) { $symb=$argsymb; }
                   3147:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3148:     if ($type eq 'course') {
                   3149: 	$res='course';
                   3150:     } elsif ($type eq 'map') {
1.588     albertel 3151: 	$res=&symbread($map);
                   3152:     } else {
                   3153: 	$res=$symb;
                   3154:     }
                   3155:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3156:     return $times{"$courseid\0$res"};
1.504     albertel 3157: }
                   3158: 
                   3159: sub set_first_access {
                   3160:     my ($type)=@_;
1.790     albertel 3161:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3162:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3163:     if ($type eq 'course') {
                   3164: 	$res='course';
                   3165:     } elsif ($type eq 'map') {
1.588     albertel 3166: 	$res=&symbread($map);
                   3167:     } else {
                   3168: 	$res=$symb;
                   3169:     }
                   3170:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3171:     if (!$firstaccess) {
1.588     albertel 3172: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3173:     }
                   3174:     return 'already_set';
1.504     albertel 3175: }
                   3176: 
1.149     www      3177: sub checkout {
                   3178:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3179:     my $now=time;
                   3180:     my $lonhost=$perlvar{'lonHostID'};
                   3181:     my $infostr=&escape(
1.234     www      3182:                  'CHECKOUTTOKEN&'.
1.149     www      3183:                  $tuname.'&'.
                   3184:                  $tudom.'&'.
                   3185:                  $tcrsid.'&'.
                   3186:                  $symb.'&'.
                   3187: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3188:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3189:     if ($token=~/^error\:/) { 
1.672     albertel 3190:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3191:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3192:                  "</font>");
                   3193:         return ''; 
                   3194:     }
                   3195: 
1.149     www      3196:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3197:     $token=~tr/a-z/A-Z/;
                   3198: 
1.153     www      3199:     my %infohash=('resource.0.outtoken' => $token,
                   3200:                   'resource.0.checkouttime' => $now,
                   3201:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3202: 
                   3203:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3204:        return '';
1.151     www      3205:     } else {
1.672     albertel 3206:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3207:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3208:                  "</font>");
1.149     www      3209:     }    
                   3210: 
                   3211:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3212:                          &escape('Checkout '.$infostr.' - '.
                   3213:                                                  $token)) ne 'ok') {
                   3214: 	return '';
1.151     www      3215:     } else {
1.672     albertel 3216:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3217:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3218:                  "</font>");
1.149     www      3219:     }
1.151     www      3220:     return $token;
1.149     www      3221: }
                   3222: 
                   3223: # ------------------------------------------------------------ Check in an item
                   3224: 
                   3225: sub checkin {
                   3226:     my $token=shift;
1.150     www      3227:     my $now=time;
                   3228:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3229:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3230:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3231:     $dtoken=~s/\W/\_/g;
1.234     www      3232:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3233:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3234: 
1.154     www      3235:     unless (($tuname) && ($tudom)) {
                   3236:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3237:         return '';
                   3238:     }
                   3239:     
                   3240:     unless (&allowed('mgr',$tcrsid)) {
                   3241:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3242:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3243:         return '';
                   3244:     }
                   3245: 
1.153     www      3246:     my %infohash=('resource.0.intoken' => $token,
                   3247:                   'resource.0.checkintime' => $now,
                   3248:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3249: 
                   3250:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3251:        return '';
                   3252:     }    
                   3253: 
                   3254:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3255:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3256: 	return '';
                   3257:     }
                   3258: 
                   3259:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3260: }
                   3261: 
                   3262: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3263: 
                   3264: sub expirespread {
                   3265:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3266:     my $cid=$env{'request.course.id'}; 
1.110     www      3267:     if ($cid) {
                   3268:        my $now=time;
                   3269:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3270:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3271:                             $env{'course.'.$cid.'.num'}.
1.110     www      3272: 	        	    ':nohist_expirationdates:'.
                   3273:                             &escape($key).'='.$now,
1.620     albertel 3274:                             $env{'course.'.$cid.'.home'})
1.110     www      3275:     }
                   3276:     return 'ok';
1.14      www      3277: }
                   3278: 
1.109     www      3279: # ----------------------------------------------------- Devalidate Spreadsheets
                   3280: 
                   3281: sub devalidate {
1.325     www      3282:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3283:     my $cid=$env{'request.course.id'}; 
1.109     www      3284:     if ($cid) {
1.391     matthew  3285:         # delete the stored spreadsheets for
                   3286:         # - the student level sheet of this user in course's homespace
                   3287:         # - the assessment level sheet for this resource 
                   3288:         #   for this user in user's homespace
1.553     albertel 3289: 	# - current conditional state info
1.325     www      3290: 	my $key=$uname.':'.$udom.':';
1.109     www      3291:         my $status=
1.299     matthew  3292: 	    &del('nohist_calculatedsheets',
1.391     matthew  3293: 		 [$key.'studentcalc:'],
1.620     albertel 3294: 		 $env{'course.'.$cid.'.domain'},
                   3295: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3296: 		.' '.
                   3297: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3298: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3299:         unless ($status eq 'ok ok') {
                   3300:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3301:                     $uname.' at '.$udom.' for '.
1.109     www      3302: 		    $symb.': '.$status);
1.133     albertel 3303:         }
1.553     albertel 3304: 	&delenv('user.state.'.$cid);
1.109     www      3305:     }
                   3306: }
                   3307: 
1.265     albertel 3308: sub get_scalar {
                   3309:     my ($string,$end) = @_;
                   3310:     my $value;
                   3311:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3312: 	$value = $1;
                   3313:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3314: 	$value = $1;
                   3315:     }
                   3316:     return &unescape($value);
                   3317: }
                   3318: 
                   3319: sub array2str {
                   3320:   my (@array) = @_;
                   3321:   my $result=&arrayref2str(\@array);
                   3322:   $result=~s/^__ARRAY_REF__//;
                   3323:   $result=~s/__END_ARRAY_REF__$//;
                   3324:   return $result;
                   3325: }
                   3326: 
1.204     albertel 3327: sub arrayref2str {
                   3328:   my ($arrayref) = @_;
1.265     albertel 3329:   my $result='__ARRAY_REF__';
1.204     albertel 3330:   foreach my $elem (@$arrayref) {
1.265     albertel 3331:     if(ref($elem) eq 'ARRAY') {
                   3332:       $result.=&arrayref2str($elem).'&';
                   3333:     } elsif(ref($elem) eq 'HASH') {
                   3334:       $result.=&hashref2str($elem).'&';
                   3335:     } elsif(ref($elem)) {
                   3336:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3337:     } else {
                   3338:       $result.=&escape($elem).'&';
                   3339:     }
                   3340:   }
                   3341:   $result=~s/\&$//;
1.265     albertel 3342:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3343:   return $result;
                   3344: }
                   3345: 
1.168     albertel 3346: sub hash2str {
1.204     albertel 3347:   my (%hash) = @_;
                   3348:   my $result=&hashref2str(\%hash);
1.265     albertel 3349:   $result=~s/^__HASH_REF__//;
                   3350:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3351:   return $result;
                   3352: }
                   3353: 
                   3354: sub hashref2str {
                   3355:   my ($hashref)=@_;
1.265     albertel 3356:   my $result='__HASH_REF__';
1.800     albertel 3357:   foreach my $key (sort(keys(%$hashref))) {
                   3358:     if (ref($key) eq 'ARRAY') {
                   3359:       $result.=&arrayref2str($key).'=';
                   3360:     } elsif (ref($key) eq 'HASH') {
                   3361:       $result.=&hashref2str($key).'=';
                   3362:     } elsif (ref($key)) {
1.265     albertel 3363:       $result.='=';
1.800     albertel 3364:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3365:     } else {
1.800     albertel 3366: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3367:     }
                   3368: 
1.800     albertel 3369:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3370:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3371:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3372:       $result.=&hashref2str($hashref->{$key}).'&';
                   3373:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3374:        $result.='&';
1.800     albertel 3375:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3376:     } else {
1.800     albertel 3377:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3378:     }
                   3379:   }
1.168     albertel 3380:   $result=~s/\&$//;
1.265     albertel 3381:   $result .= '__END_HASH_REF__';
1.168     albertel 3382:   return $result;
                   3383: }
                   3384: 
                   3385: sub str2hash {
1.265     albertel 3386:     my ($string)=@_;
                   3387:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3388:     return %$hash;
                   3389: }
                   3390: 
                   3391: sub str2hashref {
1.168     albertel 3392:   my ($string) = @_;
1.265     albertel 3393: 
                   3394:   my %hash;
                   3395: 
                   3396:   if($string !~ /^__HASH_REF__/) {
                   3397:       if (! ($string eq '' || !defined($string))) {
                   3398: 	  $hash{'error'}='Not hash reference';
                   3399:       }
                   3400:       return (\%hash, $string);
                   3401:   }
                   3402: 
                   3403:   $string =~ s/^__HASH_REF__//;
                   3404: 
                   3405:   while($string !~ /^__END_HASH_REF__/) {
                   3406:       #key
                   3407:       my $key='';
                   3408:       if($string =~ /^__HASH_REF__/) {
                   3409:           ($key, $string)=&str2hashref($string);
                   3410:           if(defined($key->{'error'})) {
                   3411:               $hash{'error'}='Bad data';
                   3412:               return (\%hash, $string);
                   3413:           }
                   3414:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3415:           ($key, $string)=&str2arrayref($string);
                   3416:           if($key->[0] eq 'Array reference error') {
                   3417:               $hash{'error'}='Bad data';
                   3418:               return (\%hash, $string);
                   3419:           }
                   3420:       } else {
                   3421:           $string =~ s/^(.*?)=//;
1.267     albertel 3422: 	  $key=&unescape($1);
1.265     albertel 3423:       }
                   3424:       $string =~ s/^=//;
                   3425: 
                   3426:       #value
                   3427:       my $value='';
                   3428:       if($string =~ /^__HASH_REF__/) {
                   3429:           ($value, $string)=&str2hashref($string);
                   3430:           if(defined($value->{'error'})) {
                   3431:               $hash{'error'}='Bad data';
                   3432:               return (\%hash, $string);
                   3433:           }
                   3434:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3435:           ($value, $string)=&str2arrayref($string);
                   3436:           if($value->[0] eq 'Array reference error') {
                   3437:               $hash{'error'}='Bad data';
                   3438:               return (\%hash, $string);
                   3439:           }
                   3440:       } else {
                   3441: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3442:       }
                   3443:       $string =~ s/^&//;
                   3444: 
                   3445:       $hash{$key}=$value;
1.204     albertel 3446:   }
1.265     albertel 3447: 
                   3448:   $string =~ s/^__END_HASH_REF__//;
                   3449: 
                   3450:   return (\%hash, $string);
1.204     albertel 3451: }
                   3452: 
                   3453: sub str2array {
1.265     albertel 3454:     my ($string)=@_;
                   3455:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3456:     return @$array;
                   3457: }
                   3458: 
                   3459: sub str2arrayref {
1.204     albertel 3460:   my ($string) = @_;
1.265     albertel 3461:   my @array;
                   3462: 
                   3463:   if($string !~ /^__ARRAY_REF__/) {
                   3464:       if (! ($string eq '' || !defined($string))) {
                   3465: 	  $array[0]='Array reference error';
                   3466:       }
                   3467:       return (\@array, $string);
                   3468:   }
                   3469: 
                   3470:   $string =~ s/^__ARRAY_REF__//;
                   3471: 
                   3472:   while($string !~ /^__END_ARRAY_REF__/) {
                   3473:       my $value='';
                   3474:       if($string =~ /^__HASH_REF__/) {
                   3475:           ($value, $string)=&str2hashref($string);
                   3476:           if(defined($value->{'error'})) {
                   3477:               $array[0] ='Array reference error';
                   3478:               return (\@array, $string);
                   3479:           }
                   3480:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3481:           ($value, $string)=&str2arrayref($string);
                   3482:           if($value->[0] eq 'Array reference error') {
                   3483:               $array[0] ='Array reference error';
                   3484:               return (\@array, $string);
                   3485:           }
                   3486:       } else {
                   3487: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3488:       }
                   3489:       $string =~ s/^&//;
                   3490: 
                   3491:       push(@array, $value);
1.191     harris41 3492:   }
1.265     albertel 3493: 
                   3494:   $string =~ s/^__END_ARRAY_REF__//;
                   3495: 
                   3496:   return (\@array, $string);
1.168     albertel 3497: }
                   3498: 
1.167     albertel 3499: # -------------------------------------------------------------------Temp Store
                   3500: 
1.168     albertel 3501: sub tmpreset {
                   3502:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3503:   if (!$symb) {
                   3504:     $symb=&symbread();
1.620     albertel 3505:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3506:   }
                   3507:   $symb=escape($symb);
                   3508: 
1.620     albertel 3509:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3510:   $namespace=~s/\//\_/g;
                   3511:   $namespace=~s/\W//g;
                   3512: 
1.620     albertel 3513:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3514:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3515:   if ($domain eq 'public' && $stuname eq 'public') {
                   3516:       $stuname=$ENV{'REMOTE_ADDR'};
                   3517:   }
1.168     albertel 3518:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3519:   my %hash;
                   3520:   if (tie(%hash,'GDBM_File',
                   3521: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3522: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3523:     foreach my $key (keys(%hash)) {
1.180     albertel 3524:       if ($key=~ /:$symb/) {
1.168     albertel 3525: 	delete($hash{$key});
                   3526:       }
                   3527:     }
                   3528:   }
                   3529: }
                   3530: 
1.167     albertel 3531: sub tmpstore {
1.168     albertel 3532:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3533: 
                   3534:   if (!$symb) {
                   3535:     $symb=&symbread();
1.620     albertel 3536:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3537:   }
                   3538:   $symb=escape($symb);
                   3539: 
                   3540:   if (!$namespace) {
                   3541:     # I don't think we would ever want to store this for a course.
                   3542:     # it seems this will only be used if we don't have a course.
1.620     albertel 3543:     #$namespace=$env{'request.course.id'};
1.168     albertel 3544:     #if (!$namespace) {
1.620     albertel 3545:       $namespace=$env{'request.state'};
1.168     albertel 3546:     #}
                   3547:   }
                   3548:   $namespace=~s/\//\_/g;
                   3549:   $namespace=~s/\W//g;
1.620     albertel 3550:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3551:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3552:   if ($domain eq 'public' && $stuname eq 'public') {
                   3553:       $stuname=$ENV{'REMOTE_ADDR'};
                   3554:   }
1.168     albertel 3555:   my $now=time;
                   3556:   my %hash;
                   3557:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3558:   if (tie(%hash,'GDBM_File',
                   3559: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3560: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3561:     $hash{"version:$symb"}++;
                   3562:     my $version=$hash{"version:$symb"};
                   3563:     my $allkeys=''; 
                   3564:     foreach my $key (keys(%$storehash)) {
                   3565:       $allkeys.=$key.':';
1.591     albertel 3566:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3567:     }
                   3568:     $hash{"$version:$symb:timestamp"}=$now;
                   3569:     $allkeys.='timestamp';
                   3570:     $hash{"$version:keys:$symb"}=$allkeys;
                   3571:     if (untie(%hash)) {
                   3572:       return 'ok';
                   3573:     } else {
                   3574:       return "error:$!";
                   3575:     }
                   3576:   } else {
                   3577:     return "error:$!";
                   3578:   }
                   3579: }
1.167     albertel 3580: 
1.168     albertel 3581: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3582: 
1.168     albertel 3583: sub tmprestore {
                   3584:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3585: 
1.168     albertel 3586:   if (!$symb) {
                   3587:     $symb=&symbread();
1.620     albertel 3588:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3589:   }
                   3590:   $symb=escape($symb);
                   3591: 
1.620     albertel 3592:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3593: 
1.620     albertel 3594:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3595:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3596:   if ($domain eq 'public' && $stuname eq 'public') {
                   3597:       $stuname=$ENV{'REMOTE_ADDR'};
                   3598:   }
1.168     albertel 3599:   my %returnhash;
                   3600:   $namespace=~s/\//\_/g;
                   3601:   $namespace=~s/\W//g;
                   3602:   my %hash;
                   3603:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3604:   if (tie(%hash,'GDBM_File',
                   3605: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3606: 	  &GDBM_READER(),0640)) {
1.168     albertel 3607:     my $version=$hash{"version:$symb"};
                   3608:     $returnhash{'version'}=$version;
                   3609:     my $scope;
                   3610:     for ($scope=1;$scope<=$version;$scope++) {
                   3611:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3612:       my @keys=split(/:/,$vkeys);
                   3613:       my $key;
                   3614:       $returnhash{"$scope:keys"}=$vkeys;
                   3615:       foreach $key (@keys) {
1.591     albertel 3616: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3617: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3618:       }
                   3619:     }
1.168     albertel 3620:     if (!(untie(%hash))) {
                   3621:       return "error:$!";
                   3622:     }
                   3623:   } else {
                   3624:     return "error:$!";
                   3625:   }
                   3626:   return %returnhash;
1.167     albertel 3627: }
                   3628: 
1.9       www      3629: # ----------------------------------------------------------------------- Store
                   3630: 
                   3631: sub store {
1.124     www      3632:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3633:     my $home='';
                   3634: 
1.168     albertel 3635:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3636: 
1.213     www      3637:     $symb=&symbclean($symb);
1.122     albertel 3638:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3639: 
1.620     albertel 3640:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3641:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3642: 
                   3643:     &devalidate($symb,$stuname,$domain);
1.109     www      3644: 
                   3645:     $symb=escape($symb);
1.187     www      3646:     if (!$namespace) { 
1.620     albertel 3647:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3648:           return ''; 
                   3649:        } 
                   3650:     }
1.620     albertel 3651:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3652: 
                   3653:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3654:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3655: 
1.12      www      3656:     my $namevalue='';
1.800     albertel 3657:     foreach my $key (keys(%$storehash)) {
                   3658:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3659:     }
1.12      www      3660:     $namevalue=~s/\&$//;
1.187     www      3661:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3662:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3663: }
                   3664: 
1.47      www      3665: # -------------------------------------------------------------- Critical Store
                   3666: 
                   3667: sub cstore {
1.124     www      3668:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3669:     my $home='';
                   3670: 
1.168     albertel 3671:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3672: 
1.213     www      3673:     $symb=&symbclean($symb);
1.122     albertel 3674:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3675: 
1.620     albertel 3676:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3677:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3678: 
                   3679:     &devalidate($symb,$stuname,$domain);
1.109     www      3680: 
                   3681:     $symb=escape($symb);
1.187     www      3682:     if (!$namespace) { 
1.620     albertel 3683:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3684:           return ''; 
                   3685:        } 
                   3686:     }
1.620     albertel 3687:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3688: 
                   3689:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3690:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3691: 
1.47      www      3692:     my $namevalue='';
1.800     albertel 3693:     foreach my $key (keys(%$storehash)) {
                   3694:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3695:     }
1.47      www      3696:     $namevalue=~s/\&$//;
1.187     www      3697:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3698:     return critical
                   3699:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3700: }
                   3701: 
1.9       www      3702: # --------------------------------------------------------------------- Restore
                   3703: 
                   3704: sub restore {
1.124     www      3705:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3706:     my $home='';
                   3707: 
1.168     albertel 3708:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3709: 
1.122     albertel 3710:     if (!$symb) {
                   3711:       unless ($symb=escape(&symbread())) { return ''; }
                   3712:     } else {
1.213     www      3713:       $symb=&escape(&symbclean($symb));
1.122     albertel 3714:     }
1.188     www      3715:     if (!$namespace) { 
1.620     albertel 3716:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3717:           return ''; 
                   3718:        } 
                   3719:     }
1.620     albertel 3720:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3721:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3722:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3723:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3724: 
1.12      www      3725:     my %returnhash=();
1.800     albertel 3726:     foreach my $line (split(/\&/,$answer)) {
                   3727: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3728:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3729:     }
1.75      www      3730:     my $version;
                   3731:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3732:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3733:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3734:        }
1.75      www      3735:     }
1.13      www      3736:     return %returnhash;
1.34      www      3737: }
                   3738: 
                   3739: # ---------------------------------------------------------- Course Description
                   3740: 
                   3741: sub coursedescription {
1.731     albertel 3742:     my ($courseid,$args)=@_;
1.34      www      3743:     $courseid=~s/^\///;
1.49      www      3744:     $courseid=~s/\_/\//g;
1.34      www      3745:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3746:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3747:     my $normalid=$cdomain.'_'.$cnum;
                   3748:     # need to always cache even if we get errors otherwise we keep 
                   3749:     # trying and trying and trying to get the course description.
                   3750:     my %envhash=();
                   3751:     my %returnhash=();
1.731     albertel 3752:     
                   3753:     my $expiretime=600;
                   3754:     if ($env{'request.course.id'} eq $normalid) {
                   3755: 	$expiretime=120;
                   3756:     }
                   3757: 
                   3758:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3759:     if (!$args->{'freshen_cache'}
                   3760: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3761: 	foreach my $key (keys(%env)) {
                   3762: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3763: 	    my ($setting) = $1;
                   3764: 	    $returnhash{$setting} = $env{$key};
                   3765: 	}
                   3766: 	return %returnhash;
                   3767:     }
                   3768: 
                   3769:     # get the data agin
                   3770:     if (!$args->{'one_time'}) {
                   3771: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3772:     }
1.811     albertel 3773: 
1.34      www      3774:     if ($chome ne 'no_host') {
1.302     albertel 3775:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3776:        if (!exists($returnhash{'con_lost'})) {
                   3777:            $returnhash{'home'}= $chome;
                   3778: 	   $returnhash{'domain'} = $cdomain;
                   3779: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3780:            if (!defined($returnhash{'type'})) {
                   3781:                $returnhash{'type'} = 'Course';
                   3782:            }
1.130     albertel 3783:            while (my ($name,$value) = each %returnhash) {
1.53      www      3784:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3785:            }
1.270     www      3786:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3787:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3788: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3789:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3790:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3791:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3792:        }
                   3793:     }
1.731     albertel 3794:     if (!$args->{'one_time'}) {
1.949     raeburn  3795: 	&appenv(\%envhash);
1.731     albertel 3796:     }
1.302     albertel 3797:     return %returnhash;
1.461     www      3798: }
                   3799: 
                   3800: # -------------------------------------------------See if a user is privileged
                   3801: 
                   3802: sub privileged {
                   3803:     my ($username,$domain)=@_;
                   3804:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3805: 			&homeserver($username,$domain));
1.1033    raeburn  3806:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3807:         ($rolesdump =~ /^error:/)) {
                   3808:         return 0;
                   3809:     }
1.461     www      3810:     my $now=time;
                   3811:     if ($rolesdump ne '') {
1.800     albertel 3812:         foreach my $entry (split(/&/,$rolesdump)) {
                   3813: 	    if ($entry!~/^rolesdef_/) {
                   3814: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3815: 		$area=~s/\_\w\w$//;
                   3816: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3817: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3818: 		    my $active=1;
                   3819: 		    if ($tend) {
                   3820: 			if ($tend<$now) { $active=0; }
                   3821: 		    }
                   3822: 		    if ($tstart) {
                   3823: 			if ($tstart>$now) { $active=0; }
                   3824: 		    }
                   3825: 		    if ($active) { return 1; }
                   3826: 		}
                   3827: 	    }
                   3828: 	}
                   3829:     }
                   3830:     return 0;
1.9       www      3831: }
1.1       albertel 3832: 
1.103     harris41 3833: # -------------------------------------------------------- Get user privileges
1.11      www      3834: 
                   3835: sub rolesinit {
                   3836:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  3837:     my $now=time;
                   3838:     my %userroles = ('user.login.time' => $now);
1.11      www      3839:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033    raeburn  3840:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3841:         ($rolesdump =~ /^error:/)) { 
                   3842:         return \%userroles;
                   3843:     }
1.11      www      3844:     my %allroles=();
1.678     raeburn  3845:     my %allgroups=();   
                   3846:     my $group_privs;
1.11      www      3847: 
                   3848:     if ($rolesdump ne '') {
1.800     albertel 3849:         foreach my $entry (split(/&/,$rolesdump)) {
                   3850: 	  if ($entry!~/^rolesdef_/) {
                   3851:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3852: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3853:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3854: 	    if ($role=~/^cr/) { 
1.807     albertel 3855: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3856: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3857: 		    ($tend,$tstart)=split('_',$trest);
                   3858: 		} else {
                   3859: 		    $trole=$role;
                   3860: 		}
1.678     raeburn  3861:             } elsif ($role =~ m|^gr/|) {
                   3862:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3863:                 ($trole,$group_privs) = split(/\//,$trole);
                   3864:                 $group_privs = &unescape($group_privs);
1.587     albertel 3865: 	    } else {
                   3866: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3867: 	    }
1.743     albertel 3868: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3869: 					 $username);
                   3870: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3871:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3872:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3873:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3874: 		my $spec=$trole.'.'.$area;
                   3875: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3876: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3877:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3878:                 } elsif ($trole eq 'gr') {
                   3879:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3880: 		} else {
1.567     raeburn  3881:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3882: 		}
1.12      www      3883:             }
1.662     raeburn  3884:           }
1.191     harris41 3885:         }
1.743     albertel 3886:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3887:         $userroles{'user.adv'}    = $adv;
                   3888: 	$userroles{'user.author'} = $author;
1.620     albertel 3889:         $env{'user.adv'}=$adv;
1.11      www      3890:     }
1.743     albertel 3891:     return \%userroles;  
1.11      www      3892: }
                   3893: 
1.567     raeburn  3894: sub set_arearole {
                   3895:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3896: # log the associated role with the area
                   3897:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3898:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3899: }
                   3900: 
                   3901: sub custom_roleprivs {
                   3902:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3903:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3904:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3905:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3906:         my ($rdummy,$roledef)=
                   3907:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3908:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3909:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3910:             if (defined($syspriv)) {
                   3911:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3912:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3913:             }
                   3914:             if ($tdomain ne '') {
                   3915:                 if (defined($dompriv)) {
                   3916:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3917:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3918:                 }
                   3919:                 if (($trest ne '') && (defined($coursepriv))) {
                   3920:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3921:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3922:                 }
                   3923:             }
                   3924:         }
                   3925:     }
                   3926: }
                   3927: 
1.678     raeburn  3928: sub group_roleprivs {
                   3929:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3930:     my $access = 1;
                   3931:     my $now = time;
                   3932:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3933:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3934:     if ($access) {
1.811     albertel 3935:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3936:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3937:     }
                   3938: }
1.567     raeburn  3939: 
                   3940: sub standard_roleprivs {
                   3941:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3942:     if (defined($pr{$trole.':s'})) {
                   3943:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3944:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3945:     }
                   3946:     if ($tdomain ne '') {
                   3947:         if (defined($pr{$trole.':d'})) {
                   3948:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3949:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3950:         }
                   3951:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3952:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3953:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3954:         }
                   3955:     }
                   3956: }
                   3957: 
                   3958: sub set_userprivs {
1.678     raeburn  3959:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3960:     my $author=0;
                   3961:     my $adv=0;
1.678     raeburn  3962:     my %grouproles = ();
                   3963:     if (keys(%{$allgroups}) > 0) {
1.1000    raeburn  3964:         foreach my $role (keys(%{$allroles})) {
1.681     raeburn  3965:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3966:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3967:                 $trole = $1;
                   3968:                 $area = $2;
1.681     raeburn  3969:                 $sec = $3;
                   3970:                 $extendedarea = $area.$sec;
                   3971:                 if (exists($$allgroups{$area})) {
                   3972:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3973:                         my $spec = $trole.'.'.$extendedarea;
                   3974:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3975:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3976:                     }
                   3977:                 }
                   3978:             }
                   3979:         }
                   3980:     }
1.800     albertel 3981:     foreach my $group (keys(%grouproles)) {
                   3982:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3983:     }
1.800     albertel 3984:     foreach my $role (keys(%{$allroles})) {
                   3985:         my %thesepriv;
1.941     raeburn  3986:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3987:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3988:             if ($item ne '') {
                   3989:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3990:                 if ($restrictions eq '') {
                   3991:                     $thesepriv{$privilege}='F';
                   3992:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3993:                     $thesepriv{$privilege}.=$restrictions;
                   3994:                 }
                   3995:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3996:             }
                   3997:         }
                   3998:         my $thesestr='';
1.800     albertel 3999:         foreach my $priv (keys(%thesepriv)) {
                   4000: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4001: 	}
                   4002:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4003:     }
                   4004:     return ($author,$adv);
                   4005: }
                   4006: 
1.994     raeburn  4007: sub role_status {
1.1002    raeburn  4008:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4009:     my @pwhere = ();
                   4010:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4011:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4012:         unless (!defined($$role) || $$role eq '') {
                   4013:             $$where=join('.',@pwhere);
                   4014:             $$trolecode=$$role.'.'.$$where;
                   4015:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4016:             $$tstatus='is';
                   4017:             if ($$tstart && $$tstart>$then) {
                   4018:                 $$tstatus='future';
1.1034    raeburn  4019:                 if ($$tstart<$now) {
                   4020:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4021:                         if (($$where ne '') && ($$role ne '')) {
                   4022:                             my (%allroles,%allgroups,$group_privs);
                   4023:                             my %userroles = (
                   4024:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4025:                             );
                   4026:                             my $spec=$$role.'.'.$$where;
                   4027:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4028:                             if ($$role eq 'gr') {
                   4029:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4030:                                                     $env{'user.name'})=@_;
                   4031:                                 my ($trole) = split('_',$role,1);
                   4032:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4033:                                 $group_privs = &unescape($group_privs);
                   4034:                             }
                   4035:                             if ($$role =~ /^cr\//) {
                   4036:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
                   4037:                             } elsif ($$role eq 'gr') {
                   4038:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4039:                                                     $env{'user.name'});
                   4040:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
                   4041:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4042:                                 $group_privs = &unescape($group_privs);
                   4043:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
                   4044:                             } else {
                   4045:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4046:                             }
                   4047:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4048:                             &appenv(\%userroles,[$$role,'cm']);
                   4049:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4050:                         }
                   4051:                     }
1.1034    raeburn  4052:                     $$tstatus = 'is';
1.1002    raeburn  4053:                 }
1.994     raeburn  4054:             }
                   4055:             if ($$tend) {
                   4056:                 if ($$tend<$then) {
                   4057:                     $$tstatus='expired';
                   4058:                 } elsif ($$tend<$now) {
                   4059:                     $$tstatus='will_not';
                   4060:                 }
                   4061:             }
                   4062:         }
                   4063:     }
                   4064: }
                   4065: 
                   4066: sub check_adhoc_privs {
1.1002    raeburn  4067:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4068:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4069:     if ($env{$cckey}) {
                   4070:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4071:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4072:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4073:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4074:         }
                   4075:     } else {
                   4076:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4077:     }
                   4078: }
                   4079: 
                   4080: sub set_adhoc_privileges {
                   4081: # role can be cc or ca
                   4082:     my ($dcdom,$pickedcourse,$role) = @_;
                   4083:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4084:     my $spec = $role.'.'.$area;
                   4085:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4086:                                   $env{'user.name'});
                   4087:     my %ccrole = ();
                   4088:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4089:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4090:     &appenv(\%userroles,[$role,'cm']);
                   4091:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4092:     &appenv( {'request.role'        => $spec,
                   4093:               'request.role.domain' => $dcdom,
                   4094:               'request.course.sec'  => ''
                   4095:              }
                   4096:            );
                   4097:     my $tadv=0;
                   4098:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4099:     &appenv({'request.role.adv'    => $tadv});
                   4100: }
                   4101: 
1.12      www      4102: # --------------------------------------------------------------- get interface
                   4103: 
                   4104: sub get {
1.131     albertel 4105:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4106:    my $items='';
1.800     albertel 4107:    foreach my $item (@$storearr) {
                   4108:        $items.=&escape($item).'&';
1.191     harris41 4109:    }
1.12      www      4110:    $items=~s/\&$//;
1.620     albertel 4111:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4112:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4113:    my $uhome=&homeserver($uname,$udomain);
                   4114: 
1.133     albertel 4115:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4116:    my @pairs=split(/\&/,$rep);
1.273     albertel 4117:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4118:      return @pairs;
                   4119:    }
1.15      www      4120:    my %returnhash=();
1.42      www      4121:    my $i=0;
1.800     albertel 4122:    foreach my $item (@$storearr) {
                   4123:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4124:       $i++;
1.191     harris41 4125:    }
1.15      www      4126:    return %returnhash;
1.27      www      4127: }
                   4128: 
                   4129: # --------------------------------------------------------------- del interface
                   4130: 
                   4131: sub del {
1.133     albertel 4132:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4133:    my $items='';
1.800     albertel 4134:    foreach my $item (@$storearr) {
                   4135:        $items.=&escape($item).'&';
1.191     harris41 4136:    }
1.984     neumanie 4137: 
1.27      www      4138:    $items=~s/\&$//;
1.620     albertel 4139:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4140:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4141:    my $uhome=&homeserver($uname,$udomain);
                   4142:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4143: }
                   4144: 
                   4145: # -------------------------------------------------------------- dump interface
                   4146: 
                   4147: sub dump {
1.755     albertel 4148:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4149:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4150:     if (!$uname) { $uname=$env{'user.name'}; }
                   4151:     my $uhome=&homeserver($uname,$udomain);
                   4152:     if ($regexp) {
                   4153: 	$regexp=&escape($regexp);
                   4154:     } else {
                   4155: 	$regexp='.';
                   4156:     }
                   4157:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4158:     my @pairs=split(/\&/,$rep);
                   4159:     my %returnhash=();
                   4160:     foreach my $item (@pairs) {
                   4161: 	my ($key,$value)=split(/=/,$item,2);
                   4162: 	$key = &unescape($key);
                   4163: 	next if ($key =~ /^error: 2 /);
                   4164: 	$returnhash{$key}=&thaw_unescape($value);
                   4165:     }
                   4166:     return %returnhash;
1.407     www      4167: }
                   4168: 
1.717     albertel 4169: # --------------------------------------------------------- dumpstore interface
                   4170: 
                   4171: sub dumpstore {
                   4172:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4173:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4174:    if (!$uname) { $uname=$env{'user.name'}; }
                   4175:    my $uhome=&homeserver($uname,$udomain);
                   4176:    if ($regexp) {
                   4177:        $regexp=&escape($regexp);
                   4178:    } else {
                   4179:        $regexp='.';
                   4180:    }
                   4181:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4182:    my @pairs=split(/\&/,$rep);
                   4183:    my %returnhash=();
                   4184:    foreach my $item (@pairs) {
                   4185:        my ($key,$value)=split(/=/,$item,2);
                   4186:        next if ($key =~ /^error: 2 /);
                   4187:        $returnhash{$key}=&thaw_unescape($value);
                   4188:    }
                   4189:    return %returnhash;
1.717     albertel 4190: }
                   4191: 
1.407     www      4192: # -------------------------------------------------------------- keys interface
                   4193: 
                   4194: sub getkeys {
                   4195:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4196:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4197:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4198:    my $uhome=&homeserver($uname,$udomain);
                   4199:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4200:    my @keyarray=();
1.800     albertel 4201:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4202:       next if ($key =~ /^error: 2 /);
1.800     albertel 4203:       push(@keyarray,&unescape($key));
1.407     www      4204:    }
                   4205:    return @keyarray;
1.318     matthew  4206: }
                   4207: 
1.319     matthew  4208: # --------------------------------------------------------------- currentdump
                   4209: sub currentdump {
1.328     matthew  4210:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4211:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4212:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4213:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4214:    my $uhome = &homeserver($sname,$sdom);
                   4215:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4216:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4217:    #
1.318     matthew  4218:    my %returnhash=();
1.319     matthew  4219:    #
                   4220:    if ($rep eq "unknown_cmd") { 
                   4221:        # an old lond will not know currentdump
                   4222:        # Do a dump and make it look like a currentdump
1.822     albertel 4223:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4224:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4225:        my %hash = @tmp;
                   4226:        @tmp=();
1.424     matthew  4227:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4228:    } else {
                   4229:        my @pairs=split(/\&/,$rep);
1.800     albertel 4230:        foreach my $pair (@pairs) {
                   4231:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4232:            my ($symb,$param) = split(/:/,$key);
                   4233:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4234:                                                         &thaw_unescape($value);
1.319     matthew  4235:        }
1.191     harris41 4236:    }
1.12      www      4237:    return %returnhash;
1.424     matthew  4238: }
                   4239: 
                   4240: sub convert_dump_to_currentdump{
                   4241:     my %hash = %{shift()};
                   4242:     my %returnhash;
                   4243:     # Code ripped from lond, essentially.  The only difference
                   4244:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4245:     # we might run in to problems with parameter names =~ /^v\./
                   4246:     while (my ($key,$value) = each(%hash)) {
                   4247:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4248: 	$symb  = &unescape($symb);
                   4249: 	$param = &unescape($param);
1.424     matthew  4250:         next if ($v eq 'version' || $symb eq 'keys');
                   4251:         next if (exists($returnhash{$symb}) &&
                   4252:                  exists($returnhash{$symb}->{$param}) &&
                   4253:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4254:         $returnhash{$symb}->{$param}=$value;
                   4255:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4256:     }
                   4257:     #
                   4258:     # Remove all of the keys in the hashes which keep track of
                   4259:     # the version of the parameter.
                   4260:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4261:         # use a foreach because we are going to delete from the hash.
                   4262:         foreach my $key (keys(%$param_hash)) {
                   4263:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4264:         }
                   4265:     }
                   4266:     return \%returnhash;
1.12      www      4267: }
                   4268: 
1.627     albertel 4269: # ------------------------------------------------------ critical inc interface
                   4270: 
                   4271: sub cinc {
                   4272:     return &inc(@_,'critical');
                   4273: }
                   4274: 
1.449     matthew  4275: # --------------------------------------------------------------- inc interface
                   4276: 
                   4277: sub inc {
1.627     albertel 4278:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4279:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4280:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4281:     my $uhome=&homeserver($uname,$udomain);
                   4282:     my $items='';
                   4283:     if (! ref($store)) {
                   4284:         # got a single value, so use that instead
                   4285:         $items = &escape($store).'=&';
                   4286:     } elsif (ref($store) eq 'SCALAR') {
                   4287:         $items = &escape($$store).'=&';        
                   4288:     } elsif (ref($store) eq 'ARRAY') {
                   4289:         $items = join('=&',map {&escape($_);} @{$store});
                   4290:     } elsif (ref($store) eq 'HASH') {
                   4291:         while (my($key,$value) = each(%{$store})) {
                   4292:             $items.= &escape($key).'='.&escape($value).'&';
                   4293:         }
                   4294:     }
                   4295:     $items=~s/\&$//;
1.627     albertel 4296:     if ($critical) {
                   4297: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4298:     } else {
                   4299: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4300:     }
1.449     matthew  4301: }
                   4302: 
1.12      www      4303: # --------------------------------------------------------------- put interface
                   4304: 
                   4305: sub put {
1.134     albertel 4306:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4307:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4308:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4309:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4310:    my $items='';
1.800     albertel 4311:    foreach my $item (keys(%$storehash)) {
                   4312:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4313:    }
1.12      www      4314:    $items=~s/\&$//;
1.134     albertel 4315:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4316: }
                   4317: 
1.631     albertel 4318: # ------------------------------------------------------------ newput interface
                   4319: 
                   4320: sub newput {
                   4321:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4322:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4323:    if (!$uname) { $uname=$env{'user.name'}; }
                   4324:    my $uhome=&homeserver($uname,$udomain);
                   4325:    my $items='';
                   4326:    foreach my $key (keys(%$storehash)) {
                   4327:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4328:    }
                   4329:    $items=~s/\&$//;
                   4330:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4331: }
                   4332: 
                   4333: # ---------------------------------------------------------  putstore interface
                   4334: 
1.524     raeburn  4335: sub putstore {
1.715     albertel 4336:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4337:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4338:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4339:    my $uhome=&homeserver($uname,$udomain);
                   4340:    my $items='';
1.715     albertel 4341:    foreach my $key (keys(%$storehash)) {
                   4342:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4343:    }
1.715     albertel 4344:    $items=~s/\&$//;
1.716     albertel 4345:    my $esc_symb=&escape($symb);
                   4346:    my $esc_v=&escape($version);
1.715     albertel 4347:    my $reply =
1.716     albertel 4348:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4349: 	      $uhome);
                   4350:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4351:        # gfall back to way things use to be done
1.715     albertel 4352:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4353: 			    $uname);
1.524     raeburn  4354:    }
1.715     albertel 4355:    return $reply;
                   4356: }
                   4357: 
                   4358: sub old_putstore {
1.716     albertel 4359:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4360:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4361:     if (!$uname) { $uname=$env{'user.name'}; }
                   4362:     my $uhome=&homeserver($uname,$udomain);
                   4363:     my %newstorehash;
1.800     albertel 4364:     foreach my $item (keys(%$storehash)) {
                   4365: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4366: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4367:     }
                   4368:     my $items='';
                   4369:     my %allitems = ();
1.800     albertel 4370:     foreach my $item (keys(%newstorehash)) {
                   4371: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4372: 	    my $key = $1.':keys:'.$2;
                   4373: 	    $allitems{$key} .= $3.':';
                   4374: 	}
1.800     albertel 4375: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4376:     }
1.800     albertel 4377:     foreach my $item (keys(%allitems)) {
                   4378: 	$allitems{$item} =~ s/\:$//;
                   4379: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4380:     }
                   4381:     $items=~s/\&$//;
                   4382:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4383: }
                   4384: 
1.47      www      4385: # ------------------------------------------------------ critical put interface
                   4386: 
                   4387: sub cput {
1.134     albertel 4388:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4389:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4390:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4391:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4392:    my $items='';
1.800     albertel 4393:    foreach my $item (keys(%$storehash)) {
                   4394:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4395:    }
1.47      www      4396:    $items=~s/\&$//;
1.134     albertel 4397:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4398: }
                   4399: 
                   4400: # -------------------------------------------------------------- eget interface
                   4401: 
                   4402: sub eget {
1.133     albertel 4403:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4404:    my $items='';
1.800     albertel 4405:    foreach my $item (@$storearr) {
                   4406:        $items.=&escape($item).'&';
1.191     harris41 4407:    }
1.12      www      4408:    $items=~s/\&$//;
1.620     albertel 4409:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4410:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4411:    my $uhome=&homeserver($uname,$udomain);
                   4412:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4413:    my @pairs=split(/\&/,$rep);
                   4414:    my %returnhash=();
1.42      www      4415:    my $i=0;
1.800     albertel 4416:    foreach my $item (@$storearr) {
                   4417:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4418:       $i++;
1.191     harris41 4419:    }
1.12      www      4420:    return %returnhash;
                   4421: }
                   4422: 
1.667     albertel 4423: # ------------------------------------------------------------ tmpput interface
                   4424: sub tmpput {
1.802     raeburn  4425:     my ($storehash,$server,$context)=@_;
1.667     albertel 4426:     my $items='';
1.800     albertel 4427:     foreach my $item (keys(%$storehash)) {
                   4428: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4429:     }
                   4430:     $items=~s/\&$//;
1.802     raeburn  4431:     if (defined($context)) {
                   4432:         $items .= ':'.&escape($context);
                   4433:     }
1.667     albertel 4434:     return &reply("tmpput:$items",$server);
                   4435: }
                   4436: 
                   4437: # ------------------------------------------------------------ tmpget interface
                   4438: sub tmpget {
1.688     albertel 4439:     my ($token,$server)=@_;
                   4440:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4441:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4442:     my %returnhash;
                   4443:     foreach my $item (split(/\&/,$rep)) {
                   4444: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4445:         next if ($key =~ /^error: 2 /);
1.667     albertel 4446: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4447:     }
                   4448:     return %returnhash;
                   4449: }
                   4450: 
1.688     albertel 4451: # ------------------------------------------------------------ tmpget interface
                   4452: sub tmpdel {
                   4453:     my ($token,$server)=@_;
                   4454:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4455:     return &reply("tmpdel:$token",$server);
                   4456: }
                   4457: 
1.765     albertel 4458: # -------------------------------------------------- portfolio access checking
                   4459: 
                   4460: sub portfolio_access {
1.766     albertel 4461:     my ($requrl) = @_;
1.765     albertel 4462:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4463:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4464:     if ($result) {
                   4465:         my %setters;
                   4466:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4467:             my ($startblock,$endblock) =
                   4468:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4469:             if ($startblock && $endblock) {
                   4470:                 return 'B';
                   4471:             }
                   4472:         } else {
                   4473:             my ($startblock,$endblock) =
                   4474:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4475:             if ($startblock && $endblock) {
                   4476:                 return 'B';
                   4477:             }
                   4478:         }
                   4479:     }
1.765     albertel 4480:     if ($result eq 'ok') {
1.766     albertel 4481:        return 'F';
1.765     albertel 4482:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4483:        return 'A';
1.765     albertel 4484:     }
1.766     albertel 4485:     return '';
1.765     albertel 4486: }
                   4487: 
                   4488: sub get_portfolio_access {
1.767     albertel 4489:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4490: 
                   4491:     if (!ref($access_hash)) {
                   4492: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4493: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4494: 						   $file_name);
                   4495: 	$access_hash = $access_controls{$file_name};
                   4496:     }
                   4497: 
1.765     albertel 4498:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4499:     my $now = time;
                   4500:     if (ref($access_hash) eq 'HASH') {
                   4501:         foreach my $key (keys(%{$access_hash})) {
                   4502:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4503:             if ($start > $now) {
                   4504:                 next;
                   4505:             }
                   4506:             if ($end && $end<$now) {
                   4507:                 next;
                   4508:             }
                   4509:             if ($scope eq 'public') {
                   4510:                 $public = $key;
                   4511:                 last;
                   4512:             } elsif ($scope eq 'guest') {
                   4513:                 $guest = $key;
                   4514:             } elsif ($scope eq 'domains') {
                   4515:                 push(@domains,$key);
                   4516:             } elsif ($scope eq 'users') {
                   4517:                 push(@users,$key);
                   4518:             } elsif ($scope eq 'course') {
                   4519:                 push(@courses,$key);
                   4520:             } elsif ($scope eq 'group') {
                   4521:                 push(@groups,$key);
                   4522:             }
                   4523:         }
                   4524:         if ($public) {
                   4525:             return 'ok';
                   4526:         }
                   4527:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4528:             if ($guest) {
                   4529:                 return $guest;
                   4530:             }
                   4531:         } else {
                   4532:             if (@domains > 0) {
                   4533:                 foreach my $domkey (@domains) {
                   4534:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4535:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4536:                             return 'ok';
                   4537:                         }
                   4538:                     }
                   4539:                 }
                   4540:             }
                   4541:             if (@users > 0) {
                   4542:                 foreach my $userkey (@users) {
1.865     raeburn  4543:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4544:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4545:                             if (ref($item) eq 'HASH') {
                   4546:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4547:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4548:                                     return 'ok';
                   4549:                                 }
                   4550:                             }
                   4551:                         }
                   4552:                     } 
1.765     albertel 4553:                 }
                   4554:             }
                   4555:             my %roleshash;
                   4556:             my @courses_and_groups = @courses;
                   4557:             push(@courses_and_groups,@groups); 
                   4558:             if (@courses_and_groups > 0) {
                   4559:                 my (%allgroups,%allroles); 
                   4560:                 my ($start,$end,$role,$sec,$group);
                   4561:                 foreach my $envkey (%env) {
1.811     albertel 4562:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4563:                         my $cid = $2.'_'.$3; 
                   4564:                         if ($1 eq 'gr') {
                   4565:                             $group = $4;
                   4566:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4567:                         } else {
                   4568:                             if ($4 eq '') {
                   4569:                                 $sec = 'none';
                   4570:                             } else {
                   4571:                                 $sec = $4;
                   4572:                             }
                   4573:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4574:                         }
1.811     albertel 4575:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4576:                         my $cid = $2.'_'.$3;
                   4577:                         if ($4 eq '') {
                   4578:                             $sec = 'none';
                   4579:                         } else {
                   4580:                             $sec = $4;
                   4581:                         }
                   4582:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4583:                     }
                   4584:                 }
                   4585:                 if (keys(%allroles) == 0) {
                   4586:                     return;
                   4587:                 }
                   4588:                 foreach my $key (@courses_and_groups) {
                   4589:                     my %content = %{$$access_hash{$key}};
                   4590:                     my $cnum = $content{'number'};
                   4591:                     my $cdom = $content{'domain'};
                   4592:                     my $cid = $cdom.'_'.$cnum;
                   4593:                     if (!exists($allroles{$cid})) {
                   4594:                         next;
                   4595:                     }    
                   4596:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4597:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4598:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4599:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4600:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4601:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4602:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4603:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4604:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4605:                                         if (grep/^all$/,@sections) {
                   4606:                                             return 'ok';
                   4607:                                         } else {
                   4608:                                             if (grep/^$sec$/,@sections) {
                   4609:                                                 return 'ok';
                   4610:                                             }
                   4611:                                         }
                   4612:                                     }
                   4613:                                 }
                   4614:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4615:                                     if (grep/^none$/,@groups) {
                   4616:                                         return 'ok';
                   4617:                                     }
                   4618:                                 } else {
                   4619:                                     if (grep/^all$/,@groups) {
                   4620:                                         return 'ok';
                   4621:                                     } 
                   4622:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4623:                                         if (grep/^$group$/,@groups) {
                   4624:                                             return 'ok';
                   4625:                                         }
                   4626:                                     }
                   4627:                                 } 
                   4628:                             }
                   4629:                         }
                   4630:                     }
                   4631:                 }
                   4632:             }
                   4633:             if ($guest) {
                   4634:                 return $guest;
                   4635:             }
                   4636:         }
                   4637:     }
                   4638:     return;
                   4639: }
                   4640: 
                   4641: sub course_group_datechecker {
                   4642:     my ($dates,$now,$status) = @_;
                   4643:     my ($start,$end) = split(/\./,$dates);
                   4644:     if (!$start && !$end) {
                   4645:         return 'ok';
                   4646:     }
                   4647:     if (grep/^active$/,@{$status}) {
                   4648:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4649:             return 'ok';
                   4650:         }
                   4651:     }
                   4652:     if (grep/^previous$/,@{$status}) {
                   4653:         if ($end > $now ) {
                   4654:             return 'ok';
                   4655:         }
                   4656:     }
                   4657:     if (grep/^future$/,@{$status}) {
                   4658:         if ($start > $now) {
                   4659:             return 'ok';
                   4660:         }
                   4661:     }
                   4662:     return; 
                   4663: }
                   4664: 
                   4665: sub parse_portfolio_url {
                   4666:     my ($url) = @_;
                   4667: 
                   4668:     my ($type,$udom,$unum,$group,$file_name);
                   4669:     
1.823     albertel 4670:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4671: 	$type = 1;
                   4672:         $udom = $1;
                   4673:         $unum = $2;
                   4674:         $file_name = $3;
1.823     albertel 4675:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4676: 	$type = 2;
                   4677:         $udom = $1;
                   4678:         $unum = $2;
                   4679:         $group = $3;
                   4680:         $file_name = $3.'/'.$4;
                   4681:     }
                   4682:     if (wantarray) {
                   4683: 	return ($type,$udom,$unum,$file_name,$group);
                   4684:     }
                   4685:     return $type;
                   4686: }
                   4687: 
                   4688: sub is_portfolio_url {
                   4689:     my ($url) = @_;
                   4690:     return scalar(&parse_portfolio_url($url));
                   4691: }
                   4692: 
1.798     raeburn  4693: sub is_portfolio_file {
                   4694:     my ($file) = @_;
1.820     raeburn  4695:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4696:         return 1;
                   4697:     }
                   4698:     return;
                   4699: }
                   4700: 
1.976     raeburn  4701: sub usertools_access {
1.985     raeburn  4702:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4703:     my ($access,%tools);
                   4704:     if ($context eq '') {
                   4705:         $context = 'tools';
                   4706:     }
                   4707:     if ($context eq 'requestcourses') {
                   4708:         %tools = (
                   4709:                       official   => 1,
                   4710:                       unofficial => 1,
1.1006    raeburn  4711:                       community  => 1,
1.985     raeburn  4712:                  );
                   4713:     } else {
                   4714:         %tools = (
                   4715:                       aboutme   => 1,
                   4716:                       blog      => 1,
                   4717:                       portfolio => 1,
                   4718:                  );
                   4719:     }
1.976     raeburn  4720:     return if (!defined($tools{$tool}));
                   4721: 
                   4722:     if ((!defined($udom)) || (!defined($uname))) {
                   4723:         $udom = $env{'user.domain'};
                   4724:         $uname = $env{'user.name'};
                   4725:     }
                   4726: 
1.978     raeburn  4727:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4728:         if ($action ne 'reload') {
1.985     raeburn  4729:             if ($context eq 'requestcourses') {
                   4730:                 return $env{'environment.canrequest.'.$tool};
                   4731:             } else {
                   4732:                 return $env{'environment.availabletools.'.$tool};
                   4733:             }
                   4734:         }
1.976     raeburn  4735:     }
                   4736: 
                   4737:     my ($toolstatus,$inststatus);
                   4738: 
1.985     raeburn  4739:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4740:          ($action ne 'reload')) {
                   4741:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4742:         $inststatus = $env{'environment.inststatus'};
                   4743:     } else {
1.1025    raeburn  4744:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985     raeburn  4745:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4746:         $inststatus = $userenv{'inststatus'};
                   4747:     }
                   4748: 
                   4749:     if ($toolstatus ne '') {
                   4750:         if ($toolstatus) {
                   4751:             $access = 1;
                   4752:         } else {
                   4753:             $access = 0;
                   4754:         }
                   4755:         return $access;
                   4756:     }
                   4757: 
                   4758:     my $is_adv = &is_advanced_user($udom,$uname);
                   4759:     my %domdef = &get_domain_defaults($udom);
                   4760:     if (ref($domdef{$tool}) eq 'HASH') {
                   4761:         if ($is_adv) {
                   4762:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4763:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4764:                     $access = 1;
                   4765:                 } else {
                   4766:                     $access = 0;
                   4767:                 }
                   4768:                 return $access;
                   4769:             }
                   4770:         }
                   4771:         if ($inststatus ne '') {
                   4772:             my ($hasaccess,$hasnoaccess);
                   4773:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4774:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4775:                     if ($domdef{$tool}{$affiliation}) {
                   4776:                         $hasaccess = 1;
                   4777:                     } else {
                   4778:                         $hasnoaccess = 1;
                   4779:                     }
                   4780:                 }
                   4781:             }
                   4782:             if ($hasaccess || $hasnoaccess) {
                   4783:                 if ($hasaccess) {
                   4784:                     $access = 1;
                   4785:                 } elsif ($hasnoaccess) {
                   4786:                     $access = 0; 
                   4787:                 }
                   4788:                 return $access;
                   4789:             }
                   4790:         } else {
                   4791:             if ($domdef{$tool}{'default'} ne '') {
                   4792:                 if ($domdef{$tool}{'default'}) {
                   4793:                     $access = 1;
                   4794:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4795:                     $access = 0;
                   4796:                 }
                   4797:                 return $access;
                   4798:             }
                   4799:         }
                   4800:     } else {
1.985     raeburn  4801:         if ($context eq 'tools') {
                   4802:             $access = 1;
                   4803:         } else {
                   4804:             $access = 0;
                   4805:         }
1.976     raeburn  4806:         return $access;
                   4807:     }
                   4808: }
                   4809: 
                   4810: sub is_advanced_user {
                   4811:     my ($udom,$uname) = @_;
                   4812:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4813:     my %allroles;
                   4814:     my $is_adv;
                   4815:     foreach my $role (keys(%roleshash)) {
                   4816:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4817:         my $area = '/'.$tdomain.'/'.$trest;
                   4818:         if ($sec ne '') {
                   4819:             $area .= '/'.$sec;
                   4820:         }
                   4821:         if (($area ne '') && ($trole ne '')) {
                   4822:             my $spec=$trole.'.'.$area;
                   4823:             if ($trole =~ /^cr\//) {
                   4824:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4825:             } elsif ($trole ne 'gr') {
                   4826:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4827:             }
                   4828:         }
                   4829:     }
                   4830:     foreach my $role (keys(%allroles)) {
                   4831:         last if ($is_adv);
                   4832:         foreach my $item (split(/:/,$allroles{$role})) {
                   4833:             if ($item ne '') {
                   4834:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4835:                 if ($privilege eq 'adv') {
                   4836:                     $is_adv = 1;
                   4837:                     last;
                   4838:                 }
                   4839:             }
                   4840:         }
                   4841:     }
                   4842:     return $is_adv;
                   4843: }
1.798     raeburn  4844: 
1.1035    raeburn  4845: sub check_can_request {
1.1036    raeburn  4846:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  4847:     my $canreq = 0;
                   4848:     my ($types,$typename) = &Apache::loncommon::course_types();
                   4849:     my @options = ('approval','validate','autolimit');
                   4850:     my $optregex = join('|',@options);
                   4851:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   4852:         foreach my $type (@{$types}) {
                   4853:             if (&usertools_access($env{'user.name'},
                   4854:                                   $env{'user.domain'},
                   4855:                                   $type,undef,'requestcourses')) {
                   4856:                 $canreq ++;
1.1036    raeburn  4857:                 if (ref($request_domains) eq 'HASH') {
                   4858:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   4859:                 }
1.1035    raeburn  4860:                 if ($dom eq $env{'user.domain'}) {
                   4861:                     $can_request->{$type} = 1;
                   4862:                 }
                   4863:             }
                   4864:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   4865:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   4866:                 if (@curr > 0) {
1.1036    raeburn  4867:                     foreach my $item (@curr) {
                   4868:                         if (ref($request_domains) eq 'HASH') {
                   4869:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   4870:                             if ($otherdom ne '') {
                   4871:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   4872:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   4873:                                         push(@{$request_domains->{$type}},$otherdom);
                   4874:                                     }
                   4875:                                 } else {
                   4876:                                     push(@{$request_domains->{$type}},$otherdom);
                   4877:                                 }
                   4878:                             }
                   4879:                         }
                   4880:                     }
                   4881:                     unless($dom eq $env{'user.domain'}) {
                   4882:                         $canreq ++;
1.1035    raeburn  4883:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   4884:                             $can_request->{$type} = 1;
                   4885:                         }
                   4886:                     }
                   4887:                 }
                   4888:             }
                   4889:         }
                   4890:     }
                   4891:     return $canreq;
                   4892: }
                   4893: 
1.341     www      4894: # ---------------------------------------------- Custom access rule evaluation
                   4895: 
                   4896: sub customaccess {
                   4897:     my ($priv,$uri)=@_;
1.807     albertel 4898:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4899:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4900:     $udom = &LONCAPA::clean_domain($udom);
                   4901:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4902:     my $access=0;
1.800     albertel 4903:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4904: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4905: 	if ($type eq 'user') {
                   4906: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4907: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4908: 		if ($tdom) {
                   4909: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4910: 		}
1.896     albertel 4911: 		if ($tuname) {
                   4912: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4913: 		}
                   4914: 		$access=($effect eq 'allow');
                   4915: 		last;
                   4916: 	    }
                   4917: 	} else {
                   4918: 	    if ($role) {
                   4919: 		if ($role ne $urole) { next; }
                   4920: 	    }
                   4921: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4922: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4923: 		if ($tdom) {
                   4924: 		    if ($tdom ne $udom) { next; }
                   4925: 		}
                   4926: 		if ($tcrs) {
                   4927: 		    if ($tcrs ne $ucrs) { next; }
                   4928: 		}
                   4929: 		if ($tsec) {
                   4930: 		    if ($tsec ne $usec) { next; }
                   4931: 		}
                   4932: 		$access=($effect eq 'allow');
                   4933: 		last;
                   4934: 	    }
                   4935: 	    if ($realm eq '' && $role eq '') {
                   4936: 		$access=($effect eq 'allow');
                   4937: 	    }
1.402     bowersj2 4938: 	}
1.341     www      4939:     }
                   4940:     return $access;
                   4941: }
                   4942: 
1.103     harris41 4943: # ------------------------------------------------- Check for a user privilege
1.12      www      4944: 
                   4945: sub allowed {
1.810     raeburn  4946:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4947:     my $ver_orguri=$uri;
1.439     www      4948:     $uri=&deversion($uri);
1.152     www      4949:     my $orguri=$uri;
1.52      www      4950:     $uri=&declutter($uri);
1.809     raeburn  4951: 
1.810     raeburn  4952:     if ($priv eq 'evb') {
                   4953: # Evade communication block restrictions for specified role in a course
                   4954:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4955:             return $1;
                   4956:         } else {
                   4957:             return;
                   4958:         }
                   4959:     }
                   4960: 
1.620     albertel 4961:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4962: # Free bre access to adm and meta resources
1.775     albertel 4963:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4964: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4965: 	&& ($priv eq 'bre')) {
1.14      www      4966: 	return 'F';
1.159     www      4967:     }
                   4968: 
1.545     banghart 4969: # Free bre access to user's own portfolio contents
1.714     raeburn  4970:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4971:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4972: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4973:         my %setters;
                   4974:         my ($startblock,$endblock) = 
                   4975:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4976:         if ($startblock && $endblock) {
                   4977:             return 'B';
                   4978:         } else {
                   4979:             return 'F';
                   4980:         }
1.545     banghart 4981:     }
                   4982: 
1.762     raeburn  4983: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4984:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4985:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4986:         if (exists($env{'request.course.id'})) {
                   4987:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4988:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4989:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4990:                 my $courseprivid=$env{'request.course.id'};
                   4991:                 $courseprivid=~s/\_/\//;
                   4992:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4993:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4994:                     return $1; 
1.762     raeburn  4995:                 } else {
                   4996:                     if ($env{'request.course.sec'}) {
                   4997:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4998:                     }
                   4999:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5000:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5001:                         return $2;
                   5002:                     }
1.714     raeburn  5003:                 }
                   5004:             }
                   5005:         }
                   5006:     }
                   5007: 
1.159     www      5008: # Free bre to public access
                   5009: 
                   5010:     if ($priv eq 'bre') {
1.238     www      5011:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5012: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5013:            return 'F'; 
                   5014:         }
1.238     www      5015:         if ($copyright eq 'priv') {
                   5016:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5017: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5018: 		return '';
                   5019:             }
                   5020:         }
                   5021:         if ($copyright eq 'domain') {
                   5022:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5023: 	    unless (($env{'user.domain'} eq $1) ||
                   5024:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5025: 		return '';
                   5026:             }
1.262     matthew  5027:         }
1.620     albertel 5028:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5029:             # Library role, so allow browsing of resources in this domain.
                   5030:             return 'F';
1.238     www      5031:         }
1.341     www      5032:         if ($copyright eq 'custom') {
                   5033: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5034:         }
1.14      www      5035:     }
1.264     matthew  5036:     # Domain coordinator is trying to create a course
1.620     albertel 5037:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5038:         # uri is the requested domain in this case.
                   5039:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5040:         # a role of dc for the domain in question.
1.620     albertel 5041:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5042:     }
1.29      www      5043: 
1.52      www      5044:     my $thisallowed='';
                   5045:     my $statecond=0;
                   5046:     my $courseprivid='';
                   5047: 
1.1039    raeburn  5048:     my $ownaccess;
                   5049:     # Community Coordinator browsing resource space.
                   5050:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5051:         if ($uri eq '') {
                   5052:             $ownaccess = 1;
                   5053:         } else {
                   5054:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5055:                 my $udom = $env{'user.domain'};
                   5056:                 my $uname = $env{'user.name'};
                   5057:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5058:                     $ownaccess = 1;
1.1040    raeburn  5059:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5060:                     unless ($uri =~ m{\.\./}) {
                   5061:                         $ownaccess = 1;
                   5062:                     }
                   5063:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5064:                     my $now = time;
                   5065:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5066:                         my $adom = $1;
                   5067:                         foreach my $key (keys(%env)) {
                   5068:                             if ($key =~ m{^user\.role\.ca/\Q$adom\E}) {
                   5069:                                 my ($start,$end) = split('.',$env{$key});
                   5070:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5071:                                     $ownaccess = 1;
                   5072:                                     last;
                   5073:                                 }
                   5074:                             }
                   5075:                         }
                   5076:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5077:                         my $adom = $1;
                   5078:                         my $aname = $2;
                   5079:                         if ($env{"user.role.ca./$adom/$aname"}) {
                   5080:                             my ($start,$end) =
                   5081:                                 split('.',$env{"user.role.ca./$adom/$aname"});
                   5082:                             if (($now >= $start) && (!$end || $end < $now)) {
                   5083:                                 $ownaccess = 1;
                   5084:                             }
                   5085:                         }
                   5086:                     }
                   5087:                 }
                   5088:             }
                   5089:         }
                   5090:     }
                   5091: 
1.52      www      5092: # Course
                   5093: 
1.620     albertel 5094:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1039    raeburn  5095:         unless (($priv eq 'bro' && !$ownaccess)) {
                   5096:             $thisallowed.=$1;
                   5097:         }
1.52      www      5098:     }
1.29      www      5099: 
1.52      www      5100: # Domain
                   5101: 
1.620     albertel 5102:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5103:        =~/\Q$priv\E\&([^\:]*)/) {
1.1039    raeburn  5104:         unless (($priv eq 'bro' && !$ownaccess)) {
                   5105:             $thisallowed.=$1;
                   5106:         }
1.12      www      5107:     }
1.52      www      5108: 
                   5109: # Course: uri itself is a course
1.66      www      5110:     my $courseuri=$uri;
                   5111:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5112:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5113: 
1.620     albertel 5114:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5115:        =~/\Q$priv\E\&([^\:]*)/) {
1.1039    raeburn  5116:         unless (($priv eq 'bro' && !$ownaccess)) {
                   5117:             $thisallowed.=$1;
                   5118:         }
1.12      www      5119:     }
1.29      www      5120: 
1.665     albertel 5121: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5122: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5123:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5124: 	$thisallowed='';
1.671     raeburn  5125:         my ($match)=&is_on_map($uri);
                   5126:         if ($match) {
                   5127:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5128:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5129:                 $thisallowed.=$1;
                   5130:             }
                   5131:         } else {
1.705     albertel 5132:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5133:             if ($refuri) {
                   5134:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5135:                     $thisallowed='F';
1.671     raeburn  5136:                 } else {
                   5137:                     $refuri=&declutter($refuri);
                   5138:                     my ($match) = &is_on_map($refuri);
                   5139:                     if ($match) {
                   5140:                         $thisallowed='F';
                   5141:                     }
1.669     raeburn  5142:                 }
1.671     raeburn  5143:             }
                   5144:         }
1.314     www      5145:     }
1.492     albertel 5146: 
1.766     albertel 5147:     if ($priv eq 'bre'
                   5148: 	&& $thisallowed ne 'F' 
                   5149: 	&& $thisallowed ne '2'
                   5150: 	&& &is_portfolio_url($uri)) {
                   5151: 	$thisallowed = &portfolio_access($uri);
                   5152:     }
                   5153:     
1.52      www      5154: # Full access at system, domain or course-wide level? Exit.
1.29      www      5155:     if ($thisallowed=~/F/) {
                   5156: 	return 'F';
                   5157:     }
                   5158: 
1.52      www      5159: # If this is generating or modifying users, exit with special codes
1.29      www      5160: 
1.643     www      5161:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5162: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5163: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5164: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5165: 	    unless ($auname) { return $thisallowed; }
                   5166: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5167: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5168: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5169: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5170: 	}
1.52      www      5171: 	return $thisallowed;
                   5172:     }
                   5173: #
1.103     harris41 5174: # Gathered so far: system, domain and course wide privileges
1.52      www      5175: #
                   5176: # Course: See if uri or referer is an individual resource that is part of 
                   5177: # the course
                   5178: 
1.620     albertel 5179:     if ($env{'request.course.id'}) {
1.232     www      5180: 
1.620     albertel 5181:        $courseprivid=$env{'request.course.id'};
                   5182:        if ($env{'request.course.sec'}) {
                   5183:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5184:        }
                   5185:        $courseprivid=~s/\_/\//;
                   5186:        my $checkreferer=1;
1.232     www      5187:        my ($match,$cond)=&is_on_map($uri);
                   5188:        if ($match) {
                   5189:            $statecond=$cond;
1.620     albertel 5190:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5191:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5192:                $thisallowed.=$1;
                   5193:                $checkreferer=0;
                   5194:            }
1.29      www      5195:        }
1.83      www      5196:        
1.148     www      5197:        if ($checkreferer) {
1.620     albertel 5198: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5199:             unless ($refuri) {
1.800     albertel 5200:                 foreach my $key (keys(%env)) {
                   5201: 		    if ($key=~/^httpref\..*\*/) {
                   5202: 			my $pattern=$key;
1.156     www      5203:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5204:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5205:                         $pattern=~s/\//\\\//g;
1.152     www      5206:                         if ($orguri=~/$pattern/) {
1.800     albertel 5207: 			    $refuri=$env{$key};
1.148     www      5208:                         }
                   5209:                     }
1.191     harris41 5210:                 }
1.148     www      5211:             }
1.232     www      5212: 
1.148     www      5213:          if ($refuri) { 
1.152     www      5214: 	  $refuri=&declutter($refuri);
1.232     www      5215:           my ($match,$cond)=&is_on_map($refuri);
                   5216:             if ($match) {
                   5217:               my $refstatecond=$cond;
1.620     albertel 5218:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5219:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5220:                   $thisallowed.=$1;
1.53      www      5221:                   $uri=$refuri;
                   5222:                   $statecond=$refstatecond;
1.52      www      5223:               }
                   5224:           }
1.148     www      5225:         }
1.29      www      5226:        }
1.52      www      5227:    }
1.29      www      5228: 
1.52      www      5229: #
1.103     harris41 5230: # Gathered now: all privileges that could apply, and condition number
1.52      www      5231: # 
                   5232: #
                   5233: # Full or no access?
                   5234: #
1.29      www      5235: 
1.52      www      5236:     if ($thisallowed=~/F/) {
                   5237: 	return 'F';
                   5238:     }
1.29      www      5239: 
1.52      www      5240:     unless ($thisallowed) {
                   5241:         return '';
                   5242:     }
1.29      www      5243: 
1.52      www      5244: # Restrictions exist, deal with them
                   5245: #
                   5246: #   C:according to course preferences
                   5247: #   R:according to resource settings
                   5248: #   L:unless locked
                   5249: #   X:according to user session state
                   5250: #
                   5251: 
                   5252: # Possibly locked functionality, check all courses
1.54      www      5253: # Locks might take effect only after 10 minutes cache expiration for other
                   5254: # courses, and 2 minutes for current course
1.52      www      5255: 
                   5256:     my $envkey;
                   5257:     if ($thisallowed=~/L/) {
1.1000    raeburn  5258:         foreach $envkey (keys(%env)) {
1.54      www      5259:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5260:                my $courseid=$2;
                   5261:                my $roleid=$1.'.'.$2;
1.92      www      5262:                $courseid=~s/^\///;
1.54      www      5263:                my $expiretime=600;
1.620     albertel 5264:                if ($env{'request.role'} eq $roleid) {
1.54      www      5265: 		  $expiretime=120;
                   5266:                }
                   5267: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5268:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5269:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5270: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5271:                }
1.620     albertel 5272:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5273:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5274: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5275:                        &log($env{'user.domain'},$env{'user.name'},
                   5276:                             $env{'user.home'},
1.57      www      5277:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5278:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5279:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5280: 		       return '';
                   5281:                    }
                   5282:                }
1.620     albertel 5283:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5284:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5285: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5286:                        &log($env{'user.domain'},$env{'user.name'},
                   5287:                             $env{'user.home'},
1.57      www      5288:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5289:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5290:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5291: 		       return '';
                   5292:                    }
                   5293:                }
                   5294: 	   }
1.29      www      5295:        }
1.52      www      5296:     }
                   5297:    
                   5298: #
                   5299: # Rest of the restrictions depend on selected course
                   5300: #
                   5301: 
1.620     albertel 5302:     unless ($env{'request.course.id'}) {
1.766     albertel 5303: 	if ($thisallowed eq 'A') {
                   5304: 	    return 'A';
1.814     raeburn  5305:         } elsif ($thisallowed eq 'B') {
                   5306:             return 'B';
1.766     albertel 5307: 	} else {
                   5308: 	    return '1';
                   5309: 	}
1.52      www      5310:     }
1.29      www      5311: 
1.52      www      5312: #
                   5313: # Now user is definitely in a course
                   5314: #
1.53      www      5315: 
                   5316: 
                   5317: # Course preferences
                   5318: 
                   5319:    if ($thisallowed=~/C/) {
1.620     albertel 5320:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5321:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5322:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5323: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5324: 	   if ($priv ne 'pch') { 
                   5325: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5326: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5327: 			$env{'request.course.id'});
                   5328: 	   }
1.237     www      5329:            return '';
                   5330:        }
                   5331: 
1.620     albertel 5332:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5333: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5334: 	   if ($priv ne 'pch') { 
                   5335: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5336: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5337: 			$env{'request.course.id'});
                   5338: 	   }
1.54      www      5339:            return '';
                   5340:        }
1.53      www      5341:    }
                   5342: 
                   5343: # Resource preferences
                   5344: 
                   5345:    if ($thisallowed=~/R/) {
1.620     albertel 5346:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5347:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5348: 	   if ($priv ne 'pch') { 
                   5349: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5350: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5351: 	   }
                   5352: 	   return '';
1.54      www      5353:        }
1.53      www      5354:    }
1.30      www      5355: 
1.246     www      5356: # Restricted by state or randomout?
1.30      www      5357: 
1.52      www      5358:    if ($thisallowed=~/X/) {
1.620     albertel 5359:       if ($env{'acc.randomout'}) {
1.579     albertel 5360: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5361:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5362:             return ''; 
                   5363:          }
1.247     www      5364:       }
                   5365:       if (&condval($statecond)) {
1.52      www      5366: 	 return '2';
                   5367:       } else {
                   5368:          return '';
                   5369:       }
                   5370:    }
1.30      www      5371: 
1.766     albertel 5372:     if ($thisallowed eq 'A') {
                   5373: 	return 'A';
1.814     raeburn  5374:     } elsif ($thisallowed eq 'B') {
                   5375:         return 'B';
1.766     albertel 5376:     }
1.52      www      5377:    return 'F';
1.232     www      5378: }
                   5379: 
1.710     albertel 5380: sub split_uri_for_cond {
                   5381:     my $uri=&deversion(&declutter(shift));
                   5382:     my @uriparts=split(/\//,$uri);
                   5383:     my $filename=pop(@uriparts);
                   5384:     my $pathname=join('/',@uriparts);
                   5385:     return ($pathname,$filename);
                   5386: }
1.232     www      5387: # --------------------------------------------------- Is a resource on the map?
                   5388: 
                   5389: sub is_on_map {
1.710     albertel 5390:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5391:     #Trying to find the conditional for the file
1.620     albertel 5392:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5393: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5394:     if ($match) {
1.289     bowersj2 5395: 	return (1,$1);
                   5396:     } else {
1.434     www      5397: 	return (0,0);
1.289     bowersj2 5398:     }
1.12      www      5399: }
                   5400: 
1.427     www      5401: # --------------------------------------------------------- Get symb from alias
                   5402: 
                   5403: sub get_symb_from_alias {
                   5404:     my $symb=shift;
                   5405:     my ($map,$resid,$url)=&decode_symb($symb);
                   5406: # Already is a symb
                   5407:     if ($url) { return $symb; }
                   5408: # Must be an alias
                   5409:     my $aliassymb='';
                   5410:     my %bighash;
1.620     albertel 5411:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5412:                             &GDBM_READER(),0640)) {
                   5413:         my $rid=$bighash{'mapalias_'.$symb};
                   5414: 	if ($rid) {
                   5415: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5416: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5417: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5418: 	}
                   5419:         untie %bighash;
                   5420:     }
                   5421:     return $aliassymb;
                   5422: }
                   5423: 
1.12      www      5424: # ----------------------------------------------------------------- Define Role
                   5425: 
                   5426: sub definerole {
                   5427:   if (allowed('mcr','/')) {
                   5428:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5429:     foreach my $role (split(':',$sysrole)) {
                   5430: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5431:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5432:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5433: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5434:                return "refused:s:$crole&$cqual"; 
                   5435:             }
                   5436:         }
1.191     harris41 5437:     }
1.800     albertel 5438:     foreach my $role (split(':',$domrole)) {
                   5439: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5440:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5441:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5442: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5443:                return "refused:d:$crole&$cqual"; 
                   5444:             }
                   5445:         }
1.191     harris41 5446:     }
1.800     albertel 5447:     foreach my $role (split(':',$courole)) {
                   5448: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5449:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5450:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5451: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5452:                return "refused:c:$crole&$cqual"; 
                   5453:             }
                   5454:         }
1.191     harris41 5455:     }
1.620     albertel 5456:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5457:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5458: 	        "rolesdef_$rolename=".
                   5459:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5460:     return reply($command,$env{'user.home'});
1.12      www      5461:   } else {
                   5462:     return 'refused';
                   5463:   }
1.105     harris41 5464: }
                   5465: 
                   5466: # ---------------- Make a metadata query against the network of library servers
                   5467: 
                   5468: sub metadata_query {
1.244     matthew  5469:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5470:     my %rhash;
1.845     albertel 5471:     my %libserv = &all_library();
1.244     matthew  5472:     my @server_list = (defined($server_array) ? @$server_array
                   5473:                                               : keys(%libserv) );
                   5474:     for my $server (@server_list) {
1.118     harris41 5475: 	unless ($custom or $customshow) {
                   5476: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5477: 	    $rhash{$server}=$reply;
                   5478: 	}
                   5479: 	else {
                   5480: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5481: 			     &escape($custom).':'.&escape($customshow),
                   5482: 			     $server);
                   5483: 	    $rhash{$server}=$reply;
                   5484: 	}
1.112     harris41 5485:     }
1.118     harris41 5486:     return \%rhash;
1.240     www      5487: }
                   5488: 
                   5489: # ----------------------------------------- Send log queries and wait for reply
                   5490: 
                   5491: sub log_query {
                   5492:     my ($uname,$udom,$query,%filters)=@_;
                   5493:     my $uhome=&homeserver($uname,$udom);
                   5494:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5495:     my $uhost=&hostname($uhome);
1.800     albertel 5496:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5497:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5498:                        $uhome);
1.479     albertel 5499:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5500:     return get_query_reply($queryid);
                   5501: }
                   5502: 
1.818     raeburn  5503: # -------------------------- Update MySQL table for portfolio file
                   5504: 
                   5505: sub update_portfolio_table {
1.821     raeburn  5506:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5507:     if ($group ne '') {
                   5508:         $file_name =~s /^\Q$group\E//;
                   5509:     }
1.818     raeburn  5510:     my $homeserver = &homeserver($uname,$udom);
                   5511:     my $queryid=
1.821     raeburn  5512:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5513:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5514:     my $reply = &get_query_reply($queryid);
                   5515:     return $reply;
                   5516: }
                   5517: 
1.899     raeburn  5518: # -------------------------- Update MySQL allusers table
                   5519: 
                   5520: sub update_allusers_table {
                   5521:     my ($uname,$udom,$names) = @_;
                   5522:     my $homeserver = &homeserver($uname,$udom);
                   5523:     my $queryid=
                   5524:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5525:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5526:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5527:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5528:                'generation='.&escape($names->{'generation'}).'%%'.
                   5529:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5530:                'id='.&escape($names->{'id'}),$homeserver);
                   5531:     my $reply = &get_query_reply($queryid);
                   5532:     return $reply;
                   5533: }
                   5534: 
1.508     raeburn  5535: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5536: 
                   5537: sub fetch_enrollment_query {
1.511     raeburn  5538:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5539:     my $homeserver;
1.547     raeburn  5540:     my $maxtries = 1;
1.508     raeburn  5541:     if ($context eq 'automated') {
                   5542:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5543:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5544:     } else {
                   5545:         $homeserver = &homeserver($cnum,$dom);
                   5546:     }
1.838     albertel 5547:     my $host=&hostname($homeserver);
1.506     raeburn  5548:     my $cmd = '';
1.1000    raeburn  5549:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5550:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5551:     }
                   5552:     $cmd =~ s/%%$//;
                   5553:     $cmd = &escape($cmd);
                   5554:     my $query = 'fetchenrollment';
1.620     albertel 5555:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5556:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5557:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5558:         return 'error: '.$queryid;
                   5559:     }
1.506     raeburn  5560:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5561:     my $tries = 1;
                   5562:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5563:         $reply = &get_query_reply($queryid);
                   5564:         $tries ++;
                   5565:     }
1.526     raeburn  5566:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5567:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5568:     } else {
1.901     albertel 5569:         my @responses = split(/:/,$reply);
1.515     raeburn  5570:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5571:             foreach my $line (@responses) {
                   5572:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5573:                 $$replyref{$key} = $value;
                   5574:             }
                   5575:         } else {
1.506     raeburn  5576:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5577:             foreach my $line (@responses) {
                   5578:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5579:                 $$replyref{$key} = $value;
                   5580:                 if ($value > 0) {
1.800     albertel 5581:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5582:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5583:                         my $destname = $pathname.'/'.$filename;
                   5584:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5585:                         if ($xml_classlist =~ /^error/) {
                   5586:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5587:                         } else {
1.506     raeburn  5588:                             if ( open(FILE,">$destname") ) {
                   5589:                                 print FILE &unescape($xml_classlist);
                   5590:                                 close(FILE);
1.526     raeburn  5591:                             } else {
                   5592:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5593:                             }
                   5594:                         }
                   5595:                     }
                   5596:                 }
                   5597:             }
                   5598:         }
                   5599:         return 'ok';
                   5600:     }
                   5601:     return 'error';
                   5602: }
                   5603: 
1.242     www      5604: sub get_query_reply {
                   5605:     my $queryid=shift;
1.240     www      5606:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5607:     my $reply='';
                   5608:     for (1..100) {
                   5609: 	sleep 2;
                   5610:         if (-e $replyfile.'.end') {
1.448     albertel 5611: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5612: 		$reply = join('',<$fh>);
                   5613: 		close($fh);
1.240     www      5614: 	   } else { return 'error: reply_file_error'; }
1.242     www      5615:            return &unescape($reply);
                   5616: 	}
1.240     www      5617:     }
1.242     www      5618:     return 'timeout:'.$queryid;
1.240     www      5619: }
                   5620: 
                   5621: sub courselog_query {
1.241     www      5622: #
                   5623: # possible filters:
                   5624: # url: url or symb
                   5625: # username
                   5626: # domain
                   5627: # action: view, submit, grade
                   5628: # start: timestamp
                   5629: # end: timestamp
                   5630: #
1.240     www      5631:     my (%filters)=@_;
1.620     albertel 5632:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5633:     if ($filters{'url'}) {
                   5634: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5635:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5636:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5637:     }
1.620     albertel 5638:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5639:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5640:     return &log_query($cname,$cdom,'courselog',%filters);
                   5641: }
                   5642: 
                   5643: sub userlog_query {
1.858     raeburn  5644: #
                   5645: # possible filters:
                   5646: # action: log check role
                   5647: # start: timestamp
                   5648: # end: timestamp
                   5649: #
1.240     www      5650:     my ($uname,$udom,%filters)=@_;
                   5651:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5652: }
                   5653: 
1.506     raeburn  5654: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5655: 
                   5656: sub auto_run {
1.508     raeburn  5657:     my ($cnum,$cdom) = @_;
1.876     raeburn  5658:     my $response = 0;
                   5659:     my $settings;
                   5660:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5661:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5662:         $settings = $domconfig{'autoenroll'};
                   5663:         if ($settings->{'run'} eq '1') {
                   5664:             $response = 1;
                   5665:         }
                   5666:     } else {
1.934     raeburn  5667:         my $homeserver;
                   5668:         if (&is_course($cdom,$cnum)) {
                   5669:             $homeserver = &homeserver($cnum,$cdom);
                   5670:         } else {
                   5671:             $homeserver = &domain($cdom,'primary');
                   5672:         }
                   5673:         if ($homeserver ne 'no_host') {
                   5674:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5675:         }
1.876     raeburn  5676:     }
1.506     raeburn  5677:     return $response;
                   5678: }
1.776     albertel 5679: 
1.506     raeburn  5680: sub auto_get_sections {
1.508     raeburn  5681:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5682:     my $homeserver;
                   5683:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5684:         $homeserver = &homeserver($cnum,$cdom);
                   5685:     }
                   5686:     if (!defined($homeserver)) { 
                   5687:         if ($cdom =~ /^$match_domain$/) {
                   5688:             $homeserver = &domain($cdom,'primary');
                   5689:         }
                   5690:     }
                   5691:     my @secs;
                   5692:     if (defined($homeserver)) {
                   5693:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5694:         unless ($response eq 'refused') {
                   5695:             @secs = split(/:/,$response);
                   5696:         }
1.506     raeburn  5697:     }
                   5698:     return @secs;
                   5699: }
1.776     albertel 5700: 
1.506     raeburn  5701: sub auto_new_course {
1.508     raeburn  5702:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5703:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5704:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5705:     return $response;
                   5706: }
1.776     albertel 5707: 
1.506     raeburn  5708: sub auto_validate_courseID {
1.508     raeburn  5709:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5710:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5711:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5712:     return $response;
                   5713: }
1.776     albertel 5714: 
1.1007    raeburn  5715: sub auto_validate_instcode {
1.1020    raeburn  5716:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5717:     my ($homeserver,$response);
                   5718:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5719:         $homeserver = &homeserver($cnum,$cdom);
                   5720:     }
                   5721:     if (!defined($homeserver)) {
                   5722:         if ($cdom =~ /^$match_domain$/) {
                   5723:             $homeserver = &domain($cdom,'primary');
                   5724:         }
                   5725:     }
                   5726:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
1.1020    raeburn  5727:                            &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  5728:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   5729:     return ($outcome,$description);
1.1007    raeburn  5730: }
                   5731: 
1.506     raeburn  5732: sub auto_create_password {
1.873     raeburn  5733:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5734:     my ($homeserver,$response);
1.506     raeburn  5735:     my $create_passwd = 0;
                   5736:     my $authchk = '';
1.873     raeburn  5737:     if ($udom =~ /^$match_domain$/) {
                   5738:         $homeserver = &domain($udom,'primary');
                   5739:     }
                   5740:     if ($homeserver eq '') {
                   5741:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5742:             $homeserver = &homeserver($cnum,$cdom);
                   5743:         }
                   5744:     }
                   5745:     if ($homeserver eq '') {
                   5746:         $authchk = 'nodomain';
1.506     raeburn  5747:     } else {
1.873     raeburn  5748:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5749:         if ($response eq 'refused') {
                   5750:             $authchk = 'refused';
                   5751:         } else {
1.901     albertel 5752:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5753:         }
1.506     raeburn  5754:     }
                   5755:     return ($authparam,$create_passwd,$authchk);
                   5756: }
                   5757: 
1.706     raeburn  5758: sub auto_photo_permission {
                   5759:     my ($cnum,$cdom,$students) = @_;
                   5760:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5761:     my ($outcome,$perm_reqd,$conditions) = 
                   5762: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5763:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5764: 	return (undef,undef);
                   5765:     }
1.706     raeburn  5766:     return ($outcome,$perm_reqd,$conditions);
                   5767: }
                   5768: 
                   5769: sub auto_checkphotos {
                   5770:     my ($uname,$udom,$pid) = @_;
                   5771:     my $homeserver = &homeserver($uname,$udom);
                   5772:     my ($result,$resulttype);
                   5773:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5774: 				   &escape($uname).':'.&escape($pid),
                   5775: 				   $homeserver));
1.709     albertel 5776:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5777: 	return (undef,undef);
                   5778:     }
1.706     raeburn  5779:     if ($outcome) {
                   5780:         ($result,$resulttype) = split(/:/,$outcome);
                   5781:     } 
                   5782:     return ($result,$resulttype);
                   5783: }
                   5784: 
                   5785: sub auto_photochoice {
                   5786:     my ($cnum,$cdom) = @_;
                   5787:     my $homeserver = &homeserver($cnum,$cdom);
                   5788:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5789: 						       &escape($cdom),
                   5790: 						       $homeserver)));
1.709     albertel 5791:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5792: 	return (undef,undef);
                   5793:     }
1.706     raeburn  5794:     return ($update,$comment);
                   5795: }
                   5796: 
                   5797: sub auto_photoupdate {
                   5798:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5799:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5800:     my $host=&hostname($homeserver);
1.706     raeburn  5801:     my $cmd = '';
                   5802:     my $maxtries = 1;
1.800     albertel 5803:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5804:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5805:     }
                   5806:     $cmd =~ s/%%$//;
                   5807:     $cmd = &escape($cmd);
                   5808:     my $query = 'institutionalphotos';
                   5809:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5810:     unless ($queryid=~/^\Q$host\E\_/) {
                   5811:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5812:         return 'error: '.$queryid;
                   5813:     }
                   5814:     my $reply = &get_query_reply($queryid);
                   5815:     my $tries = 1;
                   5816:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5817:         $reply = &get_query_reply($queryid);
                   5818:         $tries ++;
                   5819:     }
                   5820:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5821:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5822:     } else {
                   5823:         my @responses = split(/:/,$reply);
                   5824:         my $outcome = shift(@responses); 
                   5825:         foreach my $item (@responses) {
                   5826:             my ($key,$value) = split(/=/,$item);
                   5827:             $$photo{$key} = $value;
                   5828:         }
                   5829:         return $outcome;
                   5830:     }
                   5831:     return 'error';
                   5832: }
                   5833: 
1.521     raeburn  5834: sub auto_instcode_format {
1.793     albertel 5835:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5836: 	$cat_order) = @_;
1.521     raeburn  5837:     my $courses = '';
1.772     raeburn  5838:     my @homeservers;
1.521     raeburn  5839:     if ($caller eq 'global') {
1.841     albertel 5840: 	my %servers = &get_servers($codedom,'library');
                   5841: 	foreach my $tryserver (keys(%servers)) {
                   5842: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5843: 		push(@homeservers,$tryserver);
                   5844: 	    }
1.584     raeburn  5845:         }
1.1022    raeburn  5846:     } elsif ($caller eq 'requests') {
                   5847:         if ($codedom =~ /^$match_domain$/) {
                   5848:             my $chome = &domain($codedom,'primary');
                   5849:             unless ($chome eq 'no_host') {
                   5850:                 push(@homeservers,$chome);
                   5851:             }
                   5852:         }
1.521     raeburn  5853:     } else {
1.772     raeburn  5854:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5855:     }
1.793     albertel 5856:     foreach my $code (keys(%{$instcodes})) {
                   5857:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5858:     }
                   5859:     chop($courses);
1.772     raeburn  5860:     my $ok_response = 0;
                   5861:     my $response;
                   5862:     while (@homeservers > 0 && $ok_response == 0) {
                   5863:         my $server = shift(@homeservers); 
                   5864:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5865:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5866:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5867: 		split(/:/,$response);
1.772     raeburn  5868:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5869:             push(@{$codetitles},&str2array($codetitles_str));
                   5870:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5871:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5872:             $ok_response = 1;
                   5873:         }
                   5874:     }
                   5875:     if ($ok_response) {
1.521     raeburn  5876:         return 'ok';
1.772     raeburn  5877:     } else {
                   5878:         return $response;
1.521     raeburn  5879:     }
                   5880: }
                   5881: 
1.792     raeburn  5882: sub auto_instcode_defaults {
                   5883:     my ($domain,$returnhash,$code_order) = @_;
                   5884:     my @homeservers;
1.841     albertel 5885: 
                   5886:     my %servers = &get_servers($domain,'library');
                   5887:     foreach my $tryserver (keys(%servers)) {
                   5888: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5889: 	    push(@homeservers,$tryserver);
                   5890: 	}
1.792     raeburn  5891:     }
1.841     albertel 5892: 
1.792     raeburn  5893:     my $response;
1.841     albertel 5894:     foreach my $server (@homeservers) {
1.792     raeburn  5895:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5896:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5897: 	
                   5898: 	foreach my $pair (split(/\&/,$response)) {
                   5899: 	    my ($name,$value)=split(/\=/,$pair);
                   5900: 	    if ($name eq 'code_order') {
                   5901: 		@{$code_order} = split(/\&/,&unescape($value));
                   5902: 	    } else {
                   5903: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5904: 	    }
                   5905: 	}
                   5906: 	return 'ok';
1.792     raeburn  5907:     }
1.841     albertel 5908: 
                   5909:     return $response;
1.1003    raeburn  5910: }
                   5911: 
                   5912: sub auto_possible_instcodes {
1.1007    raeburn  5913:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   5914:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   5915:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   5916:         return;
                   5917:     }
1.1003    raeburn  5918:     my (@homeservers,$uhome);
                   5919:     if (defined(&domain($domain,'primary'))) {
                   5920:         $uhome=&domain($domain,'primary');
                   5921:         push(@homeservers,&domain($domain,'primary'));
                   5922:     } else {
                   5923:         my %servers = &get_servers($domain,'library');
                   5924:         foreach my $tryserver (keys(%servers)) {
                   5925:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5926:                 push(@homeservers,$tryserver);
                   5927:             }
                   5928:         }
                   5929:     }
                   5930:     my $response;
                   5931:     foreach my $server (@homeservers) {
                   5932:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   5933:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  5934:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   5935:             split(':',$response);
                   5936:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   5937:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  5938:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  5939:             my ($name,$value)=split('=',$item);
                   5940:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5941:         }
                   5942:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  5943:             my ($name,$value)=split('=',$item);
                   5944:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  5945:         }
                   5946:         return 'ok';
                   5947:     }
                   5948:     return $response;
                   5949: }
1.792     raeburn  5950: 
1.1010    raeburn  5951: sub auto_courserequest_checks {
                   5952:     my ($dom) = @_;
1.1020    raeburn  5953:     my ($homeserver,%validations);
                   5954:     if ($dom =~ /^$match_domain$/) {
                   5955:         $homeserver = &domain($dom,'primary');
                   5956:     }
                   5957:     unless ($homeserver eq 'no_host') {
                   5958:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   5959:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   5960:             my @items = split(/&/,$response);
                   5961:             foreach my $item (@items) {
                   5962:                 my ($key,$value) = split('=',$item);
                   5963:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   5964:             }
                   5965:         }
                   5966:     }
1.1010    raeburn  5967:     return %validations; 
                   5968: }
                   5969: 
1.1020    raeburn  5970: sub auto_courserequest_validation {
                   5971:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   5972:     my ($homeserver,$response);
                   5973:     if ($dom =~ /^$match_domain$/) {
                   5974:         $homeserver = &domain($dom,'primary');
                   5975:     }
                   5976:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  5977:           
1.1020    raeburn  5978:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  5979:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  5980:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   5981:                                     $homeserver));
                   5982:     }
                   5983:     return $response;
                   5984: }
                   5985: 
1.777     albertel 5986: sub auto_validate_class_sec {
1.918     raeburn  5987:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5988:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5989:     my $ownerlist;
                   5990:     if (ref($owners) eq 'ARRAY') {
                   5991:         $ownerlist = join(',',@{$owners});
                   5992:     } else {
                   5993:         $ownerlist = $owners;
                   5994:     }
1.773     raeburn  5995:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5996:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5997:     return $response;
                   5998: }
                   5999: 
1.679     raeburn  6000: # ------------------------------------------------------- Course Group routines
                   6001: 
                   6002: sub get_coursegroups {
1.809     raeburn  6003:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6004:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6005: }
                   6006: 
1.679     raeburn  6007: sub modify_coursegroup {
                   6008:     my ($cdom,$cnum,$groupsettings) = @_;
                   6009:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6010: }
                   6011: 
1.809     raeburn  6012: sub toggle_coursegroup_status {
                   6013:     my ($cdom,$cnum,$group,$action) = @_;
                   6014:     my ($from_namespace,$to_namespace);
                   6015:     if ($action eq 'delete') {
                   6016:         $from_namespace = 'coursegroups';
                   6017:         $to_namespace = 'deleted_groups';
                   6018:     } else {
                   6019:         $from_namespace = 'deleted_groups';
                   6020:         $to_namespace = 'coursegroups';
                   6021:     }
                   6022:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6023:     if (my $tmp = &error(%curr_group)) {
                   6024:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6025:         return ('read error',$tmp);
                   6026:     } else {
                   6027:         my %savedsettings = %curr_group; 
1.809     raeburn  6028:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6029:         my $deloutcome;
                   6030:         if ($result eq 'ok') {
1.809     raeburn  6031:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6032:         } else {
                   6033:             return ('write error',$result);
                   6034:         }
                   6035:         if ($deloutcome eq 'ok') {
                   6036:             return 'ok';
                   6037:         } else {
                   6038:             return ('delete error',$deloutcome);
                   6039:         }
                   6040:     }
                   6041: }
                   6042: 
1.679     raeburn  6043: sub modify_group_roles {
1.957     raeburn  6044:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6045:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6046:     my $role = 'gr/'.&escape($userprivs);
                   6047:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6048:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6049:     if ($result eq 'ok') {
                   6050:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6051:     }
1.679     raeburn  6052:     return $result;
                   6053: }
                   6054: 
                   6055: sub modify_coursegroup_membership {
                   6056:     my ($cdom,$cnum,$membership) = @_;
                   6057:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6058:     return $result;
                   6059: }
                   6060: 
1.682     raeburn  6061: sub get_active_groups {
                   6062:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6063:     my $now = time;
                   6064:     my %groups = ();
                   6065:     foreach my $key (keys(%env)) {
1.811     albertel 6066:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6067:             my ($start,$end) = split(/\./,$env{$key});
                   6068:             if (($end!=0) && ($end<$now)) { next; }
                   6069:             if (($start!=0) && ($start>$now)) { next; }
                   6070:             if ($1 eq $cdom && $2 eq $cnum) {
                   6071:                 $groups{$3} = $env{$key} ;
                   6072:             }
                   6073:         }
                   6074:     }
                   6075:     return %groups;
                   6076: }
                   6077: 
1.683     raeburn  6078: sub get_group_membership {
                   6079:     my ($cdom,$cnum,$group) = @_;
                   6080:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6081: }
                   6082: 
                   6083: sub get_users_groups {
                   6084:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6085:     my @usersgroups;
1.683     raeburn  6086:     my $cachetime=1800;
                   6087: 
                   6088:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6089:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6090:     if (defined($cached)) {
1.734     albertel 6091:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6092:     } else {  
                   6093:         $grouplist = '';
1.816     raeburn  6094:         my $courseurl = &courseid_to_courseurl($courseid);
                   6095:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6096:         my $access_end = $env{'course.'.$courseid.
                   6097:                               '.default_enrollment_end_date'};
                   6098:         my $now = time;
                   6099:         foreach my $key (keys(%roleshash)) {
                   6100:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6101:                 my $group = $1;
                   6102:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6103:                     my $start = $2;
                   6104:                     my $end = $1;
                   6105:                     if ($start == -1) { next; } # deleted from group
                   6106:                     if (($start!=0) && ($start>$now)) { next; }
                   6107:                     if (($end!=0) && ($end<$now)) {
                   6108:                         if ($access_end && $access_end < $now) {
                   6109:                             if ($access_end - $end < 86400) {
                   6110:                                 push(@usersgroups,$group);
1.733     raeburn  6111:                             }
                   6112:                         }
1.817     raeburn  6113:                         next;
1.733     raeburn  6114:                     }
1.817     raeburn  6115:                     push(@usersgroups,$group);
1.683     raeburn  6116:                 }
                   6117:             }
                   6118:         }
1.817     raeburn  6119:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6120:         $grouplist = join(':',@usersgroups);
                   6121:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6122:     }
1.733     raeburn  6123:     return @usersgroups;
1.683     raeburn  6124: }
                   6125: 
                   6126: sub devalidate_getgroups_cache {
                   6127:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6128:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6129: 
1.683     raeburn  6130:     my $hashid="$udom:$uname:$courseid";
                   6131:     &devalidate_cache_new('getgroups',$hashid);
                   6132: }
                   6133: 
1.12      www      6134: # ------------------------------------------------------------------ Plain Text
                   6135: 
                   6136: sub plaintext {
1.988     raeburn  6137:     my ($short,$type,$cid,$forcedefault) = @_;
1.758     albertel 6138:     if ($short =~ /^cr/) {
                   6139: 	return (split('/',$short))[-1];
                   6140:     }
1.742     raeburn  6141:     if (!defined($cid)) {
                   6142:         $cid = $env{'request.course.id'};
                   6143:     }
                   6144:     my %rolenames = (
1.1008    raeburn  6145:                       Course    => 'std',
                   6146:                       Community => 'alt1',
1.742     raeburn  6147:                     );
1.1037    raeburn  6148:     if ($cid ne '') {
                   6149:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6150:             unless ($forcedefault) {
                   6151:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6152:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6153:                 return &Apache::lonlocal::mt($roletext);
                   6154:             }
                   6155:         }
                   6156:     }
                   6157:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6158:         (defined($rolenames{$type})) && 
                   6159:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6160:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6161:     } elsif ($cid ne '') {
                   6162:         my $crstype = $env{'course.'.$cid.'.type'};
                   6163:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6164:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6165:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6166:         }
1.742     raeburn  6167:     }
1.1037    raeburn  6168:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6169: }
                   6170: 
                   6171: # ----------------------------------------------------------------- Assign Role
                   6172: 
                   6173: sub assignrole {
1.957     raeburn  6174:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6175:         $context)=@_;
1.21      www      6176:     my $mrole;
                   6177:     if ($role =~ /^cr\//) {
1.393     www      6178:         my $cwosec=$url;
1.811     albertel 6179:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6180: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6181:            my $refused = 1;
                   6182:            if ($context eq 'requestcourses') {
                   6183:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6184:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6185:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6186:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6187:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6188:                            if ($crsenv{'internal.courseowner'} eq
                   6189:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6190:                                $refused = '';
                   6191:                            }
                   6192:                        }
                   6193:                    }
                   6194:                }
                   6195:            }
                   6196:            if ($refused) {
                   6197:                &logthis('Refused custom assignrole: '.
                   6198:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6199:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6200:                return 'refused';
                   6201:            }
1.104     www      6202:         }
1.21      www      6203:         $mrole='cr';
1.678     raeburn  6204:     } elsif ($role =~ /^gr\//) {
                   6205:         my $cwogrp=$url;
1.811     albertel 6206:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6207:         unless (&allowed('mdg',$cwogrp)) {
                   6208:             &logthis('Refused group assignrole: '.
                   6209:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6210:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6211:             return 'refused';
                   6212:         }
                   6213:         $mrole='gr';
1.21      www      6214:     } else {
1.82      www      6215:         my $cwosec=$url;
1.811     albertel 6216:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6217:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6218:             my $refused;
                   6219:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6220:                 if (!(&allowed('c'.$role,$url))) {
                   6221:                     $refused = 1;
                   6222:                 }
                   6223:             } else {
                   6224:                 $refused = 1;
                   6225:             }
1.947     raeburn  6226:             if ($refused) {
                   6227:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6228:                     $refused = '';
1.1017    raeburn  6229:                 } elsif ($context eq 'requestcourses') {
1.1041  ! raeburn  6230:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6231:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
                   6232:                         my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1041  ! raeburn  6233:                         my $wrongcc;
        !          6234:                         if ($cnum =~ /^$match_community$/) {
        !          6235:                             $wrongcc = 1 if ($role eq 'cc');
        !          6236:                         } else {
        !          6237:                             $wrongcc = 1 if ($role eq 'co');
        !          6238:                         }
        !          6239:                         unless ($wrongcc) {
        !          6240:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
        !          6241:                             if ($crsenv{'internal.courseowner'} eq 
        !          6242:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
        !          6243:                                 $refused = '';
        !          6244:                             }
1.1017    raeburn  6245:                         }
                   6246:                     }
                   6247:                 }
                   6248:                 if ($refused) {
1.947     raeburn  6249:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6250:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6251: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6252:                     return 'refused';
                   6253:                 }
1.932     raeburn  6254:             }
1.104     www      6255:         }
1.21      www      6256:         $mrole=$role;
                   6257:     }
1.620     albertel 6258:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6259:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6260:     if ($end) { $command.='_'.$end; }
1.21      www      6261:     if ($start) {
                   6262: 	if ($end) { 
1.81      www      6263:            $command.='_'.$start; 
1.21      www      6264:         } else {
1.81      www      6265:            $command.='_0_'.$start;
1.21      www      6266:         }
                   6267:     }
1.739     raeburn  6268:     my $origstart = $start;
                   6269:     my $origend = $end;
1.957     raeburn  6270:     my $delflag;
1.357     www      6271: # actually delete
                   6272:     if ($deleteflag) {
1.373     www      6273: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6274: # modify command to delete the role
1.620     albertel 6275:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6276:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6277: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6278: # set start and finish to negative values for userrolelog
                   6279:            $start=-1;
                   6280:            $end=-1;
1.957     raeburn  6281:            $delflag = 1;
1.357     www      6282:         }
                   6283:     }
                   6284: # send command
1.349     www      6285:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6286: # log new user role if status is ok
1.349     www      6287:     if ($answer eq 'ok') {
1.663     raeburn  6288: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6289: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6290:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6291:         unless ($role =~ /^gr/) {
                   6292:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6293:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6294:         }
1.349     www      6295:     }
                   6296:     return $answer;
1.169     harris41 6297: }
                   6298: 
                   6299: # -------------------------------------------------- Modify user authentication
1.197     www      6300: # Overrides without validation
                   6301: 
1.169     harris41 6302: sub modifyuserauth {
                   6303:     my ($udom,$uname,$umode,$upass)=@_;
                   6304:     my $uhome=&homeserver($uname,$udom);
1.197     www      6305:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6306:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6307:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6308:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6309:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6310: 		     &escape($upass),$uhome);
1.620     albertel 6311:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6312:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6313:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6314:     &log($udom,,$uname,$uhome,
1.620     albertel 6315:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6316:                                      $env{'user.name'}.', '.$umode.
1.197     www      6317:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6318:     unless ($reply eq 'ok') {
1.197     www      6319:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6320: 	return 'error: '.$reply;
                   6321:     }   
1.170     harris41 6322:     return 'ok';
1.80      www      6323: }
                   6324: 
1.81      www      6325: # --------------------------------------------------------------- Modify a user
1.80      www      6326: 
1.81      www      6327: sub modifyuser {
1.206     matthew  6328:     my ($udom,    $uname, $uid,
                   6329:         $umode,   $upass, $first,
                   6330:         $middle,  $last,  $gene,
1.963     raeburn  6331:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 6332:     $udom= &LONCAPA::clean_domain($udom);
                   6333:     $uname=&LONCAPA::clean_username($uname);
1.81      www      6334:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6335:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  6336: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   6337:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6338:                                      ' desiredhome not specified'). 
1.620     albertel 6339:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6340:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6341:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      6342: # ----------------------------------------------------------------- Create User
1.406     albertel 6343:     if (($uhome eq 'no_host') && 
                   6344: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6345:         my $unhome='';
1.844     albertel 6346:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6347:             $unhome = $desiredhome;
1.620     albertel 6348: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6349: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6350:         } else { # load balancing routine for determining $unhome
1.81      www      6351:             my $loadm=10000000;
1.841     albertel 6352: 	    my %servers = &get_servers($udom,'library');
                   6353: 	    foreach my $tryserver (keys(%servers)) {
                   6354: 		my $answer=reply('load',$tryserver);
                   6355: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6356: 		    $loadm=$answer;
                   6357: 		    $unhome=$tryserver;
                   6358: 		}
1.80      www      6359: 	    }
                   6360:         }
                   6361:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6362: 	    return 'error: unable to find a home server for '.$uname.
                   6363:                    ' in domain '.$udom;
1.80      www      6364:         }
                   6365:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6366:                          &escape($upass),$unhome);
                   6367: 	unless ($reply eq 'ok') {
                   6368:             return 'error: '.$reply;
                   6369:         }   
1.230     stredwic 6370:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6371:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6372: 	    return 'error: unable verify users home machine.';
1.80      www      6373:         }
1.209     matthew  6374:     }   # End of creation of new user
1.80      www      6375: # ---------------------------------------------------------------------- Add ID
                   6376:     if ($uid) {
                   6377:        $uid=~tr/A-Z/a-z/;
                   6378:        my %uidhash=&idrget($udom,$uname);
1.196     www      6379:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6380:          && (!$forceid)) {
1.80      www      6381: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6382: 	      return 'error: user id "'.$uid.'" does not match '.
                   6383:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6384:           }
                   6385:        } else {
                   6386: 	  &idput($udom,($uname => $uid));
                   6387:        }
                   6388:     }
                   6389: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6390:     my @tmp=&get('environment',
1.899     raeburn  6391: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6392:                     'permanentemail','inststatus'],
1.134     albertel 6393: 		   $udom,$uname);
1.313     matthew  6394:     my %names;
                   6395:     if ($tmp[0] =~ m/^error:.*/) { 
                   6396:         %names=(); 
                   6397:     } else {
                   6398:         %names = @tmp;
                   6399:     }
1.388     www      6400: #
                   6401: # Make sure to not trash student environment if instructor does not bother
                   6402: # to supply name and email information
                   6403: #
                   6404:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6405:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6406:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6407:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6408:     if ($email) {
                   6409:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6410:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6411:     }
1.899     raeburn  6412:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6413:     if (defined($inststatus)) {
                   6414:         $names{'inststatus'} = '';
                   6415:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6416:         if (ref($usertypes) eq 'HASH') {
                   6417:             my @okstatuses; 
                   6418:             foreach my $item (split(/:/,$inststatus)) {
                   6419:                 if (defined($usertypes->{$item})) {
                   6420:                     push(@okstatuses,$item);  
                   6421:                 }
                   6422:             }
                   6423:             if (@okstatuses) {
                   6424:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6425:             }
                   6426:         }
                   6427:     }
1.134     albertel 6428:     my $reply = &put('environment', \%names, $udom,$uname);
                   6429:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6430:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6431:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  6432:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   6433:                  $umode.', '.$first.', '.$middle.', '.
                   6434: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   6435:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6436:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6437:     } else {
                   6438:         $logmsg .= ' during self creation';
                   6439:     }
                   6440:     &logthis($logmsg);
1.134     albertel 6441:     return 'ok';
1.80      www      6442: }
                   6443: 
1.81      www      6444: # -------------------------------------------------------------- Modify student
1.80      www      6445: 
1.81      www      6446: sub modifystudent {
                   6447:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6448:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6449:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6450:     if (!$cid) {
1.620     albertel 6451: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6452: 	    return 'not_in_class';
                   6453: 	}
1.80      www      6454:     }
                   6455: # --------------------------------------------------------------- Make the user
1.81      www      6456:     my $reply=&modifyuser
1.209     matthew  6457: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6458:          $desiredhome,$email,$inststatus);
1.80      www      6459:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6460:     # This will cause &modify_student_enrollment to get the uid from the
                   6461:     # students environment
                   6462:     $uid = undef if (!$forceid);
1.455     albertel 6463:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6464: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6465:     return $reply;
                   6466: }
                   6467: 
                   6468: sub modify_student_enrollment {
1.957     raeburn  6469:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6470:     my ($cdom,$cnum,$chome);
                   6471:     if (!$cid) {
1.620     albertel 6472: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6473: 	    return 'not_in_class';
                   6474: 	}
1.620     albertel 6475: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6476: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6477:     } else {
                   6478: 	($cdom,$cnum)=split(/_/,$cid);
                   6479:     }
1.620     albertel 6480:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6481:     if (!$chome) {
1.457     raeburn  6482: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6483:     }
1.455     albertel 6484:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6485:     # Make sure the user exists
1.81      www      6486:     my $uhome=&homeserver($uname,$udom);
                   6487:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6488: 	return 'error: no such user';
                   6489:     }
1.297     matthew  6490:     # Get student data if we were not given enough information
                   6491:     if (!defined($first)  || $first  eq '' || 
                   6492:         !defined($last)   || $last   eq '' || 
                   6493:         !defined($uid)    || $uid    eq '' || 
                   6494:         !defined($middle) || $middle eq '' || 
                   6495:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6496:         # They did not supply us with enough data to enroll the student, so
                   6497:         # we need to pick up more information.
1.297     matthew  6498:         my %tmp = &get('environment',
1.294     matthew  6499:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6500:                        ,$udom,$uname);
                   6501: 
1.800     albertel 6502:         #foreach my $key (keys(%tmp)) {
                   6503:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6504:         #}
1.294     matthew  6505:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6506:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6507:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6508:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6509:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6510:     }
1.556     albertel 6511:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6512:     my $reply=cput('classlist',
                   6513: 		   {"$uname:$udom" => 
1.515     raeburn  6514: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6515: 		   $cdom,$cnum);
1.81      www      6516:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6517: 	return 'error: '.$reply;
1.652     albertel 6518:     } else {
                   6519: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6520:     }
1.297     matthew  6521:     # Add student role to user
1.83      www      6522:     my $uurl='/'.$cid;
1.81      www      6523:     $uurl=~s/\_/\//g;
                   6524:     if ($usec) {
                   6525: 	$uurl.='/'.$usec;
                   6526:     }
1.957     raeburn  6527:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6528: }
                   6529: 
1.556     albertel 6530: sub format_name {
                   6531:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6532:     my $name;
                   6533:     if ($first ne 'lastname') {
                   6534: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6535:     } else {
                   6536: 	if ($lastname=~/\S/) {
                   6537: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6538: 	    $name=~s/\s+,/,/;
                   6539: 	} else {
                   6540: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6541: 	}
                   6542:     }
                   6543:     $name=~s/^\s+//;
                   6544:     $name=~s/\s+$//;
                   6545:     $name=~s/\s+/ /g;
                   6546:     return $name;
                   6547: }
                   6548: 
1.84      www      6549: # ------------------------------------------------- Write to course preferences
                   6550: 
                   6551: sub writecoursepref {
                   6552:     my ($courseid,%prefs)=@_;
                   6553:     $courseid=~s/^\///;
                   6554:     $courseid=~s/\_/\//g;
                   6555:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6556:     my $chome=homeserver($cnum,$cdomain);
                   6557:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6558: 	return 'error: no such course';
                   6559:     }
                   6560:     my $cstring='';
1.800     albertel 6561:     foreach my $pref (keys(%prefs)) {
                   6562: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6563:     }
1.84      www      6564:     $cstring=~s/\&$//;
                   6565:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6566: }
                   6567: 
                   6568: # ---------------------------------------------------------- Make/modify course
                   6569: 
                   6570: sub createcourse {
1.741     raeburn  6571:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  6572:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      6573:     $url=&declutter($url);
                   6574:     my $cid='';
1.1028    raeburn  6575:     if ($context eq 'requestcourses') {
                   6576:         my $can_create = 0;
                   6577:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   6578:         if ($udom eq $ownerdom) {
                   6579:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   6580:                                   $context)) {
                   6581:                 $can_create = 1;
                   6582:             }
                   6583:         } else {
                   6584:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   6585:                                            $category);
                   6586:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   6587:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   6588:                 if (@curr > 0) {
                   6589:                     my @options = qw(approval validate autolimit);
                   6590:                     my $optregex = join('|',@options);
                   6591:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   6592:                         $can_create = 1;
                   6593:                     }
                   6594:                 }
                   6595:             }
                   6596:         }
                   6597:         if ($can_create) {
                   6598:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   6599:                 unless (&allowed('ccc',$udom)) {
                   6600:                     return 'refused'; 
                   6601:                 }
1.1017    raeburn  6602:             }
                   6603:         } else {
                   6604:             return 'refused';
                   6605:         }
1.1028    raeburn  6606:     } elsif (!&allowed('ccc',$udom)) {
                   6607:         return 'refused';
1.84      www      6608:     }
1.1011    raeburn  6609: # --------------------------------------------------------------- Get Unique ID
                   6610:     my $uname;
                   6611:     if ($cnum =~ /^$match_courseid$/) {
                   6612:         my $chome=&homeserver($cnum,$udom,'true');
                   6613:         if (($chome eq '') || ($chome eq 'no_host')) {
                   6614:             $uname = $cnum;
                   6615:         } else {
1.1038    raeburn  6616:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6617:         }
                   6618:     } else {
1.1038    raeburn  6619:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6620:     }
                   6621:     return $uname if ($uname =~ /^error/);
                   6622: # -------------------------------------------------- Check supplied server name
1.620     albertel 6623:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6624:     if (! &is_library($course_server)) {
1.264     matthew  6625:         return 'error:bad server name '.$course_server;
                   6626:     }
1.84      www      6627: # ------------------------------------------------------------- Make the course
                   6628:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6629:                       $course_server);
1.84      www      6630:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  6631:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6632:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6633: 	return 'error: no such course';
                   6634:     }
1.271     www      6635: # ----------------------------------------------------------------- Course made
1.516     raeburn  6636: # log existence
1.1029    raeburn  6637:     my $now = time;
1.918     raeburn  6638:     my $newcourse = {
                   6639:                     $udom.'_'.$uname => {
1.921     raeburn  6640:                                      description => $description,
                   6641:                                      inst_code   => $inst_code,
                   6642:                                      owner       => $course_owner,
                   6643:                                      type        => $crstype,
1.1029    raeburn  6644:                                      creator     => $env{'user.name'}.':'.
                   6645:                                                     $env{'user.domain'},
                   6646:                                      created     => $now,
                   6647:                                      context     => $context,
1.918     raeburn  6648:                                                 },
                   6649:                     };
1.921     raeburn  6650:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6651: # set toplevel url
1.271     www      6652:     my $topurl=$url;
                   6653:     unless ($nonstandard) {
                   6654: # ------------------------------------------ For standard courses, make top url
                   6655:         my $mapurl=&clutter($url);
1.278     www      6656:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6657:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6658: <map>
                   6659: <resource id="1" type="start"></resource>
                   6660: <resource id="2" src="$mapurl"></resource>
                   6661: <resource id="3" type="finish"></resource>
                   6662: <link index="1" from="1" to="2"></link>
                   6663: <link index="2" from="2" to="3"></link>
                   6664: </map>
                   6665: ENDINITMAP
                   6666:         $topurl=&declutter(
1.638     albertel 6667:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6668:                           );
                   6669:     }
                   6670: # ----------------------------------------------------------- Write preferences
1.84      www      6671:     &writecoursepref($udom.'_'.$uname,
                   6672:                      ('description' => $description,
1.271     www      6673:                       'url'         => $topurl));
1.84      www      6674:     return '/'.$udom.'/'.$uname;
                   6675: }
                   6676: 
1.1011    raeburn  6677: # ------------------------------------------------------------------- Create ID
                   6678: sub generate_coursenum {
1.1038    raeburn  6679:     my ($udom,$crstype) = @_;
1.1011    raeburn  6680:     my $domdesc = &domain($udom);
                   6681:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  6682:     my $first;
                   6683:     if ($crstype eq 'Community') {
                   6684:         $first = '0';
                   6685:     } else {
                   6686:         $first = int(1+rand(9)); 
                   6687:     } 
                   6688:     my $uname=$first.
1.1011    raeburn  6689:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6690:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6691:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6692: # ----------------------------------------------- Make sure that does not exist
                   6693:     my $uhome=&homeserver($uname,$udom,'true');
                   6694:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  6695:         if ($crstype eq 'Community') {
                   6696:             $first = '0';
                   6697:         } else {
                   6698:             $first = int(1+rand(9));
                   6699:         }
                   6700:         $uname=$first.
1.1011    raeburn  6701:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6702:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6703:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6704:         $uhome=&homeserver($uname,$udom,'true');
                   6705:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6706:             return 'error: unable to generate unique course-ID';
                   6707:         }
                   6708:     }
                   6709:     return $uname;
                   6710: }
                   6711: 
1.813     albertel 6712: sub is_course {
                   6713:     my ($cdom,$cnum) = @_;
                   6714:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6715: 				undef,'.');
1.813     albertel 6716:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6717:         return 1;
                   6718:     }
                   6719:     return 0;
                   6720: }
                   6721: 
1.1015    raeburn  6722: sub store_userdata {
                   6723:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  6724:     my $result;
1.1016    raeburn  6725:     if ($datakey ne '') {
1.1013    raeburn  6726:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  6727:             if ($udom eq '' || $uname eq '') {
                   6728:                 $udom = $env{'user.domain'};
                   6729:                 $uname = $env{'user.name'};
                   6730:             }
                   6731:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  6732:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   6733:                 $result = 'error: no_host';
                   6734:             } else {
                   6735:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   6736:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   6737: 
                   6738:                 my $namevalue='';
                   6739:                 foreach my $key (keys(%{$storehash})) {
                   6740:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6741:                 }
                   6742:                 $namevalue=~s/\&$//;
                   6743:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  6744:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  6745:             }
                   6746:         } else {
                   6747:             $result = 'error: data to store was not a hash reference'; 
                   6748:         }
                   6749:     } else {
                   6750:         $result= 'error: invalid requestkey'; 
                   6751:     }
                   6752:     return $result;
                   6753: }
                   6754: 
1.21      www      6755: # ---------------------------------------------------------- Assign Custom Role
                   6756: 
                   6757: sub assigncustomrole {
1.957     raeburn  6758:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6759:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6760:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6761: }
                   6762: 
                   6763: # ----------------------------------------------------------------- Revoke Role
                   6764: 
                   6765: sub revokerole {
1.957     raeburn  6766:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6767:     my $now=time;
1.965     raeburn  6768:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6769: }
                   6770: 
                   6771: # ---------------------------------------------------------- Revoke Custom Role
                   6772: 
                   6773: sub revokecustomrole {
1.957     raeburn  6774:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6775:     my $now=time;
1.357     www      6776:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6777:            $deleteflag,$selfenroll,$context);
1.17      www      6778: }
                   6779: 
1.533     banghart 6780: # ------------------------------------------------------------ Disk usage
1.535     albertel 6781: sub diskusage {
1.955     raeburn  6782:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6783:     $directorypath =~ s/\/$//;
                   6784:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6785:                        .&escape($getpropath).':'.&escape($uname).':'
                   6786:                        .&escape($udom),homeserver($uname,$udom));
                   6787:     if ($listing eq 'unknown_cmd') {
                   6788:         if ($getpropath) {
                   6789:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6790:         }
                   6791:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6792:     }
1.514     albertel 6793:     return $listing;
1.512     banghart 6794: }
                   6795: 
1.566     banghart 6796: sub is_locked {
                   6797:     my ($file_name, $domain, $user) = @_;
                   6798:     my @check;
                   6799:     my $is_locked;
                   6800:     push @check, $file_name;
1.613     albertel 6801:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6802: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6803:     my ($tmp)=keys(%locked);
                   6804:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6805:     
1.566     banghart 6806:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6807:         $is_locked = 'false';
                   6808:         foreach my $entry (@{$locked{$file_name}}) {
                   6809:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6810:                $is_locked = 'true';
                   6811:                last;
1.745     raeburn  6812:            }
                   6813:        }
1.566     banghart 6814:     } else {
                   6815:         $is_locked = 'false';
                   6816:     }
                   6817: }
                   6818: 
1.759     albertel 6819: sub declutter_portfile {
                   6820:     my ($file) = @_;
1.833     albertel 6821:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6822:     return $file;
                   6823: }
                   6824: 
1.559     banghart 6825: # ------------------------------------------------------------- Mark as Read Only
                   6826: 
                   6827: sub mark_as_readonly {
                   6828:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6829:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6830:     my ($tmp)=keys(%current_permissions);
                   6831:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6832:     foreach my $file (@{$files}) {
1.759     albertel 6833: 	$file = &declutter_portfile($file);
1.561     banghart 6834:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6835:     }
1.613     albertel 6836:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6837:     return;
                   6838: }
                   6839: 
1.572     banghart 6840: # ------------------------------------------------------------Save Selected Files
                   6841: 
                   6842: sub save_selected_files {
                   6843:     my ($user, $path, @files) = @_;
                   6844:     my $filename = $user."savedfiles";
1.573     banghart 6845:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6846:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6847:     foreach my $file (@files) {
1.620     albertel 6848:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6849:     }
                   6850:     foreach my $file (@other_files) {
1.574     banghart 6851:         print (OUT $file."\n");
1.572     banghart 6852:     }
1.574     banghart 6853:     close (OUT);
1.572     banghart 6854:     return 'ok';
                   6855: }
                   6856: 
1.574     banghart 6857: sub clear_selected_files {
                   6858:     my ($user) = @_;
                   6859:     my $filename = $user."savedfiles";
                   6860:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6861:     print (OUT undef);
                   6862:     close (OUT);
                   6863:     return ("ok");    
                   6864: }
                   6865: 
1.572     banghart 6866: sub files_in_path {
                   6867:     my ($user, $path) = @_;
                   6868:     my $filename = $user."savedfiles";
                   6869:     my %return_files;
1.574     banghart 6870:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6871:     while (my $line_in = <IN>) {
1.574     banghart 6872:         chomp ($line_in);
                   6873:         my @paths_and_file = split (m!/!, $line_in);
                   6874:         my $file_part = pop (@paths_and_file);
                   6875:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6876:         $path_part.='/';
                   6877:         my $path_and_file = $path_part.$file_part;
                   6878:         if ($path_part eq $path) {
                   6879:             $return_files{$file_part}= 'selected';
                   6880:         }
                   6881:     }
1.574     banghart 6882:     close (IN);
                   6883:     return (\%return_files);
1.572     banghart 6884: }
                   6885: 
                   6886: # called in portfolio select mode, to show files selected NOT in current directory
                   6887: sub files_not_in_path {
                   6888:     my ($user, $path) = @_;
                   6889:     my $filename = $user."savedfiles";
                   6890:     my @return_files;
                   6891:     my $path_part;
1.800     albertel 6892:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6893:     while (my $line = <IN>) {
1.572     banghart 6894:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6895:         my @paths_and_file = split(m|/|, $line);
                   6896:         my $file_part = pop(@paths_and_file);
                   6897:         chomp($file_part);
                   6898:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6899:         $path_part .= '/';
                   6900:         my $path_and_file = $path_part.$file_part;
                   6901:         if ($path_part ne $path) {
1.800     albertel 6902:             push(@return_files, ($path_and_file));
1.572     banghart 6903:         }
                   6904:     }
1.800     albertel 6905:     close(OUT);
1.574     banghart 6906:     return (@return_files);
1.572     banghart 6907: }
                   6908: 
1.745     raeburn  6909: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6910: 
1.745     raeburn  6911: sub get_portfile_permissions {
                   6912:     my ($domain,$user) = @_;
1.613     albertel 6913:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6914:     my ($tmp)=keys(%current_permissions);
                   6915:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6916:     return \%current_permissions;
                   6917: }
                   6918: 
                   6919: #---------------------------------------------Get portfolio file access controls
                   6920: 
1.749     raeburn  6921: sub get_access_controls {
1.745     raeburn  6922:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6923:     my %access;
                   6924:     my $real_file = $file;
                   6925:     $file =~ s/\.meta$//;
1.745     raeburn  6926:     if (defined($file)) {
1.749     raeburn  6927:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6928:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6929:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6930:             }
                   6931:         }
1.745     raeburn  6932:     } else {
1.749     raeburn  6933:         foreach my $key (keys(%{$current_permissions})) {
                   6934:             if ($key =~ /\0accesscontrol$/) {
                   6935:                 if (defined($group)) {
                   6936:                     if ($key !~ m-^\Q$group\E/-) {
                   6937:                         next;
                   6938:                     }
                   6939:                 }
                   6940:                 my ($fullpath) = split(/\0/,$key);
                   6941:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6942:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6943:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6944:                     }
                   6945:                 }
                   6946:             }
                   6947:         }
                   6948:     }
                   6949:     return %access;
                   6950: }
                   6951: 
                   6952: sub modify_access_controls {
                   6953:     my ($file_name,$changes,$domain,$user)=@_;
                   6954:     my ($outcome,$deloutcome);
                   6955:     my %store_permissions;
                   6956:     my %new_values;
                   6957:     my %new_control;
                   6958:     my %translation;
                   6959:     my @deletions = ();
                   6960:     my $now = time;
                   6961:     if (exists($$changes{'activate'})) {
                   6962:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6963:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6964:             my $numnew = scalar(@newitems);
                   6965:             for (my $i=0; $i<$numnew; $i++) {
                   6966:                 my $newkey = $newitems[$i];
                   6967:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6968:                 if ($newkey =~ /^\d+:/) { 
                   6969:                     $newkey =~ s/^(\d+)/$newid/;
                   6970:                     $translation{$1} = $newid;
                   6971:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6972:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6973:                     $translation{$1} = $newid;
                   6974:                 }
1.749     raeburn  6975:                 $new_values{$file_name."\0".$newkey} = 
                   6976:                                           $$changes{'activate'}{$newitems[$i]};
                   6977:                 $new_control{$newkey} = $now;
                   6978:             }
                   6979:         }
                   6980:     }
                   6981:     my %todelete;
                   6982:     my %changed_items;
                   6983:     foreach my $action ('delete','update') {
                   6984:         if (exists($$changes{$action})) {
                   6985:             if (ref($$changes{$action}) eq 'HASH') {
                   6986:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6987:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6988:                     if ($action eq 'delete') { 
                   6989:                         $todelete{$itemnum} = 1;
                   6990:                     } else {
                   6991:                         $changed_items{$itemnum} = $key;
                   6992:                     }
                   6993:                 }
1.745     raeburn  6994:             }
                   6995:         }
1.749     raeburn  6996:     }
                   6997:     # get lock on access controls for file.
                   6998:     my $lockhash = {
                   6999:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7000:                                                        ':'.$env{'user.domain'},
                   7001:                    }; 
                   7002:     my $tries = 0;
                   7003:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7004:    
                   7005:     while (($gotlock ne 'ok') && $tries <3) {
                   7006:         $tries ++;
                   7007:         sleep 1;
                   7008:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7009:     }
                   7010:     if ($gotlock eq 'ok') {
                   7011:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7012:         my ($tmp)=keys(%curr_permissions);
                   7013:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7014:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7015:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7016:             if (ref($curr_controls) eq 'HASH') {
                   7017:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7018:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7019:                     if (defined($todelete{$itemnum})) {
                   7020:                         push(@deletions,$file_name."\0".$control_item);
                   7021:                     } else {
                   7022:                         if (defined($changed_items{$itemnum})) {
                   7023:                             $new_control{$changed_items{$itemnum}} = $now;
                   7024:                             push(@deletions,$file_name."\0".$control_item);
                   7025:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7026:                         } else {
                   7027:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7028:                         }
                   7029:                     }
1.745     raeburn  7030:                 }
                   7031:             }
                   7032:         }
1.970     raeburn  7033:         my ($group);
                   7034:         if (&is_course($domain,$user)) {
                   7035:             ($group,my $file) = split(/\//,$file_name,2);
                   7036:         }
1.749     raeburn  7037:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7038:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7039:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7040:         #  remove lock
                   7041:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7042:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7043:         my $sqlresult =
1.970     raeburn  7044:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7045:                                     $group);
1.749     raeburn  7046:     } else {
                   7047:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7048:     }
1.749     raeburn  7049:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7050: }
                   7051: 
1.827     raeburn  7052: sub make_public_indefinitely {
                   7053:     my ($requrl) = @_;
                   7054:     my $now = time;
                   7055:     my $action = 'activate';
                   7056:     my $aclnum = 0;
                   7057:     if (&is_portfolio_url($requrl)) {
                   7058:         my (undef,$udom,$unum,$file_name,$group) =
                   7059:             &parse_portfolio_url($requrl);
                   7060:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7061:         my %access_controls = &get_access_controls($current_perms,
                   7062:                                                    $group,$file_name);
                   7063:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7064:             my ($num,$scope,$end,$start) = 
                   7065:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7066:             if ($scope eq 'public') {
                   7067:                 if ($start <= $now && $end == 0) {
                   7068:                     $action = 'none';
                   7069:                 } else {
                   7070:                     $action = 'update';
                   7071:                     $aclnum = $num;
                   7072:                 }
                   7073:                 last;
                   7074:             }
                   7075:         }
                   7076:         if ($action eq 'none') {
                   7077:              return 'ok';
                   7078:         } else {
                   7079:             my %changes;
                   7080:             my $newend = 0;
                   7081:             my $newstart = $now;
                   7082:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7083:             $changes{$action}{$newkey} = {
                   7084:                 type => 'public',
                   7085:                 time => {
                   7086:                     start => $newstart,
                   7087:                     end   => $newend,
                   7088:                 },
                   7089:             };
                   7090:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7091:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7092:             return $outcome;
                   7093:         }
                   7094:     } else {
                   7095:         return 'invalid';
                   7096:     }
                   7097: }
                   7098: 
1.745     raeburn  7099: #------------------------------------------------------Get Marked as Read Only
                   7100: 
                   7101: sub get_marked_as_readonly {
                   7102:     my ($domain,$user,$what,$group) = @_;
                   7103:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7104:     my @readonly_files;
1.629     banghart 7105:     my $cmp1=$what;
                   7106:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7107:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7108:         if (defined($group)) {
                   7109:             if ($file_name !~ m-^\Q$group\E/-) {
                   7110:                 next;
                   7111:             }
                   7112:         }
1.561     banghart 7113:         if (ref($value) eq "ARRAY"){
                   7114:             foreach my $stored_what (@{$value}) {
1.629     banghart 7115:                 my $cmp2=$stored_what;
1.759     albertel 7116:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7117:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7118:                 }
1.629     banghart 7119:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7120:                     push(@readonly_files, $file_name);
1.745     raeburn  7121:                     last;
1.563     banghart 7122:                 } elsif (!defined($what)) {
                   7123:                     push(@readonly_files, $file_name);
1.745     raeburn  7124:                     last;
1.561     banghart 7125:                 }
                   7126:             }
1.745     raeburn  7127:         }
1.561     banghart 7128:     }
                   7129:     return @readonly_files;
                   7130: }
1.577     banghart 7131: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7132: 
1.577     banghart 7133: sub get_marked_as_readonly_hash {
1.745     raeburn  7134:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7135:     my %readonly_files;
1.745     raeburn  7136:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7137:         if (defined($group)) {
                   7138:             if ($file_name !~ m-^\Q$group\E/-) {
                   7139:                 next;
                   7140:             }
                   7141:         }
1.577     banghart 7142:         if (ref($value) eq "ARRAY"){
                   7143:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7144:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7145:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7146:                         if ($lock_descriptor eq 'graded') {
                   7147:                             $readonly_files{$file_name} = 'graded';
                   7148:                         } elsif ($lock_descriptor eq 'handback') {
                   7149:                             $readonly_files{$file_name} = 'handback';
                   7150:                         } else {
                   7151:                             if (!exists($readonly_files{$file_name})) {
                   7152:                                 $readonly_files{$file_name} = 'locked';
                   7153:                             }
                   7154:                         }
1.745     raeburn  7155:                     }
1.750     banghart 7156:                 } 
1.577     banghart 7157:             }
                   7158:         } 
                   7159:     }
                   7160:     return %readonly_files;
                   7161: }
1.559     banghart 7162: # ------------------------------------------------------------ Unmark as Read Only
                   7163: 
                   7164: sub unmark_as_readonly {
1.629     banghart 7165:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7166:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7167:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7168:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7169:     my $symb_crs = $what;
                   7170:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7171:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7172:     my ($tmp)=keys(%current_permissions);
                   7173:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7174:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7175:     foreach my $file (@readonly_files) {
1.759     albertel 7176: 	my $clean_file = &declutter_portfile($file);
                   7177: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7178: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7179:         my @new_locks;
                   7180:         my @del_keys;
                   7181:         if (ref($current_locks) eq "ARRAY"){
                   7182:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7183:                 my $compare=$locker;
1.749     raeburn  7184:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7185:                     $compare=join('',@{$locker});
1.746     raeburn  7186:                     if ($compare ne $symb_crs) {
                   7187:                         push(@new_locks, $locker);
                   7188:                     }
1.563     banghart 7189:                 }
                   7190:             }
1.650     albertel 7191:             if (scalar(@new_locks) > 0) {
1.563     banghart 7192:                 $current_permissions{$file} = \@new_locks;
                   7193:             } else {
                   7194:                 push(@del_keys, $file);
1.613     albertel 7195:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7196:                 delete($current_permissions{$file});
1.563     banghart 7197:             }
                   7198:         }
1.561     banghart 7199:     }
1.613     albertel 7200:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7201:     return;
                   7202: }
1.512     banghart 7203: 
1.17      www      7204: # ------------------------------------------------------------ Directory lister
                   7205: 
                   7206: sub dirlist {
1.955     raeburn  7207:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7208:     $uri=~s/^\///;
                   7209:     $uri=~s/\/$//;
1.253     stredwic 7210:     my ($udom, $uname);
1.955     raeburn  7211:     if ($getuserdir) {
1.253     stredwic 7212:         $udom = $userdomain;
                   7213:         $uname = $username;
1.955     raeburn  7214:     } else {
                   7215:         (undef,$udom,$uname)=split(/\//,$uri);
                   7216:         if(defined($userdomain)) {
                   7217:             $udom = $userdomain;
                   7218:         }
                   7219:         if(defined($username)) {
                   7220:             $uname = $username;
                   7221:         }
1.253     stredwic 7222:     }
1.955     raeburn  7223:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7224: 
1.955     raeburn  7225:     $dirRoot = $perlvar{'lonDocRoot'};
                   7226:     if (defined($getpropath)) {
                   7227:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7228:         $dirRoot =~ s/\/$//;
1.955     raeburn  7229:     } elsif (defined($getuserdir)) {
                   7230:         my $subdir=$uname.'__';
                   7231:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7232:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7233:                    ."/$udom/$subdir/$uname";
                   7234:     } elsif (defined($alternateRoot)) {
                   7235:         $dirRoot = $alternateRoot;
1.751     banghart 7236:     }
1.253     stredwic 7237: 
                   7238:     if($udom) {
                   7239:         if($uname) {
1.955     raeburn  7240:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7241:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7242:                               .':'.&escape($uname).':'.&escape($udom),
                   7243:                               &homeserver($uname,$udom));
                   7244:             if ($listing eq 'unknown_cmd') {
                   7245:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7246:                                   &homeserver($uname,$udom));
                   7247:             } else {
                   7248:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7249:             }
1.605     matthew  7250:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7251:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7252: 				  &homeserver($uname,$udom));
1.605     matthew  7253:                 @listing_results = split(/:/,$listing);
                   7254:             } else {
                   7255:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7256:             }
                   7257:             return @listing_results;
1.955     raeburn  7258:         } elsif(!$alternateRoot) {
1.800     albertel 7259:             my %allusers;
1.841     albertel 7260: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7261:  	    foreach my $tryserver (keys(%servers)) {
                   7262:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7263:                                   &escape($udom),$tryserver);
                   7264:                 if ($listing eq 'unknown_cmd') {
                   7265: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7266: 				      $udom, $tryserver);
                   7267:                 } else {
                   7268:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7269:                 }
1.841     albertel 7270: 		if ($listing eq 'unknown_cmd') {
                   7271: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7272: 				      $udom, $tryserver);
                   7273: 		    @listing_results = split(/:/,$listing);
                   7274: 		} else {
                   7275: 		    @listing_results =
                   7276: 			map { &unescape($_); } split(/:/,$listing);
                   7277: 		}
                   7278: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7279: 		    $listing_results[0] ne 'empty'       &&
                   7280: 		    $listing_results[0] ne 'con_lost') {
                   7281: 		    foreach my $line (@listing_results) {
                   7282: 			my ($entry) = split(/&/,$line,2);
                   7283: 			$allusers{$entry} = 1;
                   7284: 		    }
                   7285: 		}
1.253     stredwic 7286:             }
                   7287:             my $alluserstr='';
1.800     albertel 7288:             foreach my $user (sort(keys(%allusers))) {
                   7289:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7290:             }
                   7291:             $alluserstr=~s/:$//;
                   7292:             return split(/:/,$alluserstr);
                   7293:         } else {
1.800     albertel 7294:             return ('missing user name');
1.253     stredwic 7295:         }
1.955     raeburn  7296:     } elsif(!defined($getpropath)) {
1.841     albertel 7297:         my @all_domains = sort(&all_domains());
1.955     raeburn  7298:         foreach my $domain (@all_domains) {
                   7299:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7300:         }
                   7301:         return @all_domains;
                   7302:     } else {
1.800     albertel 7303:         return ('missing domain');
1.275     stredwic 7304:     }
                   7305: }
                   7306: 
                   7307: # --------------------------------------------- GetFileTimestamp
                   7308: # This function utilizes dirlist and returns the date stamp for
                   7309: # when it was last modified.  It will also return an error of -1
                   7310: # if an error occurs
                   7311: 
                   7312: sub GetFileTimestamp {
1.955     raeburn  7313:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7314:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7315:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7316:     my ($fileStat) = 
                   7317:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7318:                                  undef,$getuserdir);
1.275     stredwic 7319:     my @stats = split('&', $fileStat);
                   7320:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7321:         # @stats contains first the filename, then the stat output
                   7322:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7323:     } else {
                   7324:         return -1;
1.253     stredwic 7325:     }
1.26      www      7326: }
                   7327: 
1.712     albertel 7328: sub stat_file {
                   7329:     my ($uri) = @_;
1.787     albertel 7330:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7331: 
1.955     raeburn  7332:     my ($udom,$uname,$file);
1.712     albertel 7333:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7334: 	($udom,$uname,$file) =
1.811     albertel 7335: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7336: 	$file = 'userfiles/'.$file;
                   7337:     }
                   7338:     if ($uri =~ m-^/res/-) {
                   7339: 	($udom,$uname) = 
1.807     albertel 7340: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7341: 	$file = $uri;
                   7342:     }
                   7343: 
                   7344:     if (!$udom || !$uname || !$file) {
                   7345: 	# unable to handle the uri
                   7346: 	return ();
                   7347:     }
1.956     raeburn  7348:     my $getpropath;
                   7349:     if ($file =~ /^userfiles\//) {
                   7350:         $getpropath = 1;
                   7351:     }
1.955     raeburn  7352:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7353:     my @stats = split('&', $result);
1.721     banghart 7354:     
1.712     albertel 7355:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7356: 	shift(@stats); #filename is first
                   7357: 	return @stats;
                   7358:     }
                   7359:     return ();
                   7360: }
                   7361: 
1.26      www      7362: # -------------------------------------------------------- Value of a Condition
                   7363: 
1.713     albertel 7364: # gets the value of a specific preevaluated condition
                   7365: #    stored in the string  $env{user.state.<cid>}
                   7366: # or looks up a condition reference in the bighash and if if hasn't
                   7367: # already been evaluated recurses into docondval to get the value of
                   7368: # the condition, then memoizing it to 
                   7369: #   $env{user.state.<cid>.<condition>}
1.40      www      7370: sub directcondval {
                   7371:     my $number=shift;
1.620     albertel 7372:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7373: 	&Apache::lonuserstate::evalstate();
                   7374:     }
1.713     albertel 7375:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7376: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7377:     } elsif ($number =~ /^_/) {
                   7378: 	my $sub_condition;
                   7379: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7380: 		&GDBM_READER(),0640)) {
                   7381: 	    $sub_condition=$bighash{'conditions'.$number};
                   7382: 	    untie(%bighash);
                   7383: 	}
                   7384: 	my $value = &docondval($sub_condition);
1.949     raeburn  7385: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7386: 	return $value;
                   7387:     }
1.620     albertel 7388:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7389:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7390:     } else {
                   7391:        return 2;
                   7392:     }
                   7393: }
                   7394: 
1.713     albertel 7395: # get the collection of conditions for this resource
1.26      www      7396: sub condval {
                   7397:     my $condidx=shift;
1.54      www      7398:     my $allpathcond='';
1.713     albertel 7399:     foreach my $cond (split(/\|/,$condidx)) {
                   7400: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7401: 	    $allpathcond.=
                   7402: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7403: 	}
1.191     harris41 7404:     }
1.54      www      7405:     $allpathcond=~s/\|$//;
1.713     albertel 7406:     return &docondval($allpathcond);
                   7407: }
                   7408: 
                   7409: #evaluates an expression of conditions
                   7410: sub docondval {
                   7411:     my ($allpathcond) = @_;
                   7412:     my $result=0;
                   7413:     if ($env{'request.course.id'}
                   7414: 	&& defined($allpathcond)) {
                   7415: 	my $operand='|';
                   7416: 	my @stack;
                   7417: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7418: 	    if ($chunk eq '(') {
                   7419: 		push @stack,($operand,$result);
                   7420: 	    } elsif ($chunk eq ')') {
                   7421: 		my $before=pop @stack;
                   7422: 		if (pop @stack eq '&') {
                   7423: 		    $result=$result>$before?$before:$result;
                   7424: 		} else {
                   7425: 		    $result=$result>$before?$result:$before;
                   7426: 		}
                   7427: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7428: 		$operand=$chunk;
                   7429: 	    } else {
                   7430: 		my $new=directcondval($chunk);
                   7431: 		if ($operand eq '&') {
                   7432: 		    $result=$result>$new?$new:$result;
                   7433: 		} else {
                   7434: 		    $result=$result>$new?$result:$new;
                   7435: 		}
                   7436: 	    }
                   7437: 	}
1.26      www      7438:     }
                   7439:     return $result;
1.421     albertel 7440: }
                   7441: 
                   7442: # ---------------------------------------------------- Devalidate courseresdata
                   7443: 
                   7444: sub devalidatecourseresdata {
                   7445:     my ($coursenum,$coursedomain)=@_;
                   7446:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7447:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7448: }
                   7449: 
1.763     www      7450: 
1.200     www      7451: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7452: #
                   7453: #  Parameters:
                   7454: #      $coursenum    - Number of the course.
                   7455: #      $coursedomain - Domain at which the course was created.
                   7456: #  Returns:
                   7457: #     A hash of the course parameters along (I think) with timestamps
                   7458: #     and version info.
1.877     foxr     7459: 
1.624     albertel 7460: sub get_courseresdata {
                   7461:     my ($coursenum,$coursedomain)=@_;
1.200     www      7462:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7463:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7464:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7465:     my %dumpreply;
1.417     albertel 7466:     unless (defined($cached)) {
1.624     albertel 7467: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7468: 	$result=\%dumpreply;
1.251     albertel 7469: 	my ($tmp) = keys(%dumpreply);
                   7470: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7471: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7472: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7473: 	    return $tmp;
1.416     albertel 7474: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7475: 	    $result=undef;
1.599     albertel 7476: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7477: 	}
                   7478:     }
1.624     albertel 7479:     return $result;
                   7480: }
                   7481: 
1.633     albertel 7482: sub devalidateuserresdata {
                   7483:     my ($uname,$udom)=@_;
                   7484:     my $hashid="$udom:$uname";
                   7485:     &devalidate_cache_new('userres',$hashid);
                   7486: }
                   7487: 
1.624     albertel 7488: sub get_userresdata {
                   7489:     my ($uname,$udom)=@_;
                   7490:     #most student don\'t have any data set, check if there is some data
                   7491:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7492: 
                   7493:     my $hashid="$udom:$uname";
                   7494:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7495:     if (!defined($cached)) {
                   7496: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7497: 	$result=\%resourcedata;
                   7498: 	&do_cache_new('userres',$hashid,$result,600);
                   7499:     }
                   7500:     my ($tmp)=keys(%$result);
                   7501:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7502: 	return $result;
                   7503:     }
                   7504:     #error 2 occurs when the .db doesn't exist
                   7505:     if ($tmp!~/error: 2 /) {
1.672     albertel 7506: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7507: 		 " Trying to get resource data for ".
                   7508: 		 $uname." at ".$udom.": ".
                   7509: 		 $tmp."</font>");
                   7510:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7511: 	#&EXT_cache_set($udom,$uname);
                   7512: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7513: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7514:     }
                   7515:     return $tmp;
                   7516: }
1.879     foxr     7517: #----------------------------------------------- resdata - return resource data
                   7518: #  Purpose:
                   7519: #    Return resource data for either users or for a course.
                   7520: #  Parameters:
                   7521: #     $name      - Course/user name.
                   7522: #     $domain    - Name of the domain the user/course is registered on.
                   7523: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7524: #     @which     - Array of names of resources desired.
                   7525: #  Returns:
                   7526: #     The value of the first reasource in @which that is found in the
                   7527: #     resource hash.
                   7528: #  Exceptional Conditions:
                   7529: #     If the $type passed in is not valid (not the string 'course' or 
                   7530: #     'user', an undefined  reference is returned.
                   7531: #     If none of the resources are found, an undef is returned
1.624     albertel 7532: sub resdata {
                   7533:     my ($name,$domain,$type,@which)=@_;
                   7534:     my $result;
                   7535:     if ($type eq 'course') {
                   7536: 	$result=&get_courseresdata($name,$domain);
                   7537:     } elsif ($type eq 'user') {
                   7538: 	$result=&get_userresdata($name,$domain);
                   7539:     }
                   7540:     if (!ref($result)) { return $result; }    
1.251     albertel 7541:     foreach my $item (@which) {
1.927     albertel 7542: 	if (defined($result->{$item->[0]})) {
                   7543: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7544: 	}
1.250     albertel 7545:     }
1.291     albertel 7546:     return undef;
1.200     www      7547: }
                   7548: 
1.379     matthew  7549: #
                   7550: # EXT resource caching routines
                   7551: #
                   7552: 
                   7553: sub clear_EXT_cache_status {
1.383     albertel 7554:     &delenv('cache.EXT.');
1.379     matthew  7555: }
                   7556: 
                   7557: sub EXT_cache_status {
                   7558:     my ($target_domain,$target_user) = @_;
1.383     albertel 7559:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7560:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7561:         # We know already the user has no data
                   7562:         return 1;
                   7563:     } else {
                   7564:         return 0;
                   7565:     }
                   7566: }
                   7567: 
                   7568: sub EXT_cache_set {
                   7569:     my ($target_domain,$target_user) = @_;
1.383     albertel 7570:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7571:     #&appenv({$cachename => time});
1.379     matthew  7572: }
                   7573: 
1.28      www      7574: # --------------------------------------------------------- Value of a Variable
1.58      www      7575: sub EXT {
1.715     albertel 7576: 
1.395     albertel 7577:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7578:     unless ($varname) { return ''; }
1.218     albertel 7579:     #get real user name/domain, courseid and symb
                   7580:     my $courseid;
1.359     albertel 7581:     my $publicuser;
1.427     www      7582:     if ($symbparm) {
                   7583: 	$symbparm=&get_symb_from_alias($symbparm);
                   7584:     }
1.218     albertel 7585:     if (!($uname && $udom)) {
1.790     albertel 7586:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7587:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7588:     } else {
1.620     albertel 7589: 	$courseid=$env{'request.course.id'};
1.218     albertel 7590:     }
1.48      www      7591:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7592:     my $rest;
1.320     albertel 7593:     if (defined($therest[0])) {
1.48      www      7594:        $rest=join('.',@therest);
                   7595:     } else {
                   7596:        $rest='';
                   7597:     }
1.320     albertel 7598: 
1.57      www      7599:     my $qualifierrest=$qualifier;
                   7600:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7601:     my $spacequalifierrest=$space;
                   7602:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7603:     if ($realm eq 'user') {
1.48      www      7604: # --------------------------------------------------------------- user.resource
                   7605: 	if ($space eq 'resource') {
1.651     albertel 7606: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7607: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7608: 		 &&
1.744     albertel 7609: 		 ($symbparm eq &symbread()) ) {	
                   7610: 		# if we are in the middle of processing the resource the
                   7611: 		# get the value we are planning on committing
                   7612:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7613:                     return $Apache::lonhomework::results{$qualifierrest};
                   7614:                 } else {
                   7615:                     return $Apache::lonhomework::history{$qualifierrest};
                   7616:                 }
1.335     albertel 7617: 	    } else {
1.359     albertel 7618: 		my %restored;
1.620     albertel 7619: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7620: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7621: 		} else {
                   7622: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7623: 		}
1.335     albertel 7624: 		return $restored{$qualifierrest};
                   7625: 	    }
1.48      www      7626: # ----------------------------------------------------------------- user.access
                   7627:         } elsif ($space eq 'access') {
1.218     albertel 7628: 	    # FIXME - not supporting calls for a specific user
1.48      www      7629:             return &allowed($qualifier,$rest);
                   7630: # ------------------------------------------ user.preferences, user.environment
                   7631:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7632: 	    if (($uname eq $env{'user.name'}) &&
                   7633: 		($udom eq $env{'user.domain'})) {
                   7634: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7635: 	    } else {
1.359     albertel 7636: 		my %returnhash;
                   7637: 		if (!$publicuser) {
                   7638: 		    %returnhash=&userenvironment($udom,$uname,
                   7639: 						 $qualifierrest);
                   7640: 		}
1.218     albertel 7641: 		return $returnhash{$qualifierrest};
                   7642: 	    }
1.48      www      7643: # ----------------------------------------------------------------- user.course
                   7644:         } elsif ($space eq 'course') {
1.218     albertel 7645: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7646:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7647: # ------------------------------------------------------------------- user.role
                   7648:         } elsif ($space eq 'role') {
1.218     albertel 7649: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7650:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7651:             if ($qualifier eq 'value') {
                   7652: 		return $role;
                   7653:             } elsif ($qualifier eq 'extent') {
                   7654:                 return $where;
                   7655:             }
                   7656: # ----------------------------------------------------------------- user.domain
                   7657:         } elsif ($space eq 'domain') {
1.218     albertel 7658:             return $udom;
1.48      www      7659: # ------------------------------------------------------------------- user.name
                   7660:         } elsif ($space eq 'name') {
1.218     albertel 7661:             return $uname;
1.48      www      7662: # ---------------------------------------------------- Any other user namespace
1.29      www      7663:         } else {
1.359     albertel 7664: 	    my %reply;
                   7665: 	    if (!$publicuser) {
                   7666: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7667: 	    }
                   7668: 	    return $reply{$qualifierrest};
1.48      www      7669:         }
1.236     www      7670:     } elsif ($realm eq 'query') {
                   7671: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7672:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7673: 						[$spacequalifierrest]);
1.620     albertel 7674: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7675:    } elsif ($realm eq 'request') {
1.48      www      7676: # ------------------------------------------------------------- request.browser
                   7677:         if ($space eq 'browser') {
1.430     www      7678: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7679: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7680: 		    return 1;
                   7681: 		} else {
                   7682: 		    return 0;
                   7683: 		}
                   7684: 	    } else {
1.620     albertel 7685: 		return $env{'browser.'.$qualifier};
1.430     www      7686: 	    }
1.57      www      7687: # ------------------------------------------------------------ request.filename
                   7688:         } else {
1.620     albertel 7689:             return $env{'request.'.$spacequalifierrest};
1.29      www      7690:         }
1.28      www      7691:     } elsif ($realm eq 'course') {
1.48      www      7692: # ---------------------------------------------------------- course.description
1.620     albertel 7693:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7694:     } elsif ($realm eq 'resource') {
1.165     www      7695: 
1.620     albertel 7696: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7697: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7698: 	}
1.693     albertel 7699: 
                   7700: 	if ($space eq 'title') {
                   7701: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7702: 	    return &gettitle($symbparm);
                   7703: 	}
                   7704: 	
                   7705: 	if ($space eq 'map') {
                   7706: 	    my ($map) = &decode_symb($symbparm);
                   7707: 	    return &symbread($map);
                   7708: 	}
1.905     albertel 7709: 	if ($space eq 'filename') {
                   7710: 	    if ($symbparm) {
                   7711: 		return &clutter((&decode_symb($symbparm))[2]);
                   7712: 	    }
                   7713: 	    return &hreflocation('',$env{'request.filename'});
                   7714: 	}
1.693     albertel 7715: 
                   7716: 	my ($section, $group, @groups);
1.593     albertel 7717: 	my ($courselevelm,$courselevel);
1.539     albertel 7718: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7719: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7720: 
1.218     albertel 7721: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7722: 
1.60      www      7723: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7724: 	    my $symbp=$symbparm;
1.735     albertel 7725: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7726: 
                   7727: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7728: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7729: 
1.620     albertel 7730: 	    if (($env{'user.name'} eq $uname) &&
                   7731: 		($env{'user.domain'} eq $udom)) {
                   7732: 		$section=$env{'request.course.sec'};
1.733     raeburn  7733:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7734:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7735: 	    } else {
1.539     albertel 7736: 		if (! defined($usection)) {
1.551     albertel 7737: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7738: 		} else {
                   7739: 		    $section = $usection;
                   7740: 		}
1.733     raeburn  7741:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7742: 	    }
                   7743: 
                   7744: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7745: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7746: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7747: 
1.593     albertel 7748: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7749: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7750: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7751: 
1.60      www      7752: # ----------------------------------------------------------- first, check user
1.624     albertel 7753: 
                   7754: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7755: 				       ([$courselevelr,'resource'],
                   7756: 					[$courselevelm,'map'     ],
                   7757: 					[$courselevel, 'course'  ]));
1.931     albertel 7758: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7759: 
1.594     albertel 7760: # ------------------------------------------------ second, check some of course
1.684     raeburn  7761:             my $coursereply;
1.691     raeburn  7762:             if (@groups > 0) {
                   7763:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7764:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7765:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7766:             }
1.96      www      7767: 
1.684     raeburn  7768: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7769: 				  $env{'course.'.$courseid.'.domain'},
                   7770: 				  'course',
                   7771: 				  ([$seclevelr,   'resource'],
                   7772: 				   [$seclevelm,   'map'     ],
                   7773: 				   [$seclevel,    'course'  ],
                   7774: 				   [$courselevelr,'resource']));
                   7775: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7776: 
1.60      www      7777: # ------------------------------------------------------ third, check map parms
1.218     albertel 7778: 	    my %parmhash=();
                   7779: 	    my $thisparm='';
                   7780: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7781: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7782: 		    &GDBM_READER(),0640)) {
1.218     albertel 7783: 		$thisparm=$parmhash{$symbparm};
                   7784: 		untie(%parmhash);
                   7785: 	    }
1.927     albertel 7786: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7787: 	}
1.594     albertel 7788: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7789: 
1.218     albertel 7790: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7791: 	my $filename;
                   7792: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7793: 	if ($symbparm) {
1.409     www      7794: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7795: 	} else {
1.620     albertel 7796: 	    $filename=$env{'request.filename'};
1.282     albertel 7797: 	}
                   7798: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7799: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7800: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7801: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7802: 
1.927     albertel 7803: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7804: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7805: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7806: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7807: 				     $env{'course.'.$courseid.'.domain'},
                   7808: 				     'course',
1.927     albertel 7809: 				     ([$courselevelm,'map'   ],
                   7810: 				      [$courselevel, 'course']));
                   7811: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7812: 	}
1.145     www      7813: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7814: 	unless ($space eq '0') {
1.336     albertel 7815: 	    my @parts=split(/_/,$space);
                   7816: 	    my $id=pop(@parts);
                   7817: 	    my $part=join('_',@parts);
                   7818: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7819: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7820: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7821: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7822: 	}
1.395     albertel 7823: 	if ($recurse) { return undef; }
                   7824: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7825: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7826: # ---------------------------------------------------- Any other user namespace
                   7827:     } elsif ($realm eq 'environment') {
                   7828: # ----------------------------------------------------------------- environment
1.620     albertel 7829: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7830: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7831: 	} else {
1.770     albertel 7832: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7833: 		return '';
                   7834: 	    }
1.219     albertel 7835: 	    my %returnhash=&userenvironment($udom,$uname,
                   7836: 					    $spacequalifierrest);
                   7837: 	    return $returnhash{$spacequalifierrest};
                   7838: 	}
1.28      www      7839:     } elsif ($realm eq 'system') {
1.48      www      7840: # ----------------------------------------------------------------- system.time
                   7841: 	if ($space eq 'time') {
                   7842: 	    return time;
                   7843:         }
1.696     albertel 7844:     } elsif ($realm eq 'server') {
                   7845: # ----------------------------------------------------------------- system.time
                   7846: 	if ($space eq 'name') {
                   7847: 	    return $ENV{'SERVER_NAME'};
                   7848:         }
1.28      www      7849:     }
1.48      www      7850:     return '';
1.61      www      7851: }
                   7852: 
1.927     albertel 7853: sub get_reply {
                   7854:     my ($reply_value) = @_;
1.940     raeburn  7855:     if (ref($reply_value) eq 'ARRAY') {
                   7856:         if (wantarray) {
                   7857: 	    return @$reply_value;
                   7858:         }
                   7859:         return $reply_value->[0];
                   7860:     } else {
                   7861:         return $reply_value;
1.927     albertel 7862:     }
                   7863: }
                   7864: 
1.691     raeburn  7865: sub check_group_parms {
                   7866:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7867:     my @groupitems = ();
                   7868:     my $resultitem;
1.927     albertel 7869:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7870:     foreach my $group (@{$groups}) {
                   7871:         foreach my $level (@levels) {
1.927     albertel 7872:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7873:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7874:         }
                   7875:     }
                   7876:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7877:                             $env{'course.'.$courseid.'.domain'},
                   7878:                                      'course',@groupitems);
                   7879:     return $coursereply;
                   7880: }
                   7881: 
                   7882: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7883:     my ($courseid,@groups) = @_;
                   7884:     @groups = sort(@groups);
1.691     raeburn  7885:     return @groups;
                   7886: }
                   7887: 
1.395     albertel 7888: sub packages_tab_default {
                   7889:     my ($uri,$varname)=@_;
                   7890:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7891: 
                   7892:     my (@extension,@specifics,$do_default);
                   7893:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7894: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7895: 	if ($pack_type eq 'default') {
                   7896: 	    $do_default=1;
                   7897: 	} elsif ($pack_type eq 'extension') {
                   7898: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7899: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7900: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7901: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7902: 	}
                   7903:     }
                   7904:     # first look for a package that matches the requested part id
                   7905:     foreach my $package (@specifics) {
                   7906: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7907: 	next if ($pack_part ne $part);
                   7908: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7909: 	    return $packagetab{"$pack_type&$name&default"};
                   7910: 	}
                   7911:     }
                   7912:     # look for any possible matching non extension_ package
                   7913:     foreach my $package (@specifics) {
                   7914: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7915: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7916: 	    return $packagetab{"$pack_type&$name&default"};
                   7917: 	}
1.585     albertel 7918: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7919: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7920: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7921: 	}
                   7922:     }
1.738     albertel 7923:     # look for any posible extension_ match
                   7924:     foreach my $package (@extension) {
                   7925: 	my ($package,$pack_type)=@{$package};
                   7926: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7927: 	    return $packagetab{"$pack_type&$name&default"};
                   7928: 	}
                   7929: 	if (defined($packagetab{$package."&$name&default"})) {
                   7930: 	    return $packagetab{$package."&$name&default"};
                   7931: 	}
                   7932:     }
                   7933:     # look for a global default setting
                   7934:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7935: 	return $packagetab{"default&$name&default"};
                   7936:     }
1.395     albertel 7937:     return undef;
                   7938: }
                   7939: 
1.334     albertel 7940: sub add_prefix_and_part {
                   7941:     my ($prefix,$part)=@_;
                   7942:     my $keyroot;
                   7943:     if (defined($prefix) && $prefix !~ /^__/) {
                   7944: 	# prefix that has a part already
                   7945: 	$keyroot=$prefix;
                   7946:     } elsif (defined($prefix)) {
                   7947: 	# prefix that is missing a part
                   7948: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7949:     } else {
                   7950: 	# no prefix at all
                   7951: 	if (defined($part)) { $keyroot='_'.$part; }
                   7952:     }
                   7953:     return $keyroot;
                   7954: }
                   7955: 
1.71      www      7956: # ---------------------------------------------------------------- Get metadata
                   7957: 
1.599     albertel 7958: my %metaentry;
1.71      www      7959: sub metadata {
1.176     www      7960:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7961:     $uri=&declutter($uri);
1.288     albertel 7962:     # if it is a non metadata possible uri return quickly
1.529     albertel 7963:     if (($uri eq '') || 
                   7964: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7965: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7966:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7967: 	return undef;
                   7968:     }
                   7969:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7970: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7971: 	return undef;
1.288     albertel 7972:     }
1.73      www      7973:     my $filename=$uri;
                   7974:     $uri=~s/\.meta$//;
1.172     www      7975: #
                   7976: # Is the metadata already cached?
1.177     www      7977: # Look at timestamp of caching
1.172     www      7978: # Everything is cached by the main uri, libraries are never directly cached
                   7979: #
1.428     albertel 7980:     if (!defined($liburi)) {
1.599     albertel 7981: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7982: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7983:     }
                   7984:     {
1.172     www      7985: #
                   7986: # Is this a recursive call for a library?
                   7987: #
1.599     albertel 7988: #	if (! exists($metacache{$uri})) {
                   7989: #	    $metacache{$uri}={};
                   7990: #	}
1.924     albertel 7991: 	my $cachetime = 60*60;
1.171     www      7992:         if ($liburi) {
                   7993: 	    $liburi=&declutter($liburi);
                   7994:             $filename=$liburi;
1.401     bowersj2 7995:         } else {
1.599     albertel 7996: 	    &devalidate_cache_new('meta',$uri);
                   7997: 	    undef(%metaentry);
1.401     bowersj2 7998: 	}
1.140     www      7999:         my %metathesekeys=();
1.73      www      8000:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8001: 	my $metastring;
1.924     albertel 8002: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8003: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8004: 	    $metastring = 
1.929     albertel 8005: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8006: 					  ('grade_target' => 'meta'));
                   8007: 	    $cachetime = 1; # only want this cached in the child not long term
                   8008: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8009: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8010: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8011: 	    $metastring=&getfile($file);
1.489     albertel 8012: 	}
1.208     albertel 8013:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8014:         my $token;
1.140     www      8015:         undef %metathesekeys;
1.71      www      8016:         while ($token=$parser->get_token) {
1.339     albertel 8017: 	    if ($token->[0] eq 'S') {
                   8018: 		if (defined($token->[2]->{'package'})) {
1.172     www      8019: #
                   8020: # This is a package - get package info
                   8021: #
1.339     albertel 8022: 		    my $package=$token->[2]->{'package'};
                   8023: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8024: 		    if (defined($token->[2]->{'id'})) { 
                   8025: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8026: 		    }
1.599     albertel 8027: 		    if ($metaentry{':packages'}) {
                   8028: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8029: 		    } else {
1.599     albertel 8030: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8031: 		    }
1.736     albertel 8032: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8033: 			my $part=$keyroot;
                   8034: 			$part=~s/^\_//;
1.736     albertel 8035: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8036: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8037: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8038: 			    # ignore package.tab specified default values
                   8039:                             # here &package_tab_default() will fetch those
                   8040: 			    if ($subp eq 'default') { next; }
1.736     albertel 8041: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8042: 			    my $unikey;
                   8043: 			    if ($pack =~ /_0$/) {
                   8044: 				$unikey='parameter_0_'.$name;
                   8045: 				$part=0;
                   8046: 			    } else {
                   8047: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8048: 			    }
1.339     albertel 8049: 			    if ($subp eq 'display') {
                   8050: 				$value.=' [Part: '.$part.']';
                   8051: 			    }
1.599     albertel 8052: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8053: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8054: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8055: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8056: 			    }
1.599     albertel 8057: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8058: 				$metaentry{':'.$unikey}=
                   8059: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8060: 			    }
1.339     albertel 8061: 			}
                   8062: 		    }
                   8063: 		} else {
1.172     www      8064: #
                   8065: # This is not a package - some other kind of start tag
1.339     albertel 8066: #
                   8067: 		    my $entry=$token->[1];
                   8068: 		    my $unikey;
                   8069: 		    if ($entry eq 'import') {
                   8070: 			$unikey='';
                   8071: 		    } else {
                   8072: 			$unikey=$entry;
                   8073: 		    }
                   8074: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8075: 
                   8076: 		    if (defined($token->[2]->{'id'})) { 
                   8077: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8078: 		    }
1.175     www      8079: 
1.339     albertel 8080: 		    if ($entry eq 'import') {
1.175     www      8081: #
                   8082: # Importing a library here
1.339     albertel 8083: #
                   8084: 			if ($depthcount<20) {
                   8085: 			    my $location=$parser->get_text('/import');
                   8086: 			    my $dir=$filename;
                   8087: 			    $dir=~s|[^/]*$||;
                   8088: 			    $location=&filelocation($dir,$location);
1.736     albertel 8089: 			    my $metadata = 
                   8090: 				&metadata($uri,'keys', $location,$unikey,
                   8091: 					  $depthcount+1);
                   8092: 			    foreach my $meta (split(',',$metadata)) {
                   8093: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8094: 				$metathesekeys{$meta}=1;
1.339     albertel 8095: 			    }
                   8096: 			}
                   8097: 		    } else { 
                   8098: 			
                   8099: 			if (defined($token->[2]->{'name'})) { 
                   8100: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8101: 			}
                   8102: 			$metathesekeys{$unikey}=1;
1.736     albertel 8103: 			foreach my $param (@{$token->[3]}) {
                   8104: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8105: 				$token->[2]->{$param};
1.339     albertel 8106: 			}
                   8107: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8108: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8109: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8110: 		 # only ws inside the tag, and not in default, so use default
                   8111: 		 # as value
1.599     albertel 8112: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8113: 			} elsif ( $internaltext =~ /\S/ ) {
                   8114: 		  # something interesting inside the tag
                   8115: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8116: 			} else {
1.908     albertel 8117: 		  # no interesting values, don't set a default
1.339     albertel 8118: 			}
1.172     www      8119: # end of not-a-package not-a-library import
1.339     albertel 8120: 		    }
1.172     www      8121: # end of not-a-package start tag
1.339     albertel 8122: 		}
1.172     www      8123: # the next is the end of "start tag"
1.339     albertel 8124: 	    }
                   8125: 	}
1.483     albertel 8126: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8127: 	$extension = lc($extension);
                   8128: 	if ($extension eq 'htm') { $extension='html'; }
                   8129: 
1.737     albertel 8130: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8131: 	    #no specific packages #how's our extension
                   8132: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8133: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8134: 					 \%metathesekeys);
                   8135: 	}
1.883     albertel 8136: 
                   8137: 	if (!exists($metaentry{':packages'})
                   8138: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8139: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8140: 		#no specific packages well let's get default then
                   8141: 		if ($key!~/^default&/) { next; }
1.488     albertel 8142: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8143: 					     \%metathesekeys);
                   8144: 	    }
                   8145: 	}
1.338     www      8146: # are there custom rights to evaluate
1.599     albertel 8147: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8148: 
1.338     www      8149:     #
                   8150:     # Importing a rights file here
1.339     albertel 8151:     #
                   8152: 	    unless ($depthcount) {
1.599     albertel 8153: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8154: 		my $dir=$filename;
                   8155: 		$dir=~s|[^/]*$||;
                   8156: 		$location=&filelocation($dir,$location);
1.736     albertel 8157: 		my $rights_metadata =
                   8158: 		    &metadata($uri,'keys',$location,'_rights',
                   8159: 			      $depthcount+1);
                   8160: 		foreach my $rights (split(',',$rights_metadata)) {
                   8161: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8162: 		    $metathesekeys{$rights}=1;
1.339     albertel 8163: 		}
                   8164: 	    }
                   8165: 	}
1.737     albertel 8166: 	# uniqifiy package listing
                   8167: 	my %seen;
                   8168: 	my @uniq_packages =
                   8169: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8170: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8171: 
                   8172: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8173: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8174: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8175: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8176: # this is the end of "was not already recently cached
1.71      www      8177:     }
1.599     albertel 8178:     return $metaentry{':'.$what};
1.261     albertel 8179: }
                   8180: 
1.488     albertel 8181: sub metadata_create_package_def {
1.483     albertel 8182:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8183:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8184:     if ($subp eq 'default') { next; }
                   8185:     
1.599     albertel 8186:     if (defined($metaentry{':packages'})) {
                   8187: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8188:     } else {
1.599     albertel 8189: 	$metaentry{':packages'}=$package;
1.483     albertel 8190:     }
                   8191:     my $value=$packagetab{$key};
                   8192:     my $unikey;
                   8193:     $unikey='parameter_0_'.$name;
1.599     albertel 8194:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8195:     $$metathesekeys{$unikey}=1;
1.599     albertel 8196:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8197: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8198:     }
1.599     albertel 8199:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8200: 	$metaentry{':'.$unikey}=
                   8201: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8202:     }
                   8203: }
                   8204: 
1.261     albertel 8205: sub metadata_generate_part0 {
                   8206:     my ($metadata,$metacache,$uri) = @_;
                   8207:     my %allnames;
1.737     albertel 8208:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8209: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8210: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8211: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8212: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8213: 	    $allnames{$name}=$part;
                   8214: 	  }
                   8215: 	}
                   8216:     }
                   8217:     foreach my $name (keys(%allnames)) {
                   8218:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8219:       my $key=":parameter_0_$name";
1.261     albertel 8220:       $$metacache{"$key.part"}='0';
                   8221:       $$metacache{"$key.name"}=$name;
1.428     albertel 8222:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8223: 					   $allnames{$name}.'_'.$name.
                   8224: 					   '.type'};
1.428     albertel 8225:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8226: 			     '.display'};
1.644     www      8227:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8228:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8229:       $$metacache{"$key.display"}=$olddis;
                   8230:     }
1.71      www      8231: }
                   8232: 
1.764     albertel 8233: # ------------------------------------------------------ Devalidate title cache
                   8234: 
                   8235: sub devalidate_title_cache {
                   8236:     my ($url)=@_;
                   8237:     if (!$env{'request.course.id'}) { return; }
                   8238:     my $symb=&symbread($url);
                   8239:     if (!$symb) { return; }
                   8240:     my $key=$env{'request.course.id'}."\0".$symb;
                   8241:     &devalidate_cache_new('title',$key);
                   8242: }
                   8243: 
1.1014    droeschl 8244: # ------------------------------------------------- Get the title of a course
                   8245: 
                   8246: sub current_course_title {
                   8247:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8248: }
1.301     www      8249: # ------------------------------------------------- Get the title of a resource
                   8250: 
                   8251: sub gettitle {
                   8252:     my $urlsymb=shift;
                   8253:     my $symb=&symbread($urlsymb);
1.534     albertel 8254:     if ($symb) {
1.620     albertel 8255: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8256: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8257: 	if (defined($cached)) { 
                   8258: 	    return $result;
                   8259: 	}
1.534     albertel 8260: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8261: 	my $title='';
1.907     albertel 8262: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8263: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8264: 	} else {
                   8265: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8266: 		    &GDBM_READER(),0640)) {
                   8267: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8268: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8269: 		untie(%bighash);
                   8270: 	    }
1.534     albertel 8271: 	}
                   8272: 	$title=~s/\&colon\;/\:/gs;
                   8273: 	if ($title) {
1.599     albertel 8274: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8275: 	}
                   8276: 	$urlsymb=$url;
                   8277:     }
                   8278:     my $title=&metadata($urlsymb,'title');
                   8279:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8280:     return $title;
1.301     www      8281: }
1.613     albertel 8282: 
1.614     albertel 8283: sub get_slot {
                   8284:     my ($which,$cnum,$cdom)=@_;
                   8285:     if (!$cnum || !$cdom) {
1.790     albertel 8286: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8287: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8288: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8289:     }
1.703     albertel 8290:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8291:     my %slotinfo;
                   8292:     if (exists($remembered{$key})) {
                   8293: 	$slotinfo{$which} = $remembered{$key};
                   8294:     } else {
                   8295: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8296: 	&Apache::lonhomework::showhash(%slotinfo);
                   8297: 	my ($tmp)=keys(%slotinfo);
                   8298: 	if ($tmp=~/^error:/) { return (); }
                   8299: 	$remembered{$key} = $slotinfo{$which};
                   8300:     }
1.616     albertel 8301:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8302: 	return %{$slotinfo{$which}};
                   8303:     }
                   8304:     return $slotinfo{$which};
1.614     albertel 8305: }
1.31      www      8306: # ------------------------------------------------- Update symbolic store links
                   8307: 
                   8308: sub symblist {
                   8309:     my ($mapname,%newhash)=@_;
1.438     www      8310:     $mapname=&deversion(&declutter($mapname));
1.31      www      8311:     my %hash;
1.620     albertel 8312:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8313:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8314:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8315: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8316: 		next if ($url eq 'last_known'
                   8317: 			 && $env{'form.no_update_last_known'});
                   8318: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8319: 						    $newhash{$url}->[1],
                   8320: 						    $newhash{$url}->[0]);
1.191     harris41 8321:             }
1.31      www      8322:             if (untie(%hash)) {
                   8323: 		return 'ok';
                   8324:             }
                   8325:         }
                   8326:     }
                   8327:     return 'error';
1.212     www      8328: }
                   8329: 
                   8330: # --------------------------------------------------------------- Verify a symb
                   8331: 
                   8332: sub symbverify {
1.510     www      8333:     my ($symb,$thisurl)=@_;
                   8334:     my $thisfn=$thisurl;
1.439     www      8335:     $thisfn=&declutter($thisfn);
1.215     www      8336: # direct jump to resource in page or to a sequence - will construct own symbs
                   8337:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8338: # check URL part
1.409     www      8339:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8340: 
1.431     www      8341:     unless ($url eq $thisfn) { return 0; }
1.213     www      8342: 
1.216     www      8343:     $symb=&symbclean($symb);
1.510     www      8344:     $thisurl=&deversion($thisurl);
1.439     www      8345:     $thisfn=&deversion($thisfn);
1.213     www      8346: 
                   8347:     my %bighash;
                   8348:     my $okay=0;
1.431     www      8349: 
1.620     albertel 8350:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8351:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8352:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8353:             $thisurl =~ s/\?.+$//;
                   8354:         }
1.510     www      8355:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8356:         unless ($ids) { 
1.510     www      8357:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8358:         }
                   8359:         if ($ids) {
                   8360: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8361: 	    foreach my $id (split(/\,/,$ids)) {
                   8362: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8363:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8364:                    $symb =~ s/\?.+$//;
                   8365:                }
1.216     www      8366:                if (
                   8367:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8368:    eq $symb) { 
1.620     albertel 8369: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8370: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8371: 		       $okay=1; 
                   8372: 		   }
                   8373: 	       }
1.216     www      8374: 	   }
                   8375:         }
1.213     www      8376: 	untie(%bighash);
                   8377:     }
                   8378:     return $okay;
1.31      www      8379: }
                   8380: 
1.210     www      8381: # --------------------------------------------------------------- Clean-up symb
                   8382: 
                   8383: sub symbclean {
                   8384:     my $symb=shift;
1.568     albertel 8385:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8386: # remove version from map
                   8387:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8388: 
1.210     www      8389: # remove version from URL
                   8390:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8391: 
1.507     www      8392: # remove wrapper
                   8393: 
1.510     www      8394:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8395:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8396:     return $symb;
1.409     www      8397: }
                   8398: 
                   8399: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8400: 
                   8401: sub encode_symb {
                   8402:     my ($map,$resid,$url)=@_;
                   8403:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8404: }
1.409     www      8405: 
                   8406: sub decode_symb {
1.568     albertel 8407:     my $symb=shift;
                   8408:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8409:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8410:     return (&fixversion($map),$resid,&fixversion($url));
                   8411: }
                   8412: 
                   8413: sub fixversion {
                   8414:     my $fn=shift;
1.609     banghart 8415:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8416:     my %bighash;
                   8417:     my $uri=&clutter($fn);
1.620     albertel 8418:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8419: # is this cached?
1.599     albertel 8420:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8421:     if (defined($cached)) { return $result; }
                   8422: # unfortunately not cached, or expired
1.620     albertel 8423:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8424: 	    &GDBM_READER(),0640)) {
                   8425:  	if ($bighash{'version_'.$uri}) {
                   8426:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8427:  	    unless (($version eq 'mostrecent') || 
                   8428: 		    ($version==&getversion($uri))) {
1.440     www      8429:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8430:  	    }
                   8431:  	}
                   8432:  	untie %bighash;
1.413     www      8433:     }
1.599     albertel 8434:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8435: }
                   8436: 
                   8437: sub deversion {
                   8438:     my $url=shift;
                   8439:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8440:     return $url;
1.210     www      8441: }
                   8442: 
1.31      www      8443: # ------------------------------------------------------ Return symb list entry
                   8444: 
                   8445: sub symbread {
1.249     www      8446:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8447:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8448:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8449: # no filename provided? try from environment
1.44      www      8450:     unless ($thisfn) {
1.620     albertel 8451:         if ($env{'request.symb'}) {
                   8452: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8453: 	}
1.620     albertel 8454: 	$thisfn=$env{'request.filename'};
1.44      www      8455:     }
1.569     albertel 8456:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8457: # is that filename actually a symb? Verify, clean, and return
                   8458:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8459: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8460: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8461: 	}
1.242     www      8462:     }
1.44      www      8463:     $thisfn=declutter($thisfn);
1.31      www      8464:     my %hash;
1.37      www      8465:     my %bighash;
                   8466:     my $syval='';
1.620     albertel 8467:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8468:         my $targetfn = $thisfn;
1.609     banghart 8469:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8470:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8471:         }
1.687     albertel 8472: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8473: 	    $targetfn=$1;
                   8474: 	}
1.620     albertel 8475:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8476:                       &GDBM_READER(),0640)) {
1.481     raeburn  8477: 	    $syval=$hash{$targetfn};
1.37      www      8478:             untie(%hash);
                   8479:         }
                   8480: # ---------------------------------------------------------- There was an entry
                   8481:         if ($syval) {
1.601     albertel 8482: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8483: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8484: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8485: 		    #return $env{$cache_str}='';
1.601     albertel 8486: 		#}    
                   8487: 		#$syval.=$1;
                   8488: 	    #}
1.37      www      8489:         } else {
                   8490: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8491:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8492:                             &GDBM_READER(),0640)) {
1.37      www      8493: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8494:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8495:               unless ($ids) { 
                   8496:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8497:               }
                   8498:               unless ($ids) {
                   8499: # alias?
                   8500: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8501:               }
1.37      www      8502:               if ($ids) {
                   8503: # ------------------------------------------------------------------- Has ID(s)
                   8504:                  my @possibilities=split(/\,/,$ids);
1.39      www      8505:                  if ($#possibilities==0) {
                   8506: # ----------------------------------------------- There is only one possibility
1.37      www      8507: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8508: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8509: 						    $resid,$thisfn);
1.249     www      8510:                  } elsif (!$donotrecurse) {
1.39      www      8511: # ------------------------------------------ There is more than one possibility
                   8512:                      my $realpossible=0;
1.800     albertel 8513:                      foreach my $id (@possibilities) {
                   8514: 			 my $file=$bighash{'src_'.$id};
1.39      www      8515:                          if (&allowed('bre',$file)) {
1.800     albertel 8516:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8517:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8518: 				$realpossible++;
1.626     albertel 8519:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8520: 						    $resid,$thisfn);
1.39      www      8521:                             }
                   8522: 			 }
1.191     harris41 8523:                      }
1.39      www      8524: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8525:                  } else {
                   8526:                      $syval='';
1.37      www      8527:                  }
                   8528: 	      }
                   8529:               untie(%bighash)
1.481     raeburn  8530:            }
1.31      www      8531:         }
1.62      www      8532:         if ($syval) {
1.620     albertel 8533: 	    return $env{$cache_str}=$syval;
1.62      www      8534:         }
1.31      www      8535:     }
1.949     raeburn  8536:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8537:     return $env{$cache_str}='';
1.31      www      8538: }
                   8539: 
                   8540: # ---------------------------------------------------------- Return random seed
                   8541: 
1.32      www      8542: sub numval {
                   8543:     my $txt=shift;
                   8544:     $txt=~tr/A-J/0-9/;
                   8545:     $txt=~tr/a-j/0-9/;
                   8546:     $txt=~tr/K-T/0-9/;
                   8547:     $txt=~tr/k-t/0-9/;
                   8548:     $txt=~tr/U-Z/0-5/;
                   8549:     $txt=~tr/u-z/0-5/;
                   8550:     $txt=~s/\D//g;
1.564     albertel 8551:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8552:     return int($txt);
1.368     albertel 8553: }
                   8554: 
1.484     albertel 8555: sub numval2 {
                   8556:     my $txt=shift;
                   8557:     $txt=~tr/A-J/0-9/;
                   8558:     $txt=~tr/a-j/0-9/;
                   8559:     $txt=~tr/K-T/0-9/;
                   8560:     $txt=~tr/k-t/0-9/;
                   8561:     $txt=~tr/U-Z/0-5/;
                   8562:     $txt=~tr/u-z/0-5/;
                   8563:     $txt=~s/\D//g;
                   8564:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8565:     my $total;
                   8566:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8567:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8568:     return int($total);
                   8569: }
                   8570: 
1.575     albertel 8571: sub numval3 {
                   8572:     use integer;
                   8573:     my $txt=shift;
                   8574:     $txt=~tr/A-J/0-9/;
                   8575:     $txt=~tr/a-j/0-9/;
                   8576:     $txt=~tr/K-T/0-9/;
                   8577:     $txt=~tr/k-t/0-9/;
                   8578:     $txt=~tr/U-Z/0-5/;
                   8579:     $txt=~tr/u-z/0-5/;
                   8580:     $txt=~s/\D//g;
                   8581:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8582:     my $total;
                   8583:     foreach my $val (@txts) { $total+=$val; }
                   8584:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8585:     return $total;
                   8586: }
                   8587: 
1.675     albertel 8588: sub digest {
                   8589:     my ($data)=@_;
                   8590:     my $digest=&Digest::MD5::md5($data);
                   8591:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8592:     my ($e,$f);
                   8593:     {
                   8594:         use integer;
                   8595:         $e=($a+$b);
                   8596:         $f=($c+$d);
                   8597:         if ($_64bit) {
                   8598:             $e=(($e<<32)>>32);
                   8599:             $f=(($f<<32)>>32);
                   8600:         }
                   8601:     }
                   8602:     if (wantarray) {
                   8603: 	return ($e,$f);
                   8604:     } else {
                   8605: 	my $g;
                   8606: 	{
                   8607: 	    use integer;
                   8608: 	    $g=($e+$f);
                   8609: 	    if ($_64bit) {
                   8610: 		$g=(($g<<32)>>32);
                   8611: 	    }
                   8612: 	}
                   8613: 	return $g;
                   8614:     }
                   8615: }
                   8616: 
1.368     albertel 8617: sub latest_rnd_algorithm_id {
1.675     albertel 8618:     return '64bit5';
1.366     albertel 8619: }
1.32      www      8620: 
1.503     albertel 8621: sub get_rand_alg {
                   8622:     my ($courseid)=@_;
1.790     albertel 8623:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8624:     if ($courseid) {
1.620     albertel 8625: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8626:     }
                   8627:     return &latest_rnd_algorithm_id();
                   8628: }
                   8629: 
1.562     albertel 8630: sub validCODE {
                   8631:     my ($CODE)=@_;
                   8632:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8633:     return 0;
                   8634: }
                   8635: 
1.491     albertel 8636: sub getCODE {
1.620     albertel 8637:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8638:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8639: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8640: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8641: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8642:     }
                   8643:     return undef;
                   8644: }
                   8645: 
1.31      www      8646: sub rndseed {
1.155     albertel 8647:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8648:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8649:     if (!defined($symb)) {
1.366     albertel 8650: 	unless ($symb=$wsymb) { return time; }
                   8651:     }
                   8652:     if (!$courseid) { $courseid=$wcourseid; }
                   8653:     if (!$domain) { $domain=$wdomain; }
                   8654:     if (!$username) { $username=$wusername }
1.503     albertel 8655:     my $which=&get_rand_alg();
1.803     albertel 8656: 
1.491     albertel 8657:     if (defined(&getCODE())) {
1.675     albertel 8658: 	if ($which eq '64bit5') {
                   8659: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8660: 	} elsif ($which eq '64bit4') {
1.575     albertel 8661: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8662: 	} else {
                   8663: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8664: 	}
1.675     albertel 8665:     } elsif ($which eq '64bit5') {
                   8666: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8667:     } elsif ($which eq '64bit4') {
                   8668: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8669:     } elsif ($which eq '64bit3') {
                   8670: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8671:     } elsif ($which eq '64bit2') {
                   8672: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8673:     } elsif ($which eq '64bit') {
                   8674: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8675:     }
                   8676:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8677: }
                   8678: 
                   8679: sub rndseed_32bit {
                   8680:     my ($symb,$courseid,$domain,$username)=@_;
                   8681:     {
                   8682: 	use integer;
                   8683: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8684: 	my $symbseed=numval($symb) << 22;
                   8685: 	my $namechck=unpack("%32C*",$username) << 17;
                   8686: 	my $nameseed=numval($username) << 12;
                   8687: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8688: 	my $courseseed=unpack("%32C*",$courseid);
                   8689: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8690: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8691: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8692: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8693: 	return $num;
                   8694:     }
                   8695: }
                   8696: 
                   8697: sub rndseed_64bit {
                   8698:     my ($symb,$courseid,$domain,$username)=@_;
                   8699:     {
                   8700: 	use integer;
                   8701: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8702: 	my $symbseed=numval($symb) << 10;
                   8703: 	my $namechck=unpack("%32S*",$username);
                   8704: 	
                   8705: 	my $nameseed=numval($username) << 21;
                   8706: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8707: 	my $courseseed=unpack("%32S*",$courseid);
                   8708: 	
                   8709: 	my $num1=$symbchck+$symbseed+$namechck;
                   8710: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8711: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8712: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8713: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8714: 	return "$num1,$num2";
1.155     albertel 8715:     }
1.366     albertel 8716: }
                   8717: 
1.443     albertel 8718: sub rndseed_64bit2 {
                   8719:     my ($symb,$courseid,$domain,$username)=@_;
                   8720:     {
                   8721: 	use integer;
                   8722: 	# strings need to be an even # of cahracters long, it it is odd the
                   8723:         # last characters gets thrown away
                   8724: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8725: 	my $symbseed=numval($symb) << 10;
                   8726: 	my $namechck=unpack("%32S*",$username.' ');
                   8727: 	
                   8728: 	my $nameseed=numval($username) << 21;
1.501     albertel 8729: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8730: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8731: 	
                   8732: 	my $num1=$symbchck+$symbseed+$namechck;
                   8733: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8734: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8735: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8736: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8737: 	return "$num1,$num2";
                   8738:     }
                   8739: }
                   8740: 
                   8741: sub rndseed_64bit3 {
                   8742:     my ($symb,$courseid,$domain,$username)=@_;
                   8743:     {
                   8744: 	use integer;
                   8745: 	# strings need to be an even # of cahracters long, it it is odd the
                   8746:         # last characters gets thrown away
                   8747: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8748: 	my $symbseed=numval2($symb) << 10;
                   8749: 	my $namechck=unpack("%32S*",$username.' ');
                   8750: 	
                   8751: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8752: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8753: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8754: 	
                   8755: 	my $num1=$symbchck+$symbseed+$namechck;
                   8756: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8757: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8758: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8759: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8760: 	
1.503     albertel 8761: 	return "$num1:$num2";
1.443     albertel 8762:     }
                   8763: }
                   8764: 
1.575     albertel 8765: sub rndseed_64bit4 {
                   8766:     my ($symb,$courseid,$domain,$username)=@_;
                   8767:     {
                   8768: 	use integer;
                   8769: 	# strings need to be an even # of cahracters long, it it is odd the
                   8770:         # last characters gets thrown away
                   8771: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8772: 	my $symbseed=numval3($symb) << 10;
                   8773: 	my $namechck=unpack("%32S*",$username.' ');
                   8774: 	
                   8775: 	my $nameseed=numval3($username) << 21;
                   8776: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8777: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8778: 	
                   8779: 	my $num1=$symbchck+$symbseed+$namechck;
                   8780: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8781: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8782: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8783: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8784: 	
                   8785: 	return "$num1:$num2";
                   8786:     }
                   8787: }
                   8788: 
1.675     albertel 8789: sub rndseed_64bit5 {
                   8790:     my ($symb,$courseid,$domain,$username)=@_;
                   8791:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8792:     return "$num1:$num2";
                   8793: }
                   8794: 
1.366     albertel 8795: sub rndseed_CODE_64bit {
                   8796:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8797:     {
1.366     albertel 8798: 	use integer;
1.443     albertel 8799: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8800: 	my $symbseed=numval2($symb);
1.491     albertel 8801: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8802: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8803: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8804: 	my $num1=$symbseed+$CODEchck;
                   8805: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8806: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8807: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8808: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8809: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8810: 	return "$num1:$num2";
1.366     albertel 8811:     }
                   8812: }
                   8813: 
1.575     albertel 8814: sub rndseed_CODE_64bit4 {
                   8815:     my ($symb,$courseid,$domain,$username)=@_;
                   8816:     {
                   8817: 	use integer;
                   8818: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8819: 	my $symbseed=numval3($symb);
                   8820: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8821: 	my $CODEseed=numval3(&getCODE());
                   8822: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8823: 	my $num1=$symbseed+$CODEchck;
                   8824: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8825: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8826: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8827: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8828: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8829: 	return "$num1:$num2";
                   8830:     }
                   8831: }
                   8832: 
1.675     albertel 8833: sub rndseed_CODE_64bit5 {
                   8834:     my ($symb,$courseid,$domain,$username)=@_;
                   8835:     my $code = &getCODE();
                   8836:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8837:     return "$num1:$num2";
                   8838: }
                   8839: 
1.366     albertel 8840: sub setup_random_from_rndseed {
                   8841:     my ($rndseed)=@_;
1.503     albertel 8842:     if ($rndseed =~/([,:])/) {
                   8843: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8844: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8845:     } else {
                   8846: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8847:     }
1.36      albertel 8848: }
                   8849: 
1.474     albertel 8850: sub latest_receipt_algorithm_id {
1.835     albertel 8851:     return 'receipt3';
1.474     albertel 8852: }
                   8853: 
1.480     www      8854: sub recunique {
                   8855:     my $fucourseid=shift;
                   8856:     my $unique;
1.835     albertel 8857:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8858: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8859: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8860:     } else {
                   8861: 	$unique=$perlvar{'lonReceipt'};
                   8862:     }
                   8863:     return unpack("%32C*",$unique);
                   8864: }
                   8865: 
                   8866: sub recprefix {
                   8867:     my $fucourseid=shift;
                   8868:     my $prefix;
1.835     albertel 8869:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8870: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8871: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8872:     } else {
                   8873: 	$prefix=$perlvar{'lonHostID'};
                   8874:     }
                   8875:     return unpack("%32C*",$prefix);
                   8876: }
                   8877: 
1.76      www      8878: sub ireceipt {
1.474     albertel 8879:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8880: 
                   8881:     my $return =&recprefix($fucourseid).'-';
                   8882: 
                   8883:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8884: 	$env{'request.state'} eq 'construct') {
                   8885: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8886: 	return $return;
                   8887:     }
                   8888: 
1.76      www      8889:     my $cuname=unpack("%32C*",$funame);
                   8890:     my $cudom=unpack("%32C*",$fudom);
                   8891:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8892:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8893:     my $cunique=&recunique($fucourseid);
1.474     albertel 8894:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8895:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8896: 
1.790     albertel 8897: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8898: 			       
                   8899: 	$return.= ($cunique%$cuname+
                   8900: 		   $cunique%$cudom+
                   8901: 		   $cusymb%$cuname+
                   8902: 		   $cusymb%$cudom+
                   8903: 		   $cucourseid%$cuname+
                   8904: 		   $cucourseid%$cudom+
                   8905: 		   $cpart%$cuname+
                   8906: 		   $cpart%$cudom);
                   8907:     } else {
                   8908: 	$return.= ($cunique%$cuname+
                   8909: 		   $cunique%$cudom+
                   8910: 		   $cusymb%$cuname+
                   8911: 		   $cusymb%$cudom+
                   8912: 		   $cucourseid%$cuname+
                   8913: 		   $cucourseid%$cudom);
                   8914:     }
                   8915:     return $return;
1.76      www      8916: }
                   8917: 
                   8918: sub receipt {
1.474     albertel 8919:     my ($part)=@_;
1.790     albertel 8920:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8921:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8922: }
1.260     ng       8923: 
1.790     albertel 8924: sub whichuser {
                   8925:     my ($passedsymb)=@_;
                   8926:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8927:     if (defined($env{'form.grade_symb'})) {
                   8928: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8929: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8930: 	if (!$allowed &&
                   8931: 	    exists($env{'request.course.sec'}) &&
                   8932: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8933: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8934: 			      '/'.$env{'request.course.sec'});
                   8935: 	}
                   8936: 	if ($allowed) {
                   8937: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8938: 	    $courseid=$tmp_courseid;
                   8939: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8940: 	    ($name)=&get_env_multiple('form.grade_username');
                   8941: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8942: 	}
                   8943:     }
                   8944:     if (!$passedsymb) {
                   8945: 	$symb=&symbread();
                   8946:     } else {
                   8947: 	$symb=$passedsymb;
                   8948:     }
                   8949:     $courseid=$env{'request.course.id'};
                   8950:     $domain=$env{'user.domain'};
                   8951:     $name=$env{'user.name'};
                   8952:     if ($name eq 'public' && $domain eq 'public') {
                   8953: 	if (!defined($env{'form.username'})) {
                   8954: 	    $env{'form.username'}.=time.rand(10000000);
                   8955: 	}
                   8956: 	$name.=$env{'form.username'};
                   8957:     }
                   8958:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8959: 
                   8960: }
                   8961: 
1.36      albertel 8962: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8963: # returns either the contents of the file or 
                   8964: # -1 if the file doesn't exist
1.481     raeburn  8965: #
                   8966: # if the target is a file that was uploaded via DOCS, 
                   8967: # a check will be made to see if a current copy exists on the local server,
                   8968: # if it does this will be served, otherwise a copy will be retrieved from
                   8969: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8970: # the local server.   
1.472     albertel 8971: 
1.36      albertel 8972: sub getfile {
1.538     albertel 8973:     my ($file) = @_;
1.609     banghart 8974:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8975:     &repcopy($file);
                   8976:     return &readfile($file);
                   8977: }
                   8978: 
                   8979: sub repcopy_userfile {
                   8980:     my ($file)=@_;
1.609     banghart 8981:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8982:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8983:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8984: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8985:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8986:     if (-e "$file") {
1.828     www      8987: # we already have a local copy, check it out
1.538     albertel 8988: 	my @fileinfo = stat($file);
1.828     www      8989: 	my $rtncode;
                   8990: 	my $info;
1.538     albertel 8991: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8992: 	if ($lwpresp ne 'ok') {
1.828     www      8993: # there is no such file anymore, even though we had a local copy
1.482     albertel 8994: 	    if ($rtncode eq '404') {
1.538     albertel 8995: 		unlink($file);
1.482     albertel 8996: 	    }
                   8997: 	    return -1;
                   8998: 	}
                   8999: 	if ($info < $fileinfo[9]) {
1.828     www      9000: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9001: 	    return 'ok';
1.828     www      9002: 	} else {
                   9003: # the file is outdated, get rid of it
                   9004: 	    unlink($file);
1.482     albertel 9005: 	}
1.828     www      9006:     }
                   9007: # one way or the other, at this point, we don't have the file
                   9008: # construct the correct path for the file
                   9009:     my @parts = ($cdom,$cnum); 
                   9010:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9011: 	push @parts, split(/\//,$1);
                   9012:     }
                   9013:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9014:     foreach my $part (@parts) {
                   9015: 	$path .= '/'.$part;
                   9016: 	if (!-e $path) {
                   9017: 	    mkdir($path,0770);
1.482     albertel 9018: 	}
                   9019:     }
1.828     www      9020: # now the path exists for sure
                   9021: # get a user agent
                   9022:     my $ua=new LWP::UserAgent;
                   9023:     my $transferfile=$file.'.in.transfer';
                   9024: # FIXME: this should flock
                   9025:     if (-e $transferfile) { return 'ok'; }
                   9026:     my $request;
                   9027:     $uri=~s/^\///;
1.980     raeburn  9028:     my $homeserver = &homeserver($cnum,$cdom);
                   9029:     my $protocol = $protocol{$homeserver};
                   9030:     $protocol = 'http' if ($protocol ne 'https');
                   9031:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9032:     my $response=$ua->request($request,$transferfile);
                   9033: # did it work?
                   9034:     if ($response->is_error()) {
                   9035: 	unlink($transferfile);
                   9036: 	&logthis("Userfile repcopy failed for $uri");
                   9037: 	return -1;
                   9038:     }
                   9039: # worked, rename the transfer file
                   9040:     rename($transferfile,$file);
1.607     raeburn  9041:     return 'ok';
1.481     raeburn  9042: }
                   9043: 
1.517     albertel 9044: sub tokenwrapper {
                   9045:     my $uri=shift;
1.980     raeburn  9046:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9047:     $uri=~s|^/||;
1.620     albertel 9048:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9049:     my $token=$1;
1.552     albertel 9050:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9051:     if ($udom && $uname && $file) {
                   9052: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9053:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9054:         my $homeserver = &homeserver($uname,$udom);
                   9055:         my $protocol = $protocol{$homeserver};
                   9056:         $protocol = 'http' if ($protocol ne 'https');
                   9057:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9058:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9059:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9060:     } else {
                   9061:         return '/adm/notfound.html';
                   9062:     }
                   9063: }
                   9064: 
1.828     www      9065: # call with reqtype HEAD: get last modification time
                   9066: # call with reqtype GET: get the file contents
                   9067: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9068: #
1.481     raeburn  9069: sub getuploaded {
                   9070:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9071:     $uri=~s/^\///;
1.980     raeburn  9072:     my $homeserver = &homeserver($cnum,$cdom);
                   9073:     my $protocol = $protocol{$homeserver};
                   9074:     $protocol = 'http' if ($protocol ne 'https');
                   9075:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9076:     my $ua=new LWP::UserAgent;
                   9077:     my $request=new HTTP::Request($reqtype,$uri);
                   9078:     my $response=$ua->request($request);
                   9079:     $$rtncode = $response->code;
1.482     albertel 9080:     if (! $response->is_success()) {
                   9081: 	return 'failed';
                   9082:     }      
                   9083:     if ($reqtype eq 'HEAD') {
1.486     www      9084: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9085:     } elsif ($reqtype eq 'GET') {
                   9086: 	$$info = $response->content;
1.472     albertel 9087:     }
1.482     albertel 9088:     return 'ok';
1.36      albertel 9089: }
                   9090: 
1.481     raeburn  9091: sub readfile {
                   9092:     my $file = shift;
                   9093:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9094:     my $fh;
                   9095:     open($fh,"<$file");
                   9096:     my $a='';
1.800     albertel 9097:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9098:     return $a;
                   9099: }
                   9100: 
1.36      albertel 9101: sub filelocation {
1.590     banghart 9102:     my ($dir,$file) = @_;
                   9103:     my $location;
                   9104:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9105: 
                   9106:     if ($file =~ m-^/adm/-) {
                   9107: 	$file=~s-^/adm/wrapper/-/-;
                   9108: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9109:     }
1.882     albertel 9110: 
1.590     banghart 9111:     if ($file=~m:^/~:) { # is a contruction space reference
                   9112:         $location = $file;
                   9113:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9114:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9115: 	# is a correct contruction space reference
                   9116:         $location = $file;
1.956     raeburn  9117:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9118:         $location = $file;
1.609     banghart 9119:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9120:         my ($udom,$uname,$filename)=
1.811     albertel 9121:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9122:         my $home=&homeserver($uname,$udom);
                   9123:         my $is_me=0;
                   9124:         my @ids=&current_machine_ids();
                   9125:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9126:         if ($is_me) {
1.955     raeburn  9127:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9128:         } else {
                   9129:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9130:   	      $udom.'/'.$uname.'/'.$filename;
                   9131:         }
1.882     albertel 9132:     } elsif ($file =~ m-^/adm/-) {
                   9133: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9134:     } else {
                   9135:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9136:         $file=~s:^/res/:/:;
                   9137:         if ( !( $file =~ m:^/:) ) {
                   9138:             $location = $dir. '/'.$file;
                   9139:         } else {
                   9140:             $location = '/home/httpd/html/res'.$file;
                   9141:         }
1.59      albertel 9142:     }
1.590     banghart 9143:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9144:     while ($location=~m{/\.\./}) {
                   9145: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9146: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9147: 	} else {
                   9148: 	    $location=~ s{/\.\./}{/}g;
                   9149: 	}
                   9150:     } #remove dir/..
1.590     banghart 9151:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9152:     return $location;
1.46      www      9153: }
1.36      albertel 9154: 
1.46      www      9155: sub hreflocation {
                   9156:     my ($dir,$file)=@_;
1.980     raeburn  9157:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9158: 	$file=filelocation($dir,$file);
1.700     albertel 9159:     } elsif ($file=~m-^/adm/-) {
                   9160: 	$file=~s-^/adm/wrapper/-/-;
                   9161: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9162:     }
                   9163:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9164: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9165:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9166: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9167:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9168: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9169: 	    -/uploaded/$1/$2/-x;
1.46      www      9170:     }
1.913     albertel 9171:     if ($file=~ m{^/userfiles/}) {
                   9172: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9173:     }
1.462     albertel 9174:     return $file;
1.465     albertel 9175: }
                   9176: 
                   9177: sub current_machine_domains {
1.853     albertel 9178:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9179: }
                   9180: 
                   9181: sub machine_domains {
                   9182:     my ($hostname) = @_;
1.465     albertel 9183:     my @domains;
1.838     albertel 9184:     my %hostname = &all_hostnames();
1.465     albertel 9185:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9186: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9187: 	if ($hostname eq $name) {
1.844     albertel 9188: 	    push(@domains,&host_domain($id));
1.465     albertel 9189: 	}
                   9190:     }
                   9191:     return @domains;
                   9192: }
                   9193: 
                   9194: sub current_machine_ids {
1.853     albertel 9195:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9196: }
                   9197: 
                   9198: sub machine_ids {
                   9199:     my ($hostname) = @_;
                   9200:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9201:     my @ids;
1.888     albertel 9202:     my %name_to_host = &all_names();
1.889     albertel 9203:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9204: 	return @{ $name_to_host{$hostname} };
                   9205:     }
                   9206:     return;
1.31      www      9207: }
                   9208: 
1.824     raeburn  9209: sub additional_machine_domains {
                   9210:     my @domains;
                   9211:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9212:     while( my $line = <$fh>) {
                   9213:         $line =~ s/\s//g;
                   9214:         push(@domains,$line);
                   9215:     }
                   9216:     return @domains;
                   9217: }
                   9218: 
                   9219: sub default_login_domain {
                   9220:     my $domain = $perlvar{'lonDefDomain'};
                   9221:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9222:     foreach my $posdom (&current_machine_domains(),
                   9223:                         &additional_machine_domains()) {
                   9224:         if (lc($posdom) eq lc($testdomain)) {
                   9225:             $domain=$posdom;
                   9226:             last;
                   9227:         }
                   9228:     }
                   9229:     return $domain;
                   9230: }
                   9231: 
1.31      www      9232: # ------------------------------------------------------------- Declutters URLs
                   9233: 
                   9234: sub declutter {
                   9235:     my $thisfn=shift;
1.569     albertel 9236:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9237:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9238:     $thisfn=~s/^\///;
1.697     albertel 9239:     $thisfn=~s|^adm/wrapper/||;
                   9240:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9241:     $thisfn=~s/^res\///;
1.1032    raeburn  9242:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9243:         $thisfn=~s/\?.+$//;
                   9244:     }
1.268     www      9245:     return $thisfn;
                   9246: }
                   9247: 
                   9248: # ------------------------------------------------------------- Clutter up URLs
                   9249: 
                   9250: sub clutter {
                   9251:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9252:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9253: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9254:        $thisfn='/res'.$thisfn; 
                   9255:     }
1.1031    raeburn  9256:     if ($thisfn !~m|^/adm|) {
                   9257: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9258: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9259: 	} else {
                   9260: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9261: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9262: 	    if ($embstyle eq 'ssi'
                   9263: 		|| ($embstyle eq 'hdn')
                   9264: 		|| ($embstyle eq 'rat')
                   9265: 		|| ($embstyle eq 'prv')
                   9266: 		|| ($embstyle eq 'ign')) {
                   9267: 		#do nothing with these
                   9268: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9269: 		|| ($embstyle eq 'emb')
                   9270: 		|| ($embstyle eq 'wrp')) {
                   9271: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9272: 	    } elsif ($embstyle eq 'unk'
                   9273: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9274: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9275: 	    } else {
1.718     www      9276: #		&logthis("Got a blank emb style");
1.695     albertel 9277: 	    }
1.694     albertel 9278: 	}
                   9279:     }
1.31      www      9280:     return $thisfn;
1.12      www      9281: }
                   9282: 
1.787     albertel 9283: sub clutter_with_no_wrapper {
                   9284:     my $uri = &clutter(shift);
                   9285:     if ($uri =~ m-^/adm/-) {
                   9286: 	$uri =~ s-^/adm/wrapper/-/-;
                   9287: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9288:     }
                   9289:     return $uri;
                   9290: }
                   9291: 
1.557     albertel 9292: sub freeze_escape {
                   9293:     my ($value)=@_;
                   9294:     if (ref($value)) {
                   9295: 	$value=&nfreeze($value);
                   9296: 	return '__FROZEN__'.&escape($value);
                   9297:     }
                   9298:     return &escape($value);
                   9299: }
                   9300: 
1.11      www      9301: 
1.557     albertel 9302: sub thaw_unescape {
                   9303:     my ($value)=@_;
                   9304:     if ($value =~ /^__FROZEN__/) {
                   9305: 	substr($value,0,10,undef);
                   9306: 	$value=&unescape($value);
                   9307: 	return &thaw($value);
                   9308:     }
                   9309:     return &unescape($value);
                   9310: }
                   9311: 
1.436     albertel 9312: sub correct_line_ends {
                   9313:     my ($result)=@_;
                   9314:     $$result =~s/\r\n/\n/mg;
                   9315:     $$result =~s/\r/\n/mg;
1.415     albertel 9316: }
1.1       albertel 9317: # ================================================================ Main Program
                   9318: 
1.184     www      9319: sub goodbye {
1.204     albertel 9320:    &logthis("Starting Shut down");
1.443     albertel 9321: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9322:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9323: #converted
1.599     albertel 9324: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9325:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9326: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9327: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9328: #1.1 only
1.870     albertel 9329: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9330: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9331: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9332: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9333:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9334:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9335:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9336:    &flushcourselogs();
                   9337:    &logthis("Shutting down");
                   9338: }
                   9339: 
1.852     albertel 9340: sub get_dns {
1.869     albertel 9341:     my ($url,$func,$ignore_cache) = @_;
                   9342:     if (!$ignore_cache) {
                   9343: 	my ($content,$cached)=
                   9344: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9345: 	if ($cached) {
                   9346: 	    &$func($content);
                   9347: 	    return;
                   9348: 	}
                   9349:     }
                   9350: 
                   9351:     my %alldns;
1.852     albertel 9352:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9353:     foreach my $dns (<$config>) {
                   9354: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9355:         my $line = $1;
                   9356:         my ($host,$protocol) = split(/:/,$line);
                   9357:         if ($protocol ne 'https') {
                   9358:             $protocol = 'http';
                   9359:         }
                   9360: 	$alldns{$host} = $protocol;
1.869     albertel 9361:     }
                   9362:     while (%alldns) {
                   9363: 	my ($dns) = keys(%alldns);
1.852     albertel 9364: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9365: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9366: 	my $response=$ua->request($request);
1.979     raeburn  9367:         delete($alldns{$dns});
1.852     albertel 9368: 	next if ($response->is_error());
                   9369: 	my @content = split("\n",$response->content);
1.869     albertel 9370: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9371: 	&$func(\@content);
1.869     albertel 9372: 	return;
1.852     albertel 9373:     }
                   9374:     close($config);
1.871     albertel 9375:     my $which = (split('/',$url))[3];
                   9376:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9377:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9378:     my @content = <$config>;
                   9379:     &$func(\@content);
                   9380:     return;
1.852     albertel 9381: }
1.327     albertel 9382: # ------------------------------------------------------------ Read domain file
                   9383: {
1.852     albertel 9384:     my $loaded;
1.846     albertel 9385:     my %domain;
                   9386: 
1.852     albertel 9387:     sub parse_domain_tab {
                   9388: 	my ($lines) = @_;
                   9389: 	foreach my $line (@$lines) {
                   9390: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9391: 
1.846     albertel 9392: 	    chomp($line);
1.852     albertel 9393: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9394: 	    my %this_domain;
                   9395: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9396: 			       'lang_def', 'city', 'longi', 'lati',
                   9397: 			       'primary') {
                   9398: 		$this_domain{$field} = shift(@elements);
                   9399: 	    }
                   9400: 	    $domain{$name} = \%this_domain;
1.852     albertel 9401: 	}
                   9402:     }
1.864     albertel 9403: 
                   9404:     sub reset_domain_info {
                   9405: 	undef($loaded);
                   9406: 	undef(%domain);
                   9407:     }
                   9408: 
1.852     albertel 9409:     sub load_domain_tab {
1.869     albertel 9410: 	my ($ignore_cache) = @_;
                   9411: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9412: 	my $fh;
                   9413: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9414: 	    my @lines = <$fh>;
                   9415: 	    &parse_domain_tab(\@lines);
1.448     albertel 9416: 	}
1.852     albertel 9417: 	close($fh);
                   9418: 	$loaded = 1;
1.327     albertel 9419:     }
1.846     albertel 9420: 
                   9421:     sub domain {
1.852     albertel 9422: 	&load_domain_tab() if (!$loaded);
                   9423: 
1.846     albertel 9424: 	my ($name,$what) = @_;
                   9425: 	return if ( !exists($domain{$name}) );
                   9426: 
                   9427: 	if (!$what) {
                   9428: 	    return $domain{$name}{'description'};
                   9429: 	}
                   9430: 	return $domain{$name}{$what};
                   9431:     }
1.974     raeburn  9432: 
                   9433:     sub domain_info {
                   9434:         &load_domain_tab() if (!$loaded);
                   9435:         return %domain;
                   9436:     }
                   9437: 
1.327     albertel 9438: }
                   9439: 
                   9440: 
1.1       albertel 9441: # ------------------------------------------------------------- Read hosts file
                   9442: {
1.838     albertel 9443:     my %hostname;
1.844     albertel 9444:     my %hostdom;
1.845     albertel 9445:     my %libserv;
1.852     albertel 9446:     my $loaded;
1.888     albertel 9447:     my %name_to_host;
1.852     albertel 9448: 
                   9449:     sub parse_hosts_tab {
                   9450: 	my ($file) = @_;
                   9451: 	foreach my $configline (@$file) {
                   9452: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9453: 	    next if ($configline =~ /^\^/);
                   9454: 	    chomp($configline);
1.968     raeburn  9455: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 9456: 	    $name=~s/\s//g;
                   9457: 	    if ($id && $domain && $role && $name) {
                   9458: 		$hostname{$id}=$name;
1.888     albertel 9459: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9460: 		$hostdom{$id}=$domain;
                   9461: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9462:                 if (defined($protocol)) {
                   9463:                     if ($protocol eq 'https') {
                   9464:                         $protocol{$id} = $protocol;
                   9465:                     } else {
                   9466:                         $protocol{$id} = 'http'; 
                   9467:                     }
1.968     raeburn  9468:                 } else {
1.969     raeburn  9469:                     $protocol{$id} = 'http';
1.968     raeburn  9470:                 }
1.852     albertel 9471: 	    }
                   9472: 	}
                   9473:     }
1.864     albertel 9474:     
                   9475:     sub reset_hosts_info {
1.897     albertel 9476: 	&purge_remembered();
1.864     albertel 9477: 	&reset_domain_info();
                   9478: 	&reset_hosts_ip_info();
1.892     albertel 9479: 	undef(%name_to_host);
1.864     albertel 9480: 	undef(%hostname);
                   9481: 	undef(%hostdom);
                   9482: 	undef(%libserv);
                   9483: 	undef($loaded);
                   9484:     }
1.1       albertel 9485: 
1.852     albertel 9486:     sub load_hosts_tab {
1.869     albertel 9487: 	my ($ignore_cache) = @_;
                   9488: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9489: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9490: 	my @config = <$config>;
                   9491: 	&parse_hosts_tab(\@config);
                   9492: 	close($config);
                   9493: 	$loaded=1;
1.1       albertel 9494:     }
1.852     albertel 9495: 
1.838     albertel 9496:     sub hostname {
1.852     albertel 9497: 	&load_hosts_tab() if (!$loaded);
                   9498: 
1.838     albertel 9499: 	my ($lonid) = @_;
                   9500: 	return $hostname{$lonid};
                   9501:     }
1.845     albertel 9502: 
1.838     albertel 9503:     sub all_hostnames {
1.852     albertel 9504: 	&load_hosts_tab() if (!$loaded);
                   9505: 
1.838     albertel 9506: 	return %hostname;
                   9507:     }
1.845     albertel 9508: 
1.888     albertel 9509:     sub all_names {
                   9510: 	&load_hosts_tab() if (!$loaded);
                   9511: 
                   9512: 	return %name_to_host;
                   9513:     }
                   9514: 
1.974     raeburn  9515:     sub all_host_domain {
                   9516:         &load_hosts_tab() if (!$loaded);
                   9517:         return %hostdom;
                   9518:     }
                   9519: 
1.845     albertel 9520:     sub is_library {
1.852     albertel 9521: 	&load_hosts_tab() if (!$loaded);
                   9522: 
1.845     albertel 9523: 	return exists($libserv{$_[0]});
                   9524:     }
                   9525: 
                   9526:     sub all_library {
1.852     albertel 9527: 	&load_hosts_tab() if (!$loaded);
                   9528: 
1.845     albertel 9529: 	return %libserv;
                   9530:     }
                   9531: 
1.841     albertel 9532:     sub get_servers {
1.852     albertel 9533: 	&load_hosts_tab() if (!$loaded);
                   9534: 
1.841     albertel 9535: 	my ($domain,$type) = @_;
                   9536: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9537: 	                                          : %hostname;
                   9538: 	my %result;
1.842     albertel 9539: 	if (ref($domain) eq 'ARRAY') {
                   9540: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9541: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9542: 		    $result{$host} = $hostname;
                   9543: 		}
                   9544: 	    }
                   9545: 	} else {
                   9546: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9547: 		if ($hostdom{$host} eq $domain) {
                   9548: 		    $result{$host} = $hostname;
                   9549: 		}
1.841     albertel 9550: 	    }
                   9551: 	}
                   9552: 	return %result;
                   9553:     }
1.845     albertel 9554: 
1.844     albertel 9555:     sub host_domain {
1.852     albertel 9556: 	&load_hosts_tab() if (!$loaded);
                   9557: 
1.844     albertel 9558: 	my ($lonid) = @_;
                   9559: 	return $hostdom{$lonid};
                   9560:     }
                   9561: 
1.841     albertel 9562:     sub all_domains {
1.852     albertel 9563: 	&load_hosts_tab() if (!$loaded);
                   9564: 
1.841     albertel 9565: 	my %seen;
                   9566: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9567: 	return @uniq;
                   9568:     }
1.1       albertel 9569: }
                   9570: 
1.847     albertel 9571: { 
                   9572:     my %iphost;
1.856     albertel 9573:     my %name_to_ip;
                   9574:     my %lonid_to_ip;
1.869     albertel 9575: 
1.847     albertel 9576:     sub get_hosts_from_ip {
                   9577: 	my ($ip) = @_;
                   9578: 	my %iphosts = &get_iphost();
                   9579: 	if (ref($iphosts{$ip})) {
                   9580: 	    return @{$iphosts{$ip}};
                   9581: 	}
                   9582: 	return;
1.839     albertel 9583:     }
1.864     albertel 9584:     
                   9585:     sub reset_hosts_ip_info {
                   9586: 	undef(%iphost);
                   9587: 	undef(%name_to_ip);
                   9588: 	undef(%lonid_to_ip);
                   9589:     }
1.856     albertel 9590: 
                   9591:     sub get_host_ip {
                   9592: 	my ($lonid) = @_;
                   9593: 	if (exists($lonid_to_ip{$lonid})) {
                   9594: 	    return $lonid_to_ip{$lonid};
                   9595: 	}
                   9596: 	my $name=&hostname($lonid);
                   9597:    	my $ip = gethostbyname($name);
                   9598: 	return if (!$ip || length($ip) ne 4);
                   9599: 	$ip=inet_ntoa($ip);
                   9600: 	$name_to_ip{$name}   = $ip;
                   9601: 	$lonid_to_ip{$lonid} = $ip;
                   9602: 	return $ip;
                   9603:     }
1.847     albertel 9604:     
                   9605:     sub get_iphost {
1.869     albertel 9606: 	my ($ignore_cache) = @_;
1.894     albertel 9607: 
1.869     albertel 9608: 	if (!$ignore_cache) {
                   9609: 	    if (%iphost) {
                   9610: 		return %iphost;
                   9611: 	    }
                   9612: 	    my ($ip_info,$cached)=
                   9613: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9614: 	    if ($cached) {
                   9615: 		%iphost      = %{$ip_info->[0]};
                   9616: 		%name_to_ip  = %{$ip_info->[1]};
                   9617: 		%lonid_to_ip = %{$ip_info->[2]};
                   9618: 		return %iphost;
                   9619: 	    }
                   9620: 	}
1.894     albertel 9621: 
                   9622: 	# get yesterday's info for fallback
                   9623: 	my %old_name_to_ip;
                   9624: 	my ($ip_info,$cached)=
                   9625: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9626: 	if ($cached) {
                   9627: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9628: 	}
                   9629: 
1.888     albertel 9630: 	my %name_to_host = &all_names();
                   9631: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9632: 	    my $ip;
                   9633: 	    if (!exists($name_to_ip{$name})) {
                   9634: 		$ip = gethostbyname($name);
                   9635: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9636: 		    if (defined($old_name_to_ip{$name})) {
                   9637: 			$ip = $old_name_to_ip{$name};
                   9638: 			&logthis("Can't find $name defaulting to old $ip");
                   9639: 		    } else {
                   9640: 			&logthis("Name $name no IP found");
                   9641: 			next;
                   9642: 		    }
                   9643: 		} else {
                   9644: 		    $ip=inet_ntoa($ip);
1.847     albertel 9645: 		}
                   9646: 		$name_to_ip{$name} = $ip;
                   9647: 	    } else {
                   9648: 		$ip = $name_to_ip{$name};
1.653     albertel 9649: 	    }
1.888     albertel 9650: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9651: 		$lonid_to_ip{$id} = $ip;
                   9652: 	    }
                   9653: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9654: 	}
1.869     albertel 9655: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9656: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9657: 				      48*60*60);
1.869     albertel 9658: 
1.847     albertel 9659: 	return %iphost;
1.598     albertel 9660:     }
                   9661: 
1.992     raeburn  9662:     #
                   9663:     #  Given a DNS returns the loncapa host name for that DNS 
                   9664:     # 
                   9665:     sub host_from_dns {
                   9666:         my ($dns) = @_;
                   9667:         my @hosts;
                   9668:         my $ip;
                   9669: 
1.993     raeburn  9670:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9671:             $ip = $name_to_ip{$dns};
                   9672:         }
                   9673:         if (!$ip) {
                   9674:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9675:             if (length($ip) == 4) { 
                   9676: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9677:             }
                   9678:         }
                   9679:         if ($ip) {
                   9680: 	    @hosts = get_hosts_from_ip($ip);
                   9681: 	    return $hosts[0];
                   9682:         }
                   9683:         return undef;
1.986     foxr     9684:     }
1.992     raeburn  9685: 
1.986     foxr     9686: }
                   9687: 
1.862     albertel 9688: BEGIN {
                   9689: 
                   9690: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9691:     unless ($readit) {
                   9692: {
                   9693:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9694:     %perlvar = (%perlvar,%{$configvars});
                   9695: }
                   9696: 
                   9697: 
1.1       albertel 9698: # ------------------------------------------------------ Read spare server file
                   9699: {
1.448     albertel 9700:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9701: 
                   9702:     while (my $configline=<$config>) {
                   9703:        chomp($configline);
1.284     matthew  9704:        if ($configline) {
1.784     albertel 9705: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9706: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9707: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9708:        }
                   9709:     }
1.448     albertel 9710:     close($config);
1.1       albertel 9711: }
1.11      www      9712: # ------------------------------------------------------------ Read permissions
                   9713: {
1.448     albertel 9714:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9715: 
                   9716:     while (my $configline=<$config>) {
1.448     albertel 9717: 	chomp($configline);
                   9718: 	if ($configline) {
                   9719: 	    my ($role,$perm)=split(/ /,$configline);
                   9720: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9721: 	}
1.11      www      9722:     }
1.448     albertel 9723:     close($config);
1.11      www      9724: }
                   9725: 
                   9726: # -------------------------------------------- Read plain texts for permissions
                   9727: {
1.448     albertel 9728:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9729: 
                   9730:     while (my $configline=<$config>) {
1.448     albertel 9731: 	chomp($configline);
                   9732: 	if ($configline) {
1.742     raeburn  9733: 	    my ($short,@plain)=split(/:/,$configline);
                   9734:             %{$prp{$short}} = ();
                   9735: 	    if (@plain > 0) {
                   9736:                 $prp{$short}{'std'} = $plain[0];
                   9737:                 for (my $i=1; $i<@plain; $i++) {
                   9738:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9739:                 }
                   9740:             }
1.448     albertel 9741: 	}
1.135     www      9742:     }
1.448     albertel 9743:     close($config);
1.135     www      9744: }
                   9745: 
                   9746: # ---------------------------------------------------------- Read package table
                   9747: {
1.448     albertel 9748:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9749: 
                   9750:     while (my $configline=<$config>) {
1.483     albertel 9751: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9752: 	chomp($configline);
                   9753: 	my ($short,$plain)=split(/:/,$configline);
                   9754: 	my ($pack,$name)=split(/\&/,$short);
                   9755: 	if ($plain ne '') {
                   9756: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9757: 	    $packagetab{$short}=$plain; 
                   9758: 	}
1.11      www      9759:     }
1.448     albertel 9760:     close($config);
1.329     matthew  9761: }
                   9762: 
                   9763: # ------------- set up temporary directory
                   9764: {
                   9765:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9766: 
1.11      www      9767: }
                   9768: 
1.794     albertel 9769: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9770: 				'compress_threshold'=> 20_000,
                   9771:  			        });
1.185     www      9772: 
1.281     www      9773: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9774: $dumpcount=0;
1.958     www      9775: $locknum=0;
1.22      www      9776: 
1.163     harris41 9777: &logtouch();
1.672     albertel 9778: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9779: $readit=1;
1.564     albertel 9780:     {
                   9781: 	use integer;
                   9782: 	my $test=(2**32)+1;
1.568     albertel 9783: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9784: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9785:     }
1.195     www      9786: }
1.1       albertel 9787: }
1.179     www      9788: 
1.1       albertel 9789: 1;
1.191     harris41 9790: __END__
                   9791: 
1.243     albertel 9792: =pod
                   9793: 
1.191     harris41 9794: =head1 NAME
                   9795: 
1.243     albertel 9796: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9797: 
                   9798: =head1 SYNOPSIS
                   9799: 
1.243     albertel 9800: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9801: 
                   9802:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9803: 
1.243     albertel 9804: Common parameters:
                   9805: 
                   9806: =over 4
                   9807: 
                   9808: =item *
                   9809: 
                   9810: $uname : an internal username (if $cname expecting a course Id specifically)
                   9811: 
                   9812: =item *
                   9813: 
                   9814: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9815: 
                   9816: =item *
                   9817: 
                   9818: $symb : a resource instance identifier
                   9819: 
                   9820: =item *
                   9821: 
                   9822: $namespace : the name of a .db file that contains the data needed or
                   9823: being set.
                   9824: 
                   9825: =back
                   9826: 
1.394     bowersj2 9827: =head1 OVERVIEW
1.191     harris41 9828: 
1.394     bowersj2 9829: lonnet provides subroutines which interact with the
                   9830: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9831: about classes, users, and resources.
1.243     albertel 9832: 
                   9833: For many of these objects you can also use this to store data about
                   9834: them or modify them in various ways.
1.191     harris41 9835: 
1.394     bowersj2 9836: =head2 Symbs
1.191     harris41 9837: 
1.394     bowersj2 9838: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9839: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9840: map, the resource number of the resource in the map, and the URL of
                   9841: the resource itself. The latter is somewhat redundant, but might help
                   9842: if maps change.
                   9843: 
                   9844: An example is
                   9845: 
                   9846:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9847: 
                   9848: The respective map entry is
                   9849: 
                   9850:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9851:   title="Problem 2">
                   9852:  </resource>
                   9853: 
                   9854: Symbs are used by the random number generator, as well as to store and
                   9855: restore data specific to a certain instance of for example a problem.
                   9856: 
                   9857: =head2 Storing And Retrieving Data
                   9858: 
                   9859: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9860: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9861: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9862: is is the non-critical message twin of cstore. These functions are for
                   9863: handlers to store a perl hash to a user's permanent data space in an
                   9864: easy manner, and to retrieve it again on another call. It is expected
                   9865: that a handler would use this once at the beginning to retrieve data,
                   9866: and then again once at the end to send only the new data back.
                   9867: 
                   9868: The data is stored in the user's data directory on the user's
                   9869: homeserver under the ID of the course.
                   9870: 
                   9871: The hash that is returned by restore will have all of the previous
                   9872: value for all of the elements of the hash.
                   9873: 
                   9874: Example:
                   9875: 
                   9876:  #creating a hash
                   9877:  my %hash;
                   9878:  $hash{'foo'}='bar';
                   9879: 
                   9880:  #storing it
                   9881:  &Apache::lonnet::cstore(\%hash);
                   9882: 
                   9883:  #changing a value
                   9884:  $hash{'foo'}='notbar';
                   9885: 
                   9886:  #adding a new value
                   9887:  $hash{'bar'}='foo';
                   9888:  &Apache::lonnet::cstore(\%hash);
                   9889: 
                   9890:  #retrieving the hash
                   9891:  my %history=&Apache::lonnet::restore();
                   9892: 
                   9893:  #print the hash
                   9894:  foreach my $key (sort(keys(%history))) {
                   9895:    print("\%history{$key} = $history{$key}");
                   9896:  }
                   9897: 
                   9898: Will print out:
1.191     harris41 9899: 
1.394     bowersj2 9900:  %history{1:foo} = bar
                   9901:  %history{1:keys} = foo:timestamp
                   9902:  %history{1:timestamp} = 990455579
                   9903:  %history{2:bar} = foo
                   9904:  %history{2:foo} = notbar
                   9905:  %history{2:keys} = foo:bar:timestamp
                   9906:  %history{2:timestamp} = 990455580
                   9907:  %history{bar} = foo
                   9908:  %history{foo} = notbar
                   9909:  %history{timestamp} = 990455580
                   9910:  %history{version} = 2
                   9911: 
                   9912: Note that the special hash entries C<keys>, C<version> and
                   9913: C<timestamp> were added to the hash. C<version> will be equal to the
                   9914: total number of versions of the data that have been stored. The
                   9915: C<timestamp> attribute will be the UNIX time the hash was
                   9916: stored. C<keys> is available in every historical section to list which
                   9917: keys were added or changed at a specific historical revision of a
                   9918: hash.
                   9919: 
                   9920: B<Warning>: do not store the hash that restore returns directly. This
                   9921: will cause a mess since it will restore the historical keys as if the
                   9922: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9923: 
1.394     bowersj2 9924: Calling convention:
1.191     harris41 9925: 
1.394     bowersj2 9926:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9927:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9928: 
1.394     bowersj2 9929: For more detailed information, see lonnet specific documentation.
1.191     harris41 9930: 
1.394     bowersj2 9931: =head1 RETURN MESSAGES
1.191     harris41 9932: 
1.394     bowersj2 9933: =over 4
1.191     harris41 9934: 
1.394     bowersj2 9935: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9936: 
1.394     bowersj2 9937: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9938: when the connection is brought back up
1.191     harris41 9939: 
1.394     bowersj2 9940: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9941: for later delivery
1.191     harris41 9942: 
1.967     bisitz   9943: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9944: 
1.394     bowersj2 9945: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9946: that was requested
1.191     harris41 9947: 
1.243     albertel 9948: =back
1.191     harris41 9949: 
1.243     albertel 9950: =head1 PUBLIC SUBROUTINES
1.191     harris41 9951: 
1.243     albertel 9952: =head2 Session Environment Functions
1.191     harris41 9953: 
1.243     albertel 9954: =over 4
1.191     harris41 9955: 
1.394     bowersj2 9956: =item * 
                   9957: X<appenv()>
1.949     raeburn  9958: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9959: the user envirnoment file, and will be restored for each access this
1.620     albertel 9960: user makes during this session, also modifies the %env for the current
1.949     raeburn  9961: process. Optional rolesarrayref - if defined contains a reference to an array
                   9962: of roles which are exempt from the restriction on modifying user.role entries 
                   9963: in the user's environment.db and in %env.    
1.191     harris41 9964: 
                   9965: =item *
1.394     bowersj2 9966: X<delenv()>
1.987     raeburn  9967: B<delenv($delthis,$regexp)>: removes all items from the session
                   9968: environment file that begin with $delthis. If the 
                   9969: optional second arg - $regexp - is true, $delthis is treated as a 
                   9970: regular expression, otherwise \Q$delthis\E is used. 
                   9971: The values are also deleted from the current processes %env.
1.191     harris41 9972: 
1.795     albertel 9973: =item * get_env_multiple($name) 
                   9974: 
                   9975: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9976: values may be defined and end up as an array ref.
                   9977: 
                   9978: returns an array of values
                   9979: 
1.243     albertel 9980: =back
                   9981: 
                   9982: =head2 User Information
1.191     harris41 9983: 
1.243     albertel 9984: =over 4
1.191     harris41 9985: 
                   9986: =item *
1.394     bowersj2 9987: X<queryauthenticate()>
                   9988: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9989: authentication scheme
                   9990: 
                   9991: =item *
1.394     bowersj2 9992: X<authenticate()>
                   9993: B<authenticate($uname,$upass,$udom)>: try to
                   9994: authenticate user from domain's lib servers (first use the current
                   9995: one). C<$upass> should be the users password.
1.191     harris41 9996: 
                   9997: =item *
1.394     bowersj2 9998: X<homeserver()>
                   9999: B<homeserver($uname,$udom)>: find the server which has
                   10000: the user's directory and files (there must be only one), this caches
                   10001: the answer, and also caches if there is a borken connection.
1.191     harris41 10002: 
                   10003: =item *
1.394     bowersj2 10004: X<idget()>
                   10005: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10006: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10007: username, and only 1 username per ID in a specific domain) (returns
                   10008: hash: id=>name,id=>name)
1.191     harris41 10009: 
                   10010: =item *
1.394     bowersj2 10011: X<idrget()>
                   10012: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10013: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10014: 
                   10015: =item *
1.394     bowersj2 10016: X<idput()>
                   10017: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10018: 
                   10019: =item *
1.394     bowersj2 10020: X<rolesinit()>
                   10021: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10022: 
                   10023: =item *
1.551     albertel 10024: X<getsection()>
                   10025: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10026: course $cname, return section name/number or '' for "not in course"
                   10027: and '-1' for "no section"
                   10028: 
                   10029: =item *
1.394     bowersj2 10030: X<userenvironment()>
                   10031: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10032: passed in @what from the requested user's environment, returns a hash
                   10033: 
1.858     raeburn  10034: =item * 
                   10035: X<userlog_query()>
1.859     albertel 10036: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10037: activity.log file. %filters defines filters applied when parsing the
                   10038: log file. These can be start or end timestamps, or the type of action
                   10039: - log to look for Login or Logout events, check for Checkin or
                   10040: Checkout, role for role selection. The response is in the form
                   10041: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10042: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10043: 
1.243     albertel 10044: =back
                   10045: 
                   10046: =head2 User Roles
                   10047: 
                   10048: =over 4
                   10049: 
                   10050: =item *
                   10051: 
1.810     raeburn  10052: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10053:  F: full access
                   10054:  U,I,K: authentication modes (cxx only)
                   10055:  '': forbidden
                   10056:  1: user needs to choose course
                   10057:  2: browse allowed
1.766     albertel 10058:  A: passphrase authentication needed
1.243     albertel 10059: 
                   10060: =item *
                   10061: 
                   10062: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10063: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10064: and course level
                   10065: 
                   10066: =item *
                   10067: 
1.988     raeburn  10068: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10069: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10070: $type is Course (default) or Community.
1.988     raeburn  10071: If $forcedefault evaluates to true, text returned will be default 
                   10072: text for $type. Otherwise, if this is a course, the text returned 
                   10073: will be a custom name for the role (if defined in the course's 
                   10074: environment).  If no custom name is defined the default is returned.
                   10075:    
1.832     raeburn  10076: =item *
                   10077: 
1.935     raeburn  10078: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10079: All arguments are optional. Returns a hash of a roles, either for
                   10080: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10081: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10082: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10083: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10084: For each key, value is set to colon-separated start and end times for
                   10085: the role.  If no username and domain are specified, will default to
1.934     raeburn  10086: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10087: of role statuses (active, future or previous), roles 
                   10088: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10089: to restrict the list of roles reported. If no array ref is 
                   10090: provided for types, will default to return only active roles.
1.834     albertel 10091: 
1.243     albertel 10092: =back
                   10093: 
                   10094: =head2 User Modification
                   10095: 
                   10096: =over 4
                   10097: 
                   10098: =item *
                   10099: 
1.957     raeburn  10100: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10101: user for the level given by URL.  Optional start and end dates (leave empty
                   10102: string or zero for "no date")
1.191     harris41 10103: 
                   10104: =item *
                   10105: 
1.243     albertel 10106: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10107: change a users, password, possible return values are: ok,
                   10108: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10109: refused
1.191     harris41 10110: 
                   10111: =item *
                   10112: 
1.243     albertel 10113: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10114: 
                   10115: =item *
                   10116: 
1.963     raeburn  10117: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   10118:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 10119: modify user
1.191     harris41 10120: 
                   10121: =item *
                   10122: 
1.286     matthew  10123: modifystudent
                   10124: 
1.957     raeburn  10125: modify a student's enrollment and identification information.
1.286     matthew  10126: The course id is resolved based on the current users environment.  
                   10127: This means the envoking user must be a course coordinator or otherwise
                   10128: associated with a course.
                   10129: 
1.297     matthew  10130: This call is essentially a wrapper for lonnet::modifyuser and
                   10131: lonnet::modify_student_enrollment
1.286     matthew  10132: 
                   10133: Inputs: 
                   10134: 
                   10135: =over 4
                   10136: 
1.957     raeburn  10137: =item B<$udom> Student's loncapa domain
1.286     matthew  10138: 
1.957     raeburn  10139: =item B<$uname> Student's loncapa login name
1.286     matthew  10140: 
1.964     bisitz   10141: =item B<$uid> Student/Employee ID
1.286     matthew  10142: 
1.957     raeburn  10143: =item B<$umode> Student's authentication mode
1.286     matthew  10144: 
1.957     raeburn  10145: =item B<$upass> Student's password
1.286     matthew  10146: 
1.957     raeburn  10147: =item B<$first> Student's first name
1.286     matthew  10148: 
1.957     raeburn  10149: =item B<$middle> Student's middle name
1.286     matthew  10150: 
1.957     raeburn  10151: =item B<$last> Student's last name
1.286     matthew  10152: 
1.957     raeburn  10153: =item B<$gene> Student's generation
1.286     matthew  10154: 
1.957     raeburn  10155: =item B<$usec> Student's section in course
1.286     matthew  10156: 
                   10157: =item B<$end> Unix time of the roles expiration
                   10158: 
                   10159: =item B<$start> Unix time of the roles start date
                   10160: 
                   10161: =item B<$forceid> If defined, allow $uid to be changed
                   10162: 
                   10163: =item B<$desiredhome> server to use as home server for student
                   10164: 
1.957     raeburn  10165: =item B<$email> Student's permanent e-mail address
                   10166: 
                   10167: =item B<$type> Type of enrollment (auto or manual)
                   10168: 
1.963     raeburn  10169: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10170: 
                   10171: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10172: 
1.963     raeburn  10173: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10174: 
1.963     raeburn  10175: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10176: 
1.963     raeburn  10177: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10178: 
1.286     matthew  10179: =back
1.297     matthew  10180: 
                   10181: =item *
                   10182: 
                   10183: modify_student_enrollment
                   10184: 
                   10185: Change a students enrollment status in a class.  The environment variable
                   10186: 'role.request.course' must be defined for this function to proceed.
                   10187: 
                   10188: Inputs:
                   10189: 
                   10190: =over 4
                   10191: 
                   10192: =item $udom, students domain
                   10193: 
                   10194: =item $uname, students name
                   10195: 
                   10196: =item $uid, students user id
                   10197: 
                   10198: =item $first, students first name
                   10199: 
                   10200: =item $middle
                   10201: 
                   10202: =item $last
                   10203: 
                   10204: =item $gene
                   10205: 
                   10206: =item $usec
                   10207: 
                   10208: =item $end
                   10209: 
                   10210: =item $start
                   10211: 
1.957     raeburn  10212: =item $type
                   10213: 
                   10214: =item $locktype
                   10215: 
                   10216: =item $cid
                   10217: 
                   10218: =item $selfenroll
                   10219: 
                   10220: =item $context
                   10221: 
1.297     matthew  10222: =back
                   10223: 
1.191     harris41 10224: 
                   10225: =item *
                   10226: 
1.243     albertel 10227: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10228: custom role; give a custom role to a user for the level given by URL.  Specify
                   10229: name and domain of role author, and role name
1.191     harris41 10230: 
                   10231: =item *
                   10232: 
1.243     albertel 10233: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10234: 
                   10235: =item *
                   10236: 
1.243     albertel 10237: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10238: 
                   10239: =back
                   10240: 
                   10241: =head2 Course Infomation
                   10242: 
                   10243: =over 4
1.191     harris41 10244: 
                   10245: =item *
                   10246: 
1.631     albertel 10247: coursedescription($courseid) : returns a hash of information about the
                   10248: specified course id, including all environment settings for the
                   10249: course, the description of the course will be in the hash under the
                   10250: key 'description'
1.191     harris41 10251: 
                   10252: =item *
                   10253: 
1.624     albertel 10254: resdata($name,$domain,$type,@which) : request for current parameter
                   10255: setting for a specific $type, where $type is either 'course' or 'user',
                   10256: @what should be a list of parameters to ask about. This routine caches
                   10257: answers for 5 minutes.
1.243     albertel 10258: 
1.877     foxr     10259: =item *
                   10260: 
                   10261: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10262: data base, returning a hash that is keyed by the resource name and has
                   10263: values that are the resource value.  I believe that the timestamps and
                   10264: versions are also returned.
                   10265: 
                   10266: 
1.243     albertel 10267: =back
                   10268: 
                   10269: =head2 Course Modification
                   10270: 
                   10271: =over 4
1.191     harris41 10272: 
                   10273: =item *
                   10274: 
1.243     albertel 10275: writecoursepref($courseid,%prefs) : write preferences (environment
                   10276: database) for a course
1.191     harris41 10277: 
                   10278: =item *
                   10279: 
1.1011    raeburn  10280: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10281: 
                   10282: =item *
                   10283: 
1.1038    raeburn  10284: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10285: 
                   10286: =back
                   10287: 
                   10288: =head2 Resource Subroutines
                   10289: 
                   10290: =over 4
1.191     harris41 10291: 
                   10292: =item *
                   10293: 
1.243     albertel 10294: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10295: 
                   10296: =item *
                   10297: 
1.243     albertel 10298: repcopy($filename) : subscribes to the requested file, and attempts to
                   10299: replicate from the owning library server, Might return
1.607     raeburn  10300: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10301: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10302: resource. Expects the local filesystem pathname
                   10303: (/home/httpd/html/res/....)
                   10304: 
                   10305: =back
                   10306: 
                   10307: =head2 Resource Information
                   10308: 
                   10309: =over 4
1.191     harris41 10310: 
                   10311: =item *
                   10312: 
1.243     albertel 10313: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10314: a vairety of different possible values, $varname should be a request
                   10315: string, and the other parameters can be used to specify who and what
                   10316: one is asking about.
                   10317: 
                   10318: Possible values for $varname are environment.lastname (or other item
                   10319: from the envirnment hash), user.name (or someother aspect about the
                   10320: user), resource.0.maxtries (or some other part and parameter of a
                   10321: resource)
1.204     albertel 10322: 
                   10323: =item *
                   10324: 
1.243     albertel 10325: directcondval($number) : get current value of a condition; reads from a state
                   10326: string
1.204     albertel 10327: 
                   10328: =item *
                   10329: 
1.243     albertel 10330: condval($condidx) : value of condition index based on state
1.204     albertel 10331: 
                   10332: =item *
                   10333: 
1.243     albertel 10334: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10335: resource's metadata, $what should be either a specific key, or either
                   10336: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10337: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10338: 
                   10339: this function automatically caches all requests
1.191     harris41 10340: 
                   10341: =item *
                   10342: 
1.243     albertel 10343: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10344: network of library servers; returns file handle of where SQL and regex results
                   10345: will be stored for query
1.191     harris41 10346: 
                   10347: =item *
                   10348: 
1.243     albertel 10349: symbread($filename) : return symbolic list entry (filename argument optional);
                   10350: returns the data handle
1.191     harris41 10351: 
                   10352: =item *
                   10353: 
1.243     albertel 10354: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10355: a possible symb for the URL in $thisfn, and if is an encryypted
                   10356: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10357: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10358: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10359: 
1.191     harris41 10360: 
                   10361: =item *
                   10362: 
1.243     albertel 10363: symbclean($symb) : removes versions numbers from a symb, returns the
                   10364: cleaned symb
1.191     harris41 10365: 
                   10366: =item *
                   10367: 
1.243     albertel 10368: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10369: course map, user must be in a course for it to work.
1.191     harris41 10370: 
                   10371: =item *
                   10372: 
1.243     albertel 10373: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10374: 
                   10375: =item *
                   10376: 
1.243     albertel 10377: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10378: a random seed, all arguments are optional, if they aren't sent it uses the
                   10379: environment to derive them. Note: if symb isn't sent and it can't get one
                   10380: from &symbread it will use the current time as its return value
1.191     harris41 10381: 
                   10382: =item *
                   10383: 
1.243     albertel 10384: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10385: unfakeable, receipt
1.191     harris41 10386: 
                   10387: =item *
                   10388: 
1.620     albertel 10389: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10390: 
                   10391: =item *
                   10392: 
1.243     albertel 10393: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10394: 
                   10395: =item *
                   10396: 
1.243     albertel 10397: 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 10398: 
                   10399: =item *
                   10400: 
1.243     albertel 10401: 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 10402: 
                   10403: =item *
                   10404: 
1.243     albertel 10405: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10406: 
                   10407: =item *
                   10408: 
1.243     albertel 10409: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10410: forcing spreadsheet to reevaluate the resource scores next time.
                   10411: 
                   10412: =back
                   10413: 
                   10414: =head2 Storing/Retreiving Data
                   10415: 
                   10416: =over 4
1.191     harris41 10417: 
                   10418: =item *
                   10419: 
1.243     albertel 10420: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10421: for this url; hashref needs to be given and should be a \%hashname; the
                   10422: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10423: be derived from the env
1.191     harris41 10424: 
                   10425: =item *
                   10426: 
1.243     albertel 10427: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10428: uses critical subroutine
1.191     harris41 10429: 
                   10430: =item *
                   10431: 
1.243     albertel 10432: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10433: all args are optional
1.191     harris41 10434: 
                   10435: =item *
                   10436: 
1.717     albertel 10437: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10438: dumps the complete (or key matching regexp) namespace into a hash
                   10439: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10440: normally &store()ed into
                   10441: 
                   10442: $range should be either an integer '100' (give me the first 100
                   10443:                                            matching records)
                   10444:               or be  two integers sperated by a - with no spaces
                   10445:                  '30-50' (give me the 30th through the 50th matching
                   10446:                           records)
                   10447: 
                   10448: 
                   10449: =item *
                   10450: 
                   10451: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10452: replaces a &store() version of data with a replacement set of data
                   10453: for a particular resource in a namespace passed in the $storehash hash 
                   10454: reference
                   10455: 
                   10456: =item *
                   10457: 
1.243     albertel 10458: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10459: works very similar to store/cstore, but all data is stored in a
                   10460: temporary location and can be reset using tmpreset, $storehash should
                   10461: be a hash reference, returns nothing on success
1.191     harris41 10462: 
                   10463: =item *
                   10464: 
1.243     albertel 10465: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10466: similar to restore, but all data is stored in a temporary location and
                   10467: can be reset using tmpreset. Returns a hash of values on success,
                   10468: error string otherwise.
1.191     harris41 10469: 
                   10470: =item *
                   10471: 
1.243     albertel 10472: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10473: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10474: 
                   10475: =item *
                   10476: 
1.243     albertel 10477: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10478: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10479: 
                   10480: =item *
                   10481: 
1.243     albertel 10482: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10483: namesp ($udom and $uname are optional)
1.191     harris41 10484: 
                   10485: =item *
                   10486: 
1.702     albertel 10487: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10488: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10489: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10490: 
1.702     albertel 10491: $range should be either an integer '100' (give me the first 100
                   10492:                                            matching records)
                   10493:               or be  two integers sperated by a - with no spaces
                   10494:                  '30-50' (give me the 30th through the 50th matching
                   10495:                           records)
1.449     matthew  10496: =item *
                   10497: 
                   10498: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10499: $store can be a scalar, an array reference, or if the amount to be 
                   10500: incremented is > 1, a hash reference.
                   10501: 
                   10502: ($udom and $uname are optional)
1.191     harris41 10503: 
                   10504: =item *
                   10505: 
1.243     albertel 10506: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10507: ($udom and $uname are optional)
1.191     harris41 10508: 
                   10509: =item *
                   10510: 
1.243     albertel 10511: cput($namespace,$storehash,$udom,$uname) : critical put
                   10512: ($udom and $uname are optional)
1.191     harris41 10513: 
                   10514: =item *
                   10515: 
1.748     albertel 10516: newput($namespace,$storehash,$udom,$uname) :
                   10517: 
                   10518: Attempts to store the items in the $storehash, but only if they don't
                   10519: currently exist, if this succeeds you can be certain that you have 
                   10520: successfully created a new key value pair in the $namespace db.
                   10521: 
                   10522: 
                   10523: Args:
                   10524:  $namespace: name of database to store values to
                   10525:  $storehash: hashref to store to the db
                   10526:  $udom: (optional) domain of user containing the db
                   10527:  $uname: (optional) name of user caontaining the db
                   10528: 
                   10529: Returns:
                   10530:  'ok' -> succeeded in storing all keys of $storehash
                   10531:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   10532:                         least <key> already existed in the db (other
                   10533:                         requested keys may also already exist)
1.967     bisitz   10534:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 10535:  'con_lost' -> unable to contact request server
                   10536:  'refused' -> action was not allowed by remote machine
                   10537: 
                   10538: 
                   10539: =item *
                   10540: 
1.243     albertel 10541: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10542: reference filled in from namesp (encrypts the return communication)
                   10543: ($udom and $uname are optional)
1.191     harris41 10544: 
                   10545: =item *
                   10546: 
1.243     albertel 10547: log($udom,$name,$home,$message) : write to permanent log for user; use
                   10548: critical subroutine
                   10549: 
1.806     raeburn  10550: =item *
                   10551: 
1.860     raeburn  10552: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   10553: array reference filled in from namespace found in domain level on either
                   10554: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  10555: 
                   10556: =item *
                   10557: 
1.860     raeburn  10558: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   10559: domain level either on specified domain server ($uhome) or primary domain 
                   10560: server ($udom and $uhome are optional)
1.806     raeburn  10561: 
1.943     raeburn  10562: =item * 
                   10563: 
                   10564: get_domain_defaults($target_domain) : returns hash with defaults for
                   10565: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   10566: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   10567: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   10568: Values are retrieved from cache (if current), or from domain's configuration.db
                   10569: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   10570: or lonTabs/domain.tab. 
                   10571: 
                   10572: %domdefaults = &get_auth_defaults($target_domain);
                   10573: 
1.243     albertel 10574: =back
                   10575: 
                   10576: =head2 Network Status Functions
                   10577: 
                   10578: =over 4
1.191     harris41 10579: 
                   10580: =item *
                   10581: 
                   10582: dirlist($uri) : return directory list based on URI
                   10583: 
                   10584: =item *
                   10585: 
1.243     albertel 10586: spareserver() : find server with least workload from spare.tab
                   10587: 
1.986     foxr     10588: 
                   10589: =item *
                   10590: 
                   10591: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10592: if there is no corresponding loncapa host.
                   10593: 
1.243     albertel 10594: =back
                   10595: 
1.986     foxr     10596: 
1.243     albertel 10597: =head2 Apache Request
                   10598: 
                   10599: =over 4
1.191     harris41 10600: 
                   10601: =item *
                   10602: 
1.243     albertel 10603: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10604: localhost, posts hash
                   10605: 
                   10606: =back
                   10607: 
                   10608: =head2 Data to String to Data
                   10609: 
                   10610: =over 4
1.191     harris41 10611: 
                   10612: =item *
                   10613: 
1.243     albertel 10614: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10615: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10616: 
                   10617: =item *
                   10618: 
1.243     albertel 10619: hashref2str($hashref) : convert a hashref into a string complete with
                   10620: escaping and '=' and '&' separators, supports elements that are
                   10621: arrayrefs and hashrefs
1.191     harris41 10622: 
                   10623: =item *
                   10624: 
1.243     albertel 10625: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10626: with escaping and '&' separators, supports elements that are arrayrefs
                   10627: and hashrefs
1.191     harris41 10628: 
                   10629: =item *
                   10630: 
1.243     albertel 10631: str2hash($string) : convert string to hash using unescaping and
                   10632: splitting on '=' and '&', supports elements that are arrayrefs and
                   10633: hashrefs
1.191     harris41 10634: 
                   10635: =item *
                   10636: 
1.243     albertel 10637: str2array($string) : convert string to hash using unescaping and
                   10638: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10639: 
                   10640: =back
                   10641: 
                   10642: =head2 Logging Routines
                   10643: 
                   10644: =over 4
                   10645: 
                   10646: These routines allow one to make log messages in the lonnet.log and
                   10647: lonnet.perm logfiles.
1.191     harris41 10648: 
                   10649: =item *
                   10650: 
1.243     albertel 10651: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10652: 
                   10653: =item *
                   10654: 
1.243     albertel 10655: logthis() : append message to the normal lonnet.log file, it gets
                   10656: preiodically rolled over and deleted.
1.191     harris41 10657: 
                   10658: =item *
                   10659: 
1.243     albertel 10660: logperm() : append a permanent message to lonnet.perm.log, this log
                   10661: file never gets deleted by any automated portion of the system, only
                   10662: messages of critical importance should go in here.
                   10663: 
                   10664: =back
                   10665: 
                   10666: =head2 General File Helper Routines
                   10667: 
                   10668: =over 4
1.191     harris41 10669: 
                   10670: =item *
                   10671: 
1.481     raeburn  10672: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10673: (a) files in /uploaded
                   10674:   (i) If a local copy of the file exists - 
                   10675:       compares modification date of local copy with last-modified date for 
                   10676:       definitive version stored on home server for course. If local copy is 
                   10677:       stale, requests a new version from the home server and stores it. 
                   10678:       If the original has been removed from the home server, then local copy 
                   10679:       is unlinked.
                   10680:   (ii) If local copy does not exist -
                   10681:       requests the file from the home server and stores it. 
                   10682:   
                   10683:   If $caller is 'uploadrep':  
                   10684:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10685:     for request for files originally uploaded via DOCS. 
                   10686:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10687:   
                   10688:   Otherwise:
                   10689:      This indicates a call from the content generation phase of the request.
                   10690:      -  returns the entire contents of the file or -1.
                   10691:      
                   10692: (b) files in /res
                   10693:    - returns the entire contents of a file or -1; 
                   10694:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10695: 
1.712     albertel 10696: 
                   10697: =item *
                   10698: 
                   10699: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10700:                   reference
                   10701: 
                   10702: returns either a stat() list of data about the file or an empty list
                   10703: if the file doesn't exist or couldn't find out about it (connection
                   10704: problems or user unknown)
                   10705: 
1.191     harris41 10706: =item *
                   10707: 
1.243     albertel 10708: filelocation($dir,$file) : returns file system location of a file
                   10709: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10710: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10711: and a file of ../bob will become /a/bob)
1.191     harris41 10712: 
                   10713: =item *
                   10714: 
                   10715: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10716: filelocation except for hrefs
                   10717: 
                   10718: =item *
                   10719: 
                   10720: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10721: 
1.243     albertel 10722: =back
                   10723: 
1.608     albertel 10724: =head2 Usererfile file routines (/uploaded*)
                   10725: 
                   10726: =over 4
                   10727: 
                   10728: =item *
                   10729: 
                   10730: userfileupload(): main rotine for putting a file in a user or course's
                   10731:                   filespace, arguments are,
                   10732: 
1.620     albertel 10733:  formname - required - this is the name of the element in $env where the
1.608     albertel 10734:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10735:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10736:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10737:  coursedoc - if true, store the file in the course of the active role
                   10738:              of the current user
                   10739:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10740:          if undefined, it will be placed in "unknown"
                   10741: 
                   10742:  (This routine calls clean_filename() to remove any dangerous
                   10743:  characters from the filename, and then calls finuserfileupload() to
                   10744:  complete the transaction)
                   10745: 
                   10746:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10747:  and /adm/notfound.html if unsuccessful
                   10748: 
                   10749: =item *
                   10750: 
                   10751: clean_filename(): routine for cleaing a filename up for storage in
                   10752:                  userfile space, argument is:
                   10753: 
                   10754:  filename - proposed filename
                   10755: 
                   10756: returns: the new clean filename
                   10757: 
                   10758: =item *
                   10759: 
                   10760: finishuserfileupload(): routine that creaes and sends the file to
                   10761: userspace, probably shouldn't be called directly
                   10762: 
                   10763:   docuname: username or courseid of destination for the file
                   10764:   docudom: domain of user/course of destination for the file
                   10765:   formname: same as for userfileupload()
                   10766:   fname: filename (inculding subdirectories) for the file
                   10767: 
                   10768:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10769:  and /adm/notfound.html if unsuccessful
                   10770: 
                   10771: =item *
                   10772: 
                   10773: renameuserfile(): renames an existing userfile to a new name
                   10774: 
                   10775:   Args:
                   10776:    docuname: username or courseid of destination for the file
                   10777:    docudom: domain of user/course of destination for the file
                   10778:    old: current file name (including any subdirs under userfiles)
                   10779:    new: desired file name (including any subdirs under userfiles)
                   10780: 
                   10781: =item *
                   10782: 
                   10783: mkdiruserfile(): creates a directory is a userfiles dir
                   10784: 
                   10785:   Args:
                   10786:    docuname: username or courseid of destination for the file
                   10787:    docudom: domain of user/course of destination for the file
                   10788:    dir: dir to create (including any subdirs under userfiles)
                   10789: 
                   10790: =item *
                   10791: 
                   10792: removeuserfile(): removes a file that exists in userfiles
                   10793: 
                   10794:   Args:
                   10795:    docuname: username or courseid of destination for the file
                   10796:    docudom: domain of user/course of destination for the file
                   10797:    fname: filname to delete (including any subdirs under userfiles)
                   10798: 
                   10799: =item *
                   10800: 
                   10801: removeuploadedurl(): convience function for removeuserfile()
                   10802: 
                   10803:   Args:
                   10804:    url:  a full /uploaded/... url to delete
                   10805: 
1.747     albertel 10806: =item * 
                   10807: 
                   10808: get_portfile_permissions():
                   10809:   Args:
                   10810:     domain: domain of user or course contain the portfolio files
                   10811:     user: name of user or num of course contain the portfolio files
                   10812:   Returns:
                   10813:     hashref of a dump of the proper file_permissions.db
                   10814:    
                   10815: 
                   10816: =item * 
                   10817: 
                   10818: get_access_controls():
                   10819: 
                   10820: Args:
                   10821:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10822:   group: (optional) the group you want the files associated with
                   10823:   file: (optional) the file you want access info on
                   10824: 
                   10825: Returns:
1.749     raeburn  10826:     a hash (keys are file names) of hashes containing
                   10827:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10828:         values are XML containing access control settings (see below) 
1.747     albertel 10829: 
                   10830: Internal notes:
                   10831: 
1.749     raeburn  10832:  access controls are stored in file_permissions.db as key=value pairs.
                   10833:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10834:         where scope -> public,guest,course,group,domains or users.
                   10835:               end -> UNIX time for end of access (0 -> no end date)
                   10836:               start -> UNIX time for start of access
                   10837: 
                   10838:     value -> XML description of access control
                   10839:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10840:             <start></start>
                   10841:             <end></end>
                   10842: 
                   10843:             <password></password>  for scope type = guest
                   10844: 
                   10845:             <domain></domain>     for scope type = course or group
                   10846:             <number></number>
                   10847:             <roles id="">
                   10848:              <role></role>
                   10849:              <access></access>
                   10850:              <section></section>
                   10851:              <group></group>
                   10852:             </roles>
                   10853: 
                   10854:             <dom></dom>         for scope type = domains
                   10855: 
                   10856:             <users>             for scope type = users
                   10857:              <user>
                   10858:               <uname></uname>
                   10859:               <udom></udom>
                   10860:              </user>
                   10861:             </users>
                   10862:            </scope> 
                   10863:               
                   10864:  Access data is also aggregated for each file in an additional key=value pair:
                   10865:  key -> path to file/file_name\0accesscontrol 
                   10866:  value -> reference to hash
                   10867:           hash contains key = value pairs
                   10868:           where key = uniqueID:scope_end_start
                   10869:                 value = UNIX time record was last updated
                   10870: 
                   10871:           Used to improve speed of look-ups of access controls for each file.  
                   10872:  
                   10873:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10874: 
                   10875: modify_access_controls():
                   10876: 
                   10877: Modifies access controls for a portfolio file
                   10878: Args
                   10879: 1. file name
                   10880: 2. reference to hash of required changes,
                   10881: 3. domain
                   10882: 4. username
                   10883:   where domain,username are the domain of the portfolio owner 
                   10884:   (either a user or a course) 
                   10885: 
                   10886: Returns:
                   10887: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10888: 2. result of deletions ('ok' or 'error', with error message).
                   10889: 3. reference to hash of any new or updated access controls.
                   10890: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10891:    key = integer (inbound ID)
                   10892:    value = uniqueID  
1.747     albertel 10893: 
1.608     albertel 10894: =back
                   10895: 
1.243     albertel 10896: =head2 HTTP Helper Routines
                   10897: 
                   10898: =over 4
                   10899: 
1.191     harris41 10900: =item *
                   10901: 
                   10902: escape() : unpack non-word characters into CGI-compatible hex codes
                   10903: 
                   10904: =item *
                   10905: 
                   10906: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10907: 
1.243     albertel 10908: =back
                   10909: 
                   10910: =head1 PRIVATE SUBROUTINES
                   10911: 
                   10912: =head2 Underlying communication routines (Shouldn't call)
                   10913: 
                   10914: =over 4
                   10915: 
                   10916: =item *
                   10917: 
                   10918: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10919: 
                   10920: =item *
                   10921: 
                   10922: reply() : uses subreply to send a message to remote machine, logs all failures
                   10923: 
                   10924: =item *
                   10925: 
                   10926: critical() : passes a critical message to another server; if cannot
                   10927: get through then place message in connection buffer directory and
                   10928: returns con_delayed, if incapable of saving message, returns
                   10929: con_failed
                   10930: 
                   10931: =item *
                   10932: 
                   10933: reconlonc() : tries to reconnect lonc client processes.
                   10934: 
                   10935: =back
                   10936: 
                   10937: =head2 Resource Access Logging
                   10938: 
                   10939: =over 4
                   10940: 
                   10941: =item *
                   10942: 
                   10943: flushcourselogs() : flush (save) buffer logs and access logs
                   10944: 
                   10945: =item *
                   10946: 
                   10947: courselog($what) : save message for course in hash
                   10948: 
                   10949: =item *
                   10950: 
                   10951: courseacclog($what) : save message for course using &courselog().  Perform
                   10952: special processing for specific resource types (problems, exams, quizzes, etc).
                   10953: 
1.191     harris41 10954: =item *
                   10955: 
                   10956: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10957: as a PerlChildExitHandler
1.243     albertel 10958: 
                   10959: =back
                   10960: 
                   10961: =head2 Other
                   10962: 
                   10963: =over 4
                   10964: 
                   10965: =item *
                   10966: 
                   10967: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10968: 
                   10969: =back
                   10970: 
                   10971: =cut
1.877     foxr     10972: 

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