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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1169  ! droeschl    4: # $Id: lonnet.pm,v 1.1168 2012/05/18 15:31:40 www 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.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1167    droeschl  100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.550     foxr      105: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.449     matthew   112: 
1.1       albertel  113: # --------------------------------------------------------------------- Logging
1.729     www       114: {
                    115:     my $logid;
                    116:     sub instructor_log {
1.957     raeburn   117: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    118:         if (($cnum eq '') || ($cdom eq '')) {
                    119:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:         }
1.729     www       122: 	$logid++;
1.957     raeburn   123:         my $now = time();
                    124: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       125: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       126: 				    { $id => {
                    127: 					'exe_uname' => $env{'user.name'},
                    128: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   129: 					'exe_time'  => $now,
1.730     www       130: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    131: 					'delflag'   => $delflag,
                    132: 					'logentry'  => $storehash,
                    133: 					'uname'     => $uname,
                    134: 					'udom'      => $udom,
                    135: 				    }
1.957     raeburn   136: 				  },$cdom,$cnum);
1.729     www       137:     }
                    138: }
1.1       albertel  139: 
1.163     harris41  140: sub logtouch {
                    141:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  142:     unless (-e "$execdir/logs/lonnet.log") {	
                    143: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  144: 	close $fh;
                    145:     }
                    146:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    147:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    148: }
                    149: 
1.1       albertel  150: sub logthis {
                    151:     my $message=shift;
                    152:     my $execdir=$perlvar{'lonDaemons'};
                    153:     my $now=time;
                    154:     my $local=localtime($now);
1.448     albertel  155:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      156: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    157: 	print $fh $logstring;
1.448     albertel  158: 	close($fh);
                    159:     }
1.1       albertel  160:     return 1;
                    161: }
                    162: 
                    163: sub logperm {
                    164:     my $message=shift;
                    165:     my $execdir=$perlvar{'lonDaemons'};
                    166:     my $now=time;
                    167:     my $local=localtime($now);
1.448     albertel  168:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    169: 	print $fh "$now:$message:$local\n";
                    170: 	close($fh);
                    171:     }
1.1       albertel  172:     return 1;
                    173: }
                    174: 
1.850     albertel  175: sub create_connection {
1.853     albertel  176:     my ($hostname,$lonid) = @_;
1.851     albertel  177:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  178: 				     Type    => SOCK_STREAM,
                    179: 				     Timeout => 10);
                    180:     return 0 if (!$client);
1.890     albertel  181:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  182:     my $result = <$client>;
                    183:     chomp($result);
                    184:     return 1 if ($result eq 'done');
                    185:     return 0;
                    186: }
                    187: 
1.983     raeburn   188: sub get_server_timezone {
                    189:     my ($cnum,$cdom) = @_;
                    190:     my $home=&homeserver($cnum,$cdom);
                    191:     if ($home ne 'no_host') {
                    192:         my $cachetime = 24*3600;
                    193:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    194:         if (defined($cached)) {
                    195:             return $timezone;
                    196:         } else {
                    197:             my $timezone = &reply('servertimezone',$home);
                    198:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    199:         }
                    200:     }
                    201: }
1.850     albertel  202: 
1.1106    raeburn   203: sub get_server_distarch {
                    204:     my ($lonhost,$ignore_cache) = @_;
                    205:     if (defined($lonhost)) {
                    206:         if (!defined(&hostname($lonhost))) {
                    207:             return;
                    208:         }
                    209:         my $cachetime = 12*3600;
                    210:         if (!$ignore_cache) {
                    211:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    212:             if (defined($cached)) {
                    213:                 return $distarch;
                    214:             }
                    215:         }
                    216:         my $rep = &reply('serverdistarch',$lonhost);
                    217:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    218:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    219:                 $rep eq '') {
                    220:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    221:         }
                    222:     }
                    223:     return;
                    224: }
                    225: 
1.993     raeburn   226: sub get_server_loncaparev {
1.1073    raeburn   227:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   228:     if (defined($lonhost)) {
                    229:         if (!defined(&hostname($lonhost))) {
                    230:             undef($lonhost);
                    231:         }
                    232:     }
                    233:     if (!defined($lonhost)) {
                    234:         if (defined(&domain($dom,'primary'))) {
                    235:             $lonhost=&domain($dom,'primary');
                    236:             if ($lonhost eq 'no_host') {
                    237:                 undef($lonhost);
                    238:             }
                    239:         }
                    240:     }
                    241:     if (defined($lonhost)) {
1.1073    raeburn   242:         my $cachetime = 12*3600;
                    243:         if (!$ignore_cache) {
                    244:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    245:             if (defined($cached)) {
                    246:                 return $loncaparev;
                    247:             }
                    248:         }
                    249:         my ($answer,$loncaparev);
                    250:         my @ids=&current_machine_ids();
                    251:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    252:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   253:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   254:                 $loncaparev = $1;
                    255:             }
                    256:         } else {
                    257:             $answer = &reply('serverloncaparev',$lonhost);
                    258:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    259:                 if ($caller eq 'loncron') {
                    260:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   261:                     $ua->timeout(4);
1.1073    raeburn   262:                     my $protocol = $protocol{$lonhost};
                    263:                     $protocol = 'http' if ($protocol ne 'https');
                    264:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    265:                     my $request=new HTTP::Request('GET',$url);
                    266:                     my $response=$ua->request($request);
                    267:                     unless ($response->is_error()) {
                    268:                         my $content = $response->content;
1.1081    raeburn   269:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   270:                             $loncaparev = $1;
                    271:                         }
                    272:                     }
                    273:                 } else {
                    274:                     $loncaparev = $loncaparevs{$lonhost};
                    275:                 }
1.1081    raeburn   276:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   277:                 $loncaparev = $1;
                    278:             }
1.993     raeburn   279:         }
1.1073    raeburn   280:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   281:     }
                    282: }
                    283: 
1.1074    raeburn   284: sub get_server_homeID {
                    285:     my ($hostname,$ignore_cache,$caller) = @_;
                    286:     unless ($ignore_cache) {
                    287:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    288:         if (defined($cached)) {
                    289:             return $serverhomeID;
                    290:         }
                    291:     }
                    292:     my $cachetime = 12*3600;
                    293:     my $serverhomeID;
                    294:     if ($caller eq 'loncron') { 
                    295:         my @machine_ids = &machine_ids($hostname);
                    296:         foreach my $id (@machine_ids) {
                    297:             my $response = &reply('serverhomeID',$id);
                    298:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    299:                 $serverhomeID = $response;
                    300:                 last;
                    301:             }
                    302:         }
                    303:         if ($serverhomeID eq '') {
                    304:             $serverhomeID = $machine_ids[-1];
                    305:         }
                    306:     } else {
                    307:         $serverhomeID = $serverhomeIDs{$hostname};
                    308:     }
                    309:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    310: }
                    311: 
1.1121    raeburn   312: sub get_remote_globals {
                    313:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   314:     my ($result,%returnhash,%whatneeded);
                    315:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   316:         foreach my $what (sort(keys(%{$whathash}))) {
                    317:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   318:             my ($response,$cached);
1.1121    raeburn   319:             unless ($ignore_cache) {
1.1125    raeburn   320:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   321:             }
                    322:             if (defined($cached)) {
1.1125    raeburn   323:                 $returnhash{$what} = $response;
1.1121    raeburn   324:             } else {
1.1125    raeburn   325:                 $whatneeded{$what} = 1;
1.1121    raeburn   326:             }
                    327:         }
1.1125    raeburn   328:         if (keys(%whatneeded) == 0) {
                    329:             $result = 'ok';
                    330:         } else {
1.1121    raeburn   331:             my $requested = &freeze_escape(\%whatneeded);
                    332:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   333:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    334:                 ($rep eq 'unknown_cmd')) {
                    335:                 $result = $rep;
                    336:             } else {
                    337:                 $result = 'ok';
1.1121    raeburn   338:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   339:                 foreach my $item (@pairs) {
                    340:                     my ($key,$value)=split(/=/,$item,2);
                    341:                     my $what = &unescape($key);
                    342:                     my $hashid = $lonhost.'-'.$what;
                    343:                     $returnhash{$what}=&thaw_unescape($value);
                    344:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   345:                 }
                    346:             }
                    347:         }
                    348:     }
1.1125    raeburn   349:     return ($result,\%returnhash);
1.1121    raeburn   350: }
                    351: 
1.1124    raeburn   352: sub remote_devalidate_cache {
                    353:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   354:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   355:     return $response;
                    356: }
                    357: 
1.1       albertel  358: # -------------------------------------------------- Non-critical communication
                    359: sub subreply {
                    360:     my ($cmd,$server)=@_;
1.838     albertel  361:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      362:     #
                    363:     #  With loncnew process trimming, there's a timing hole between lonc server
                    364:     #  process exit and the master server picking up the listen on the AF_UNIX
                    365:     #  socket.  In that time interval, a lock file will exist:
                    366: 
                    367:     my $lockfile=$peerfile.".lock";
                    368:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    369: 	sleep(1);
                    370:     }
                    371:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      372:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      373:     #
1.550     foxr      374:     #   We'll give the connection a few tries before abandoning it.  If
                    375:     #   connection is not possible, we'll con_lost back to the client.
                    376:     #   
                    377:     my $client;
                    378:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    379: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    380: 				      Type    => SOCK_STREAM,
                    381: 				      Timeout => 10);
1.869     albertel  382: 	if ($client) {
1.550     foxr      383: 	    last;		# Connected!
1.850     albertel  384: 	} else {
1.853     albertel  385: 	    &create_connection(&hostname($server),$server);
1.550     foxr      386: 	}
1.850     albertel  387:         sleep(1);		# Try again later if failed connection.
1.550     foxr      388:     }
                    389:     my $answer;
                    390:     if ($client) {
1.704     albertel  391: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      392: 	$answer=<$client>;
                    393: 	if (!$answer) { $answer="con_lost"; }
                    394: 	chomp($answer);
                    395:     } else {
                    396: 	$answer = 'con_lost';	# Failed connection.
                    397:     }
1.1       albertel  398:     return $answer;
                    399: }
                    400: 
                    401: sub reply {
                    402:     my ($cmd,$server)=@_;
1.838     albertel  403:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  404:     my $answer=subreply($cmd,$server);
1.65      www       405:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  406:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       407:                 " $cmd to $server returned $answer</font>");
                    408:     }
1.1       albertel  409:     return $answer;
                    410: }
                    411: 
                    412: # ----------------------------------------------------------- Send USR1 to lonc
                    413: 
                    414: sub reconlonc {
1.891     albertel  415:     my ($lonid) = @_;
                    416:     my $hostname = &hostname($lonid);
                    417:     if ($lonid) {
                    418: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    419: 	if ($hostname && -e $peerfile) {
                    420: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    421: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    422: 					     Type    => SOCK_STREAM,
                    423: 					     Timeout => 10);
                    424: 	    if ($client) {
                    425: 		print $client ("reset_retries\n");
                    426: 		my $answer=<$client>;
                    427: 		#reset just this one.
                    428: 	    }
                    429: 	}
                    430: 	return;
                    431:     }
                    432: 
1.836     www       433:     &logthis("Trying to reconnect lonc");
1.1       albertel  434:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  435:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  436: 	my $loncpid=<$fh>;
                    437:         chomp($loncpid);
                    438:         if (kill 0 => $loncpid) {
                    439: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    440:             kill USR1 => $loncpid;
                    441:             sleep 1;
1.836     www       442:          } else {
1.12      www       443: 	    &logthis(
1.672     albertel  444:                "<font color=\"blue\">WARNING:".
1.12      www       445:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  446:         }
                    447:     } else {
1.836     www       448: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  449:     }
                    450: }
                    451: 
                    452: # ------------------------------------------------------ Critical communication
1.12      www       453: 
1.1       albertel  454: sub critical {
                    455:     my ($cmd,$server)=@_;
1.838     albertel  456:     unless (&hostname($server)) {
1.672     albertel  457:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       458:                " Critical message to unknown server ($server)</font>");
                    459:         return 'no_such_host';
                    460:     }
1.1       albertel  461:     my $answer=reply($cmd,$server);
                    462:     if ($answer eq 'con_lost') {
                    463: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  464: 	my $answer=reply($cmd,$server);
1.1       albertel  465:         if ($answer eq 'con_lost') {
                    466:             my $now=time;
                    467:             my $middlename=$cmd;
1.5       www       468:             $middlename=substr($middlename,0,16);
1.1       albertel  469:             $middlename=~s/\W//g;
                    470:             my $dfilename=
1.305     www       471:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    472:             $dumpcount++;
1.1       albertel  473:             {
1.448     albertel  474: 		my $dfh;
                    475: 		if (open($dfh,">$dfilename")) {
                    476: 		    print $dfh "$cmd\n"; 
                    477: 		    close($dfh);
                    478: 		}
1.1       albertel  479:             }
                    480:             sleep 2;
                    481:             my $wcmd='';
                    482:             {
1.448     albertel  483: 		my $dfh;
                    484: 		if (open($dfh,"<$dfilename")) {
                    485: 		    $wcmd=<$dfh>; 
                    486: 		    close($dfh);
                    487: 		}
1.1       albertel  488:             }
                    489:             chomp($wcmd);
1.7       www       490:             if ($wcmd eq $cmd) {
1.672     albertel  491: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       492:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  493:                 &logperm("D:$server:$cmd");
                    494: 	        return 'con_delayed';
                    495:             } else {
1.672     albertel  496:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       497:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  498:                 &logperm("F:$server:$cmd");
                    499:                 return 'con_failed';
                    500:             }
                    501:         }
                    502:     }
                    503:     return $answer;
1.405     albertel  504: }
                    505: 
1.755     albertel  506: # ------------------------------------------- check if return value is an error
                    507: 
                    508: sub error {
                    509:     my ($result) = @_;
1.756     albertel  510:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  511: 	if ($2 == 2) { return undef; }
                    512: 	return $1;
                    513:     }
                    514:     return undef;
                    515: }
                    516: 
1.783     albertel  517: sub convert_and_load_session_env {
                    518:     my ($lonidsdir,$handle)=@_;
                    519:     my @profile;
                    520:     {
1.917     albertel  521: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    522: 	if (!$opened) {
1.915     albertel  523: 	    return 0;
                    524: 	}
1.783     albertel  525: 	flock($idf,LOCK_SH);
                    526: 	@profile=<$idf>;
                    527: 	close($idf);
                    528:     }
                    529:     my %temp_env;
                    530:     foreach my $line (@profile) {
1.786     albertel  531: 	if ($line !~ m/=/) {
                    532: 	    return 0;
                    533: 	}
1.783     albertel  534: 	chomp($line);
                    535: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    536: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    537:     }
                    538:     unlink("$lonidsdir/$handle.id");
                    539:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    540: 	    0640)) {
                    541: 	%disk_env = %temp_env;
                    542: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    543: 	untie(%disk_env);
                    544:     }
1.786     albertel  545:     return 1;
1.783     albertel  546: }
                    547: 
1.374     www       548: # ------------------------------------------- Transfer profile into environment
1.780     albertel  549: my $env_loaded;
                    550: sub transfer_profile_to_env {
1.788     albertel  551:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    552:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       553: 
1.720     albertel  554:     if (!defined($lonidsdir)) {
                    555: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    556:     }
                    557:     if (!defined($handle)) {
                    558:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    559:     }
                    560: 
1.786     albertel  561:     my $convert;
                    562:     {
1.917     albertel  563:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    564: 	if (!$opened) {
1.915     albertel  565: 	    return;
                    566: 	}
1.786     albertel  567: 	flock($idf,LOCK_SH);
                    568: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    569: 		&GDBM_READER(),0640)) {
                    570: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    571: 	    untie(%disk_env);
                    572: 	} else {
                    573: 	    $convert = 1;
                    574: 	}
                    575:     }
                    576:     if ($convert) {
                    577: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    578: 	    &logthis("Failed to load session, or convert session.");
                    579: 	}
1.374     www       580:     }
1.783     albertel  581: 
1.786     albertel  582:     my %remove;
1.783     albertel  583:     while ( my $envname = each(%env) ) {
1.433     matthew   584:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    585:             if ($time < time-300) {
1.783     albertel  586:                 $remove{$key}++;
1.433     matthew   587:             }
                    588:         }
                    589:     }
1.783     albertel  590: 
1.619     albertel  591:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  592:     $env_loaded=1;
1.783     albertel  593:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   594:         &delenv($expired_key);
1.374     www       595:     }
1.1       albertel  596: }
                    597: 
1.916     albertel  598: # ---------------------------------------------------- Check for valid session 
                    599: sub check_for_valid_session {
1.1155    raeburn   600:     my ($r,$name) = @_;
1.916     albertel  601:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   602:     if ($name eq '') {
                    603:         $name = 'lonID';
                    604:     }
                    605:     my $lonid=$cookies{$name};
1.916     albertel  606:     return undef if (!$lonid);
                    607: 
                    608:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   609:     my $lonidsdir;
                    610:     if ($name eq 'lonDAV') {
                    611:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    612:     } else {
                    613:         $lonidsdir=$r->dir_config('lonIDsDir');
                    614:     }
1.916     albertel  615:     return undef if (!-e "$lonidsdir/$handle.id");
                    616: 
1.917     albertel  617:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    618:     return undef if (!$opened);
1.916     albertel  619: 
                    620:     flock($idf,LOCK_SH);
                    621:     my %disk_env;
                    622:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    623: 	    &GDBM_READER(),0640)) {
                    624: 	return undef;	
                    625:     }
                    626: 
                    627:     if (!defined($disk_env{'user.name'})
                    628: 	|| !defined($disk_env{'user.domain'})) {
                    629: 	return undef;
                    630:     }
                    631:     return $handle;
                    632: }
                    633: 
1.830     albertel  634: sub timed_flock {
                    635:     my ($file,$lock_type) = @_;
                    636:     my $failed=0;
                    637:     eval {
                    638: 	local $SIG{__DIE__}='DEFAULT';
                    639: 	local $SIG{ALRM}=sub {
                    640: 	    $failed=1;
                    641: 	    die("failed lock");
                    642: 	};
                    643: 	alarm(13);
                    644: 	flock($file,$lock_type);
                    645: 	alarm(0);
                    646:     };
                    647:     if ($failed) {
                    648: 	return undef;
                    649:     } else {
                    650: 	return 1;
                    651:     }
                    652: }
                    653: 
1.5       www       654: # ---------------------------------------------------------- Append Environment
                    655: 
                    656: sub appenv {
1.949     raeburn   657:     my ($newenv,$roles) = @_;
                    658:     if (ref($newenv) eq 'HASH') {
                    659:         foreach my $key (keys(%{$newenv})) {
                    660:             my $refused = 0;
                    661: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    662:                 $refused = 1;
                    663:                 if (ref($roles) eq 'ARRAY') {
                    664:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    665:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    666:                         $refused = 0;
                    667:                     }
                    668:                 }
                    669:             }
                    670:             if ($refused) {
                    671:                 &logthis("<font color=\"blue\">WARNING: ".
                    672:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    673:                          .'</font>');
                    674: 	        delete($newenv->{$key});
                    675:             } else {
                    676:                 $env{$key}=$newenv->{$key};
                    677:             }
                    678:         }
                    679:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    680:         if ($opened
                    681: 	    && &timed_flock($env_file,LOCK_EX)
                    682: 	    &&
                    683: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    684: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    685: 	    while (my ($key,$value) = each(%{$newenv})) {
                    686: 	        $disk_env{$key} = $value;
                    687: 	    }
                    688: 	    untie(%disk_env);
1.35      www       689:         }
1.191     harris41  690:     }
1.56      www       691:     return 'ok';
                    692: }
                    693: # ----------------------------------------------------- Delete from Environment
                    694: 
                    695: sub delenv {
1.1104    raeburn   696:     my ($delthis,$regexp,$roles) = @_;
                    697:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    698:         my $refused = 1;
                    699:         if (ref($roles) eq 'ARRAY') {
                    700:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    701:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    702:                 $refused = 0;
                    703:             }
                    704:         }
                    705:         if ($refused) {
                    706:             &logthis("<font color=\"blue\">WARNING: ".
                    707:                      "Attempt to delete from environment ".$delthis);
                    708:             return 'error';
                    709:         }
1.56      www       710:     }
1.917     albertel  711:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    712:     if ($opened
1.915     albertel  713: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  714: 	&&
                    715: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    716: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  717: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   718: 	    if ($regexp) {
                    719:                 if ($key=~/^$delthis/) {
                    720:                     delete($env{$key});
                    721:                     delete($disk_env{$key});
                    722:                 } 
                    723:             } else {
                    724:                 if ($key=~/^\Q$delthis\E/) {
                    725: 		    delete($env{$key});
                    726: 		    delete($disk_env{$key});
                    727: 	        }
                    728:             }
1.448     albertel  729: 	}
1.783     albertel  730: 	untie(%disk_env);
1.5       www       731:     }
                    732:     return 'ok';
1.369     albertel  733: }
                    734: 
1.790     albertel  735: sub get_env_multiple {
                    736:     my ($name) = @_;
                    737:     my @values;
                    738:     if (defined($env{$name})) {
                    739:         # exists is it an array
                    740:         if (ref($env{$name})) {
                    741:             @values=@{ $env{$name} };
                    742:         } else {
                    743:             $values[0]=$env{$name};
                    744:         }
                    745:     }
                    746:     return(@values);
                    747: }
                    748: 
1.958     www       749: # ------------------------------------------------------------------- Locking
                    750: 
                    751: sub set_lock {
                    752:     my ($text)=@_;
                    753:     $locknum++;
                    754:     my $id=$$.'-'.$locknum;
                    755:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    756:              'session.lock.'.$id => $text});
                    757:     return $id;
                    758: }
                    759: 
                    760: sub get_locks {
                    761:     my $num=0;
                    762:     my %texts=();
                    763:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    764:        if ($lock=~/\w/) {
                    765:           $num++;
                    766:           $texts{$lock}=$env{'session.lock.'.$lock};
                    767:        }
                    768:    }
                    769:    return ($num,%texts);
                    770: }
                    771: 
                    772: sub remove_lock {
                    773:     my ($id)=@_;
                    774:     my $newlocks='';
                    775:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    776:        if (($lock=~/\w/) && ($lock ne $id)) {
                    777:           $newlocks.=','.$lock;
                    778:        }
                    779:     }
                    780:     &appenv({'session.locks' => $newlocks});
                    781:     &delenv('session.lock.'.$id);
                    782: }
                    783: 
                    784: sub remove_all_locks {
                    785:     my $activelocks=$env{'session.locks'};
                    786:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    787:        if ($lock=~/\w/) {
                    788:           &remove_lock($lock);
                    789:        }
                    790:     }
                    791: }
                    792: 
                    793: 
1.369     albertel  794: # ------------------------------------------ Find out current server userload
                    795: sub userload {
                    796:     my $numusers=0;
                    797:     {
                    798: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    799: 	my $filename;
                    800: 	my $curtime=time;
                    801: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  802: 	    next if ($filename eq '.' || $filename eq '..');
                    803: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  804: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  805: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  806: 	}
                    807: 	closedir(LONIDS);
                    808:     }
                    809:     my $userloadpercent=0;
                    810:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    811:     if ($maxuserload) {
1.371     albertel  812: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  813:     }
1.372     albertel  814:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  815:     return $userloadpercent;
1.283     www       816: }
                    817: 
1.1       albertel  818: # ------------------------------ Find server with least workload from spare.tab
1.11      www       819: 
1.1       albertel  820: sub spareserver {
1.1083    raeburn   821:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  822:     my $spare_server;
1.370     albertel  823:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  824:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    825:                                                      :  $userloadpercent;
1.1083    raeburn   826:     my ($uint_dom,$remotesessions);
                    827:     if (($udom ne '') && (&domain($udom) ne '')) {
                    828:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    829:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    830:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    831:         $remotesessions = $udomdefaults{'remotesessions'};
                    832:     }
1.1123    raeburn   833:     my $spareshash = &this_host_spares($udom);
                    834:     if (ref($spareshash) eq 'HASH') {
                    835:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    836:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    837:                 if ($uint_dom) {
                    838:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    839:                                                  $try_server));
                    840:                 }
                    841: 	        ($spare_server, $lowest_load) =
                    842: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    843:             }
1.1083    raeburn   844:         }
1.784     albertel  845: 
1.1123    raeburn   846:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    847: 
                    848:         if (!$found_server) {
                    849:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    850: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    851:                     if ($uint_dom) {
                    852:                         next unless (&spare_can_host($udom,$uint_dom,
                    853:                                                      $remotesessions,$try_server));
                    854:                     }
                    855: 	            ($spare_server, $lowest_load) =
                    856: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    857:                 }
                    858: 	    }
                    859:         }
1.784     albertel  860:     }
                    861: 
                    862:     if (!$want_server_name) {
1.968     raeburn   863:         my $protocol = 'http';
                    864:         if ($protocol{$spare_server} eq 'https') {
                    865:             $protocol = $protocol{$spare_server};
                    866:         }
1.1001    raeburn   867:         if (defined($spare_server)) {
                    868:             my $hostname = &hostname($spare_server);
1.1083    raeburn   869:             if (defined($hostname)) {
1.1001    raeburn   870: 	        $spare_server = $protocol.'://'.$hostname;
                    871:             }
                    872:         }
1.784     albertel  873:     }
                    874:     return $spare_server;
                    875: }
                    876: 
                    877: sub compare_server_load {
                    878:     my ($try_server, $spare_server, $lowest_load) = @_;
                    879: 
                    880:     my $loadans     = &reply('load',    $try_server);
                    881:     my $userloadans = &reply('userload',$try_server);
                    882: 
                    883:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   884: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  885:     }
                    886: 
                    887:     my $load;
                    888:     if ($loadans =~ /\d/) {
                    889: 	if ($userloadans =~ /\d/) {
                    890: 	    #both are numbers, pick the bigger one
                    891: 	    $load = ($loadans > $userloadans) ? $loadans 
                    892: 		                              : $userloadans;
1.411     albertel  893: 	} else {
1.784     albertel  894: 	    $load = $loadans;
1.411     albertel  895: 	}
1.784     albertel  896:     } else {
                    897: 	$load = $userloadans;
                    898:     }
                    899: 
                    900:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    901: 	$spare_server = $try_server;
                    902: 	$lowest_load  = $load;
1.370     albertel  903:     }
1.784     albertel  904:     return ($spare_server,$lowest_load);
1.202     matthew   905: }
1.914     albertel  906: 
                    907: # --------------------------- ask offload servers if user already has a session
                    908: sub find_existing_session {
                    909:     my ($udom,$uname) = @_;
1.1123    raeburn   910:     my $spareshash = &this_host_spares($udom);
                    911:     if (ref($spareshash) eq 'HASH') {
                    912:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    913:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    914:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    915:             }
                    916:         }
                    917:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    918:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    919:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    920:             }
                    921:         }
1.914     albertel  922:     }
                    923:     return;
                    924: }
                    925: 
                    926: # -------------------------------- ask if server already has a session for user
                    927: sub has_user_session {
                    928:     my ($lonid,$udom,$uname) = @_;
                    929:     my $result = &reply(join(':','userhassession',
                    930: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    931:     return 1 if ($result eq 'ok');
                    932: 
                    933:     return 0;
                    934: }
                    935: 
1.1076    raeburn   936: # --------- determine least loaded server in a user's domain which allows login
                    937: 
                    938: sub choose_server {
1.1115    raeburn   939:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   940:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   941:     my %servers = &get_servers($udom);
1.1076    raeburn   942:     my $lowest_load = 30000;
1.1151    raeburn   943:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   944:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   945:         my $loginvia;
                    946:         if ($checkloginvia) {
                    947:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   948:             if ($loginvia) {
                    949:                 my ($server,$path) = split(/:/,$loginvia);
                    950:                 ($login_host, $lowest_load) =
                    951:                     &compare_server_load($server, $login_host, $lowest_load);
                    952:                 if ($login_host eq $server) {
                    953:                     $portal_path = $path;
1.1151    raeburn   954:                     $isredirect = 1;
1.1116    raeburn   955:                 }
                    956:             } else {
                    957:                 ($login_host, $lowest_load) =
                    958:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    959:                 if ($login_host eq $lonhost) {
                    960:                     $portal_path = '';
1.1151    raeburn   961:                     $isredirect = ''; 
1.1116    raeburn   962:                 }
                    963:             }
                    964:         } else {
1.1076    raeburn   965:             ($login_host, $lowest_load) =
1.1116    raeburn   966:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   967:         }
                    968:     }
                    969:     if ($login_host ne '') {
1.1116    raeburn   970:         $hostname = &hostname($login_host);
1.1076    raeburn   971:     }
1.1151    raeburn   972:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   973: }
                    974: 
1.202     matthew   975: # --------------------------------------------- Try to change a user's password
                    976: 
                    977: sub changepass {
1.799     raeburn   978:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   979:     $currentpass = &escape($currentpass);
                    980:     $newpass     = &escape($newpass);
1.1030    raeburn   981:     my $lonhost = $perlvar{'lonHostID'};
                    982:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   983: 		       $server);
                    984:     if (! $answer) {
                    985: 	&logthis("No reply on password change request to $server ".
                    986: 		 "by $uname in domain $udom.");
                    987:     } elsif ($answer =~ "^ok") {
                    988:         &logthis("$uname in $udom successfully changed their password ".
                    989: 		 "on $server.");
                    990:     } elsif ($answer =~ "^pwchange_failure") {
                    991: 	&logthis("$uname in $udom was unable to change their password ".
                    992: 		 "on $server.  The action was blocked by either lcpasswd ".
                    993: 		 "or pwchange");
                    994:     } elsif ($answer =~ "^non_authorized") {
                    995:         &logthis("$uname in $udom did not get their password correct when ".
                    996: 		 "attempting to change it on $server.");
                    997:     } elsif ($answer =~ "^auth_mode_error") {
                    998:         &logthis("$uname in $udom attempted to change their password despite ".
                    999: 		 "not being locally or internally authenticated on $server.");
                   1000:     } elsif ($answer =~ "^unknown_user") {
                   1001:         &logthis("$uname in $udom attempted to change their password ".
                   1002: 		 "on $server but were unable to because $server is not ".
                   1003: 		 "their home server.");
                   1004:     } elsif ($answer =~ "^refused") {
                   1005: 	&logthis("$server refused to change $uname in $udom password because ".
                   1006: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1007:     } elsif ($answer =~ "invalid_client") {
                   1008:         &logthis("$server refused to change $uname in $udom password because ".
                   1009:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1010:     }
                   1011:     return $answer;
1.1       albertel 1012: }
                   1013: 
1.169     harris41 1014: # ----------------------- Try to determine user's current authentication scheme
                   1015: 
                   1016: sub queryauthenticate {
                   1017:     my ($uname,$udom)=@_;
1.456     albertel 1018:     my $uhome=&homeserver($uname,$udom);
                   1019:     if (!$uhome) {
                   1020: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1021: 	return 'no_host';
                   1022:     }
                   1023:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1024:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1025: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1026:     }
1.456     albertel 1027:     return $answer;
1.169     harris41 1028: }
                   1029: 
1.1       albertel 1030: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1031: 
1.1       albertel 1032: sub authenticate {
1.1073    raeburn  1033:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1034:     $upass=&escape($upass);
                   1035:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1036:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1037:     my $newhome;
1.836     www      1038:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1039: # Maybe the machine was offline and only re-appeared again recently?
                   1040:         &reconlonc();
                   1041: # One more
1.952     raeburn  1042: 	$uhome=&homeserver($uname,$udom,1);
                   1043:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1044:             if (defined(&domain($udom,'primary'))) {
                   1045:                 $newhome=&domain($udom,'primary');
                   1046:             }
                   1047:             if ($newhome ne '') {
                   1048:                 $uhome = $newhome;
                   1049:             }
                   1050:         }
1.836     www      1051: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1052: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1053: 	    return 'no_host';
                   1054:         }
1.1       albertel 1055:     }
1.1073    raeburn  1056:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1057:     if ($answer eq 'authorized') {
1.952     raeburn  1058:         if ($newhome) {
                   1059:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1060:             return 'no_account_on_host'; 
                   1061:         } else {
                   1062:             &logthis("User $uname at $udom authorized by $uhome");
                   1063:             return $uhome;
                   1064:         }
1.471     albertel 1065:     }
                   1066:     if ($answer eq 'non_authorized') {
                   1067: 	&logthis("User $uname at $udom rejected by $uhome");
                   1068: 	return 'no_host'; 
1.9       www      1069:     }
1.471     albertel 1070:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1071:     return 'no_host';
                   1072: }
                   1073: 
1.1073    raeburn  1074: sub can_host_session {
1.1074    raeburn  1075:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1076:     my $canhost = 1;
1.1074    raeburn  1077:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1078:     if (ref($remotesessions) eq 'HASH') {
                   1079:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1080:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1081:                 $canhost = 0;
                   1082:             } else {
                   1083:                 $canhost = 1;
                   1084:             }
                   1085:         }
                   1086:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1087:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1088:                 $canhost = 1;
                   1089:             } else {
                   1090:                 $canhost = 0;
                   1091:             }
                   1092:         }
                   1093:         if ($canhost) {
                   1094:             if ($remotesessions->{'version'} ne '') {
                   1095:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1096:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1097:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1098:                         my $major = $1;
                   1099:                         my $minor = $2;
                   1100:                         if (($major < $reqmajor ) ||
                   1101:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1102:                             $canhost = 0;
                   1103:                         }
                   1104:                     } else {
                   1105:                         $canhost = 0;
                   1106:                     }
                   1107:                 }
                   1108:             }
                   1109:         }
                   1110:     }
                   1111:     if ($canhost) {
                   1112:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1113:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1114:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1115:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1116:                 if (($uint_dom ne '') && 
                   1117:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1118:                     $canhost = 0;
                   1119:                 } else {
                   1120:                     $canhost = 1;
                   1121:                 }
                   1122:             }
                   1123:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1124:                 if (($uint_dom ne '') && 
                   1125:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1126:                     $canhost = 1;
                   1127:                 } else {
                   1128:                     $canhost = 0;
                   1129:                 }
                   1130:             }
                   1131:         }
                   1132:     }
                   1133:     return $canhost;
                   1134: }
                   1135: 
1.1083    raeburn  1136: sub spare_can_host {
                   1137:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1138:     my $canhost=1;
                   1139:     my @intdoms;
                   1140:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1141:     if (ref($internet_names) eq 'ARRAY') {
                   1142:         @intdoms = @{$internet_names};
                   1143:     }
                   1144:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1145:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1146:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1147:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1148:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1149:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1150:                                      $remotesessions,
                   1151:                                      $defdomdefaults{'hostedsessions'});
                   1152:     }
                   1153:     return $canhost;
                   1154: }
                   1155: 
1.1123    raeburn  1156: sub this_host_spares {
                   1157:     my ($dom) = @_;
1.1126    raeburn  1158:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1159:     my @hosts = &current_machine_ids();
                   1160:     foreach my $lonhost (@hosts) {
                   1161:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1162:             $dom_in_use = $dom;
                   1163:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1164:             last;
                   1165:         }
                   1166:     }
1.1126    raeburn  1167:     if ($dom_in_use ne '') {
                   1168:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1169:     }
                   1170:     if (ref($result) ne 'HASH') {
                   1171:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1172:         $dom_in_use = &host_domain($lonhost_in_use);
                   1173:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1174:         if (ref($result) ne 'HASH') {
                   1175:             $result = \%spareid;
                   1176:         }
                   1177:     }
                   1178:     return $result;
                   1179: }
                   1180: 
                   1181: sub spares_for_offload  {
                   1182:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1183:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1184:     if (defined($cached)) {
                   1185:         return $result;
                   1186:     } else {
1.1126    raeburn  1187:         my $cachetime = 60*60*24;
                   1188:         my %domconfig =
                   1189:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1190:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1191:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1192:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1193:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1194:                 }
                   1195:             }
                   1196:         }
                   1197:     }
1.1126    raeburn  1198:     return;
1.1123    raeburn  1199: }
                   1200: 
1.1129    raeburn  1201: sub get_lonbalancer_config {
                   1202:     my ($servers) = @_;
                   1203:     my ($currbalancer,$currtargets);
                   1204:     if (ref($servers) eq 'HASH') {
                   1205:         foreach my $server (keys(%{$servers})) {
                   1206:             my %what = (
                   1207:                          spareid => 1,
                   1208:                          perlvar => 1,
                   1209:                        );
                   1210:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1211:             if ($result eq 'ok') {
                   1212:                 if (ref($returnhash) eq 'HASH') {
                   1213:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1214:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1215:                             $currbalancer = $server;
                   1216:                             $currtargets = {};
                   1217:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1218:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1219:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1220:                                 }
                   1221:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1222:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1223:                                 }
                   1224:                             }
                   1225:                             last;
                   1226:                         }
                   1227:                     }
                   1228:                 }
                   1229:             }
                   1230:         }
                   1231:     }
                   1232:     return ($currbalancer,$currtargets);
                   1233: }
                   1234: 
                   1235: sub check_loadbalancing {
                   1236:     my ($uname,$udom) = @_;
                   1237:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1238:         $offloadto,$otherserver);
                   1239:     my $lonhost = $perlvar{'lonHostID'};
                   1240:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1241:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1242:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1243:     my $serverhomedom = &host_domain($lonhost);
                   1244: 
                   1245:     my $cachetime = 60*60*24;
                   1246: 
                   1247:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1248:         $dom_in_use = $udom;
                   1249:         $homeintdom = 1;
                   1250:     } else {
                   1251:         $dom_in_use = $serverhomedom;
                   1252:     }
                   1253:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1254:     unless (defined($cached)) {
                   1255:         my %domconfig =
                   1256:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1257:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1258:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1259:         }
                   1260:     }
                   1261:     if (ref($result) eq 'HASH') {
                   1262:         my $currbalancer = $result->{'lonhost'};
                   1263:         my $currtargets = $result->{'targets'};
                   1264:         my $currrules = $result->{'rules'};
                   1265:         if ($currbalancer ne '') {
                   1266:             my @hosts = &current_machine_ids();
                   1267:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1268:                 $is_balancer = 1;
                   1269:             }
                   1270:         }
                   1271:         if ($is_balancer) {
                   1272:             if (ref($currrules) eq 'HASH') {
                   1273:                 if ($homeintdom) {
                   1274:                     if ($uname ne '') {
                   1275:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1276:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1277:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1278:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1279:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1280:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1281:                             }
                   1282:                         }
                   1283:                         if ($rule_in_effect eq '') {
                   1284:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1285:                             if ($userenv{'inststatus'} ne '') {
                   1286:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1287:                                 my ($othertitle,$usertypes,$types) =
                   1288:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1289:                                 if (ref($types) eq 'ARRAY') {
                   1290:                                     foreach my $type (@{$types}) {
                   1291:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1292:                                             if (exists($currrules->{$type})) {
                   1293:                                                 $rule_in_effect = $currrules->{$type};
                   1294:                                             }
                   1295:                                         }
                   1296:                                     }
                   1297:                                 }
                   1298:                             } else {
                   1299:                                 if (exists($currrules->{'default'})) {
                   1300:                                     $rule_in_effect = $currrules->{'default'};
                   1301:                                 }
                   1302:                             }
                   1303:                         }
                   1304:                     } else {
                   1305:                         if (exists($currrules->{'default'})) {
                   1306:                             $rule_in_effect = $currrules->{'default'};
                   1307:                         }
                   1308:                     }
                   1309:                 } else {
                   1310:                     if ($currrules->{'_LC_external'} ne '') {
                   1311:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1312:                     }
                   1313:                 }
                   1314:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1315:                                                        $uname,$udom);
                   1316:             }
                   1317:         }
                   1318:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1319:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1320:         unless (defined($cached)) {
                   1321:             my %domconfig =
                   1322:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1323:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1324:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1325:             }
                   1326:         }
                   1327:         if (ref($result) eq 'HASH') {
                   1328:             my $currbalancer = $result->{'lonhost'};
                   1329:             my $currtargets = $result->{'targets'};
                   1330:             my $currrules = $result->{'rules'};
                   1331: 
                   1332:             if ($currbalancer eq $lonhost) {
                   1333:                 $is_balancer = 1;
                   1334:                 if (ref($currrules) eq 'HASH') {
                   1335:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1336:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1337:                     }
                   1338:                 }
                   1339:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1340:                                                        $uname,$udom);
                   1341:             }
                   1342:         } else {
                   1343:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1344:                 $is_balancer = 1;
                   1345:                 $offloadto = &this_host_spares($dom_in_use);
                   1346:             }
                   1347:         }
                   1348:     } else {
                   1349:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1350:             $is_balancer = 1;
                   1351:             $offloadto = &this_host_spares($dom_in_use);
                   1352:         }
                   1353:     }
                   1354:     my $lowest_load = 30000;
                   1355:     if (ref($offloadto) eq 'HASH') {
                   1356:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1357:             foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1358:                 ($otherserver,$lowest_load) =
                   1359:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1360:             }
                   1361:         }
                   1362:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
                   1363: 
                   1364:         if (!$found_server) {
                   1365:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1366:                 foreach my $try_server (@{$offloadto->{'default'}}) {
                   1367:                     ($otherserver,$lowest_load) =
                   1368:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1369:                 }
                   1370:             }
                   1371:         }
                   1372:     } elsif (ref($offloadto) eq 'ARRAY') {
                   1373:         if (@{$offloadto} == 1) {
                   1374:             $otherserver = $offloadto->[0];
                   1375:         } elsif (@{$offloadto} > 1) {
                   1376:             foreach my $try_server (@{$offloadto}) {
                   1377:                 ($otherserver,$lowest_load) =
                   1378:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1379:             }
                   1380:         }
                   1381:     }
                   1382:     return ($is_balancer,$otherserver);
                   1383: }
                   1384: 
                   1385: sub get_loadbalancer_targets {
                   1386:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1387:     my $offloadto;
                   1388:     if ($rule_in_effect eq '') {
                   1389:         $offloadto = $currtargets;
                   1390:     } else {
                   1391:         if ($rule_in_effect eq 'homeserver') {
                   1392:             my $homeserver = &homeserver($uname,$udom);
                   1393:             if ($homeserver ne 'no_host') {
                   1394:                 $offloadto = [$homeserver];
                   1395:             }
                   1396:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1397:             my %domconfig =
                   1398:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1399:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1400:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1401:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1402:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1403:                     }
                   1404:                 }
                   1405:             } else {
                   1406:                 my %servers = &dom_servers($udom);
                   1407:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1408:                 if (&hostname($remotebalancer) ne '') {
                   1409:                     $offloadto = [$remotebalancer];
                   1410:                 }
                   1411:             }
                   1412:         } elsif (&hostname($rule_in_effect) ne '') {
                   1413:             $offloadto = [$rule_in_effect];
                   1414:         }
                   1415:     }
                   1416:     return $offloadto;
                   1417: }
                   1418: 
1.1127    raeburn  1419: sub internet_dom_servers {
                   1420:     my ($dom) = @_;
                   1421:     my (%uniqservers,%servers);
                   1422:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1423:     my @machinedoms = &machine_domains($primaryserver);
                   1424:     foreach my $mdom (@machinedoms) {
                   1425:         my %currservers = %servers;
                   1426:         my %server = &get_servers($mdom);
                   1427:         %servers = (%currservers,%server);
                   1428:     }
                   1429:     my %by_hostname;
                   1430:     foreach my $id (keys(%servers)) {
                   1431:         push(@{$by_hostname{$servers{$id}}},$id);
                   1432:     }
                   1433:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1434:         if (@{$by_hostname{$hostname}} > 1) {
                   1435:             my $match = 0;
                   1436:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1437:                 if (&host_domain($id) eq $dom) {
                   1438:                     $uniqservers{$id} = $hostname;
                   1439:                     $match = 1;
                   1440:                 }
                   1441:             }
                   1442:             unless ($match) {
                   1443:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1444:             }
                   1445:         } else {
                   1446:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1447:         }
                   1448:     }
                   1449:     return %uniqservers;
                   1450: }
                   1451: 
1.1       albertel 1452: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1453: 
1.599     albertel 1454: my %homecache;
1.1       albertel 1455: sub homeserver {
1.230     stredwic 1456:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1457:     my $index="$uname:$udom";
1.426     albertel 1458: 
1.599     albertel 1459:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1460: 
                   1461:     my %servers = &get_servers($udom,'library');
                   1462:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1463:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1464: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1465: 
                   1466: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1467: 	if ($answer eq 'found') {
                   1468: 	    delete($badServerCache{$tryserver}); 
                   1469: 	    return $homecache{$index}=$tryserver;
                   1470: 	} elsif ($answer eq 'no_host') {
                   1471: 	    $badServerCache{$tryserver}=1;
                   1472: 	}
1.1       albertel 1473:     }    
                   1474:     return 'no_host';
1.70      www      1475: }
                   1476: 
                   1477: # ------------------------------------- Find the usernames behind a list of IDs
                   1478: 
                   1479: sub idget {
                   1480:     my ($udom,@ids)=@_;
                   1481:     my %returnhash=();
                   1482:     
1.841     albertel 1483:     my %servers = &get_servers($udom,'library');
                   1484:     foreach my $tryserver (keys(%servers)) {
                   1485: 	my $idlist=join('&',@ids);
                   1486: 	$idlist=~tr/A-Z/a-z/; 
                   1487: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1488: 	my @answer=();
                   1489: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1490: 	    @answer=split(/\&/,$reply);
                   1491: 	}                    ;
                   1492: 	my $i;
                   1493: 	for ($i=0;$i<=$#ids;$i++) {
                   1494: 	    if ($answer[$i]) {
                   1495: 		$returnhash{$ids[$i]}=$answer[$i];
                   1496: 	    } 
                   1497: 	}
                   1498:     } 
1.70      www      1499:     return %returnhash;
                   1500: }
                   1501: 
                   1502: # ------------------------------------- Find the IDs behind a list of usernames
                   1503: 
                   1504: sub idrget {
                   1505:     my ($udom,@unames)=@_;
                   1506:     my %returnhash=();
1.800     albertel 1507:     foreach my $uname (@unames) {
                   1508:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1509:     }
1.70      www      1510:     return %returnhash;
                   1511: }
                   1512: 
                   1513: # ------------------------------- Store away a list of names and associated IDs
                   1514: 
                   1515: sub idput {
                   1516:     my ($udom,%ids)=@_;
                   1517:     my %servers=();
1.800     albertel 1518:     foreach my $uname (keys(%ids)) {
                   1519: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1520:         my $uhom=&homeserver($uname,$udom);
1.70      www      1521:         if ($uhom ne 'no_host') {
1.800     albertel 1522:             my $id=&escape($ids{$uname});
1.70      www      1523:             $id=~tr/A-Z/a-z/;
1.800     albertel 1524:             my $esc_unam=&escape($uname);
1.70      www      1525: 	    if ($servers{$uhom}) {
1.800     albertel 1526: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1527:             } else {
1.800     albertel 1528:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1529:             }
                   1530:         }
1.191     harris41 1531:     }
1.800     albertel 1532:     foreach my $server (keys(%servers)) {
                   1533:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1534:     }
1.344     www      1535: }
                   1536: 
1.1023    raeburn  1537: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1538: sub dump_dom {
1.1165    droeschl 1539:     my ($namespace, $udom, $regexp) = @_;
                   1540: 
                   1541:     $udom ||= $env{'user.domain'};
                   1542: 
                   1543:     return () unless $udom;
                   1544: 
                   1545:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1546: }
                   1547: 
1.1023    raeburn  1548: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1549: 
                   1550: sub get_dom {
1.860     raeburn  1551:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1552:     my $items='';
                   1553:     foreach my $item (@$storearr) {
                   1554:         $items.=&escape($item).'&';
                   1555:     }
                   1556:     $items=~s/\&$//;
1.860     raeburn  1557:     if (!$udom) {
                   1558:         $udom=$env{'user.domain'};
                   1559:         if (defined(&domain($udom,'primary'))) {
                   1560:             $uhome=&domain($udom,'primary');
                   1561:         } else {
1.874     albertel 1562:             undef($uhome);
1.860     raeburn  1563:         }
                   1564:     } else {
                   1565:         if (!$uhome) {
                   1566:             if (defined(&domain($udom,'primary'))) {
                   1567:                 $uhome=&domain($udom,'primary');
                   1568:             }
                   1569:         }
                   1570:     }
                   1571:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1572:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1573:         my %returnhash;
1.875     albertel 1574:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1575:             return %returnhash;
                   1576:         }
1.806     raeburn  1577:         my @pairs=split(/\&/,$rep);
                   1578:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1579:             return @pairs;
                   1580:         }
                   1581:         my $i=0;
                   1582:         foreach my $item (@$storearr) {
                   1583:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1584:             $i++;
                   1585:         }
                   1586:         return %returnhash;
                   1587:     } else {
1.880     banghart 1588:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1589:     }
                   1590: }
                   1591: 
                   1592: # -------------------------------------------- put items in domain db files 
                   1593: 
                   1594: sub put_dom {
1.860     raeburn  1595:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1596:     if (!$udom) {
                   1597:         $udom=$env{'user.domain'};
                   1598:         if (defined(&domain($udom,'primary'))) {
                   1599:             $uhome=&domain($udom,'primary');
                   1600:         } else {
1.874     albertel 1601:             undef($uhome);
1.860     raeburn  1602:         }
                   1603:     } else {
                   1604:         if (!$uhome) {
                   1605:             if (defined(&domain($udom,'primary'))) {
                   1606:                 $uhome=&domain($udom,'primary');
                   1607:             }
                   1608:         }
                   1609:     } 
                   1610:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1611:         my $items='';
                   1612:         foreach my $item (keys(%$storehash)) {
                   1613:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1614:         }
                   1615:         $items=~s/\&$//;
                   1616:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1617:     } else {
1.860     raeburn  1618:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1619:     }
                   1620: }
                   1621: 
1.1023    raeburn  1622: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1623: sub newput_dom {
1.1023    raeburn  1624:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1625:     my $result;
                   1626:     if (!$udom) {
                   1627:         $udom=$env{'user.domain'};
                   1628:     }
1.1023    raeburn  1629:     if ($udom) {
                   1630:         my $uname = &get_domainconfiguser($udom);
                   1631:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1632:     }
                   1633:     return $result;
                   1634: }
                   1635: 
1.1023    raeburn  1636: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1637: sub del_dom {
1.1023    raeburn  1638:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1639:     if (ref($storearr) eq 'ARRAY') {
                   1640:         if (!$udom) {
                   1641:             $udom=$env{'user.domain'};
                   1642:         }
1.1023    raeburn  1643:         if ($udom) {
                   1644:             my $uname = &get_domainconfiguser($udom); 
                   1645:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1646:         }
                   1647:     }
                   1648: }
                   1649: 
1.1023    raeburn  1650: # ----------------------------------construct domainconfig user for a domain 
                   1651: sub get_domainconfiguser {
                   1652:     my ($udom) = @_;
                   1653:     return $udom.'-domainconfig';
                   1654: }
                   1655: 
1.837     raeburn  1656: sub retrieve_inst_usertypes {
                   1657:     my ($udom) = @_;
                   1658:     my (%returnhash,@order);
1.989     raeburn  1659:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1660:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1661:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1662:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1663:         @order = @{$domdefs{'inststatusorder'}};
                   1664:     } else {
                   1665:         if (defined(&domain($udom,'primary'))) {
                   1666:             my $uhome=&domain($udom,'primary');
                   1667:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1668:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1669:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1670:                 return (\%returnhash,\@order);
                   1671:             }
                   1672:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1673:             my @pairs=split(/\&/,$hashitems);
                   1674:             foreach my $item (@pairs) {
                   1675:                 my ($key,$value)=split(/=/,$item,2);
                   1676:                 $key = &unescape($key);
                   1677:                 next if ($key =~ /^error: 2 /);
                   1678:                 $returnhash{$key}=&thaw_unescape($value);
                   1679:             }
                   1680:             my @esc_order = split(/\&/,$orderitems);
                   1681:             foreach my $item (@esc_order) {
                   1682:                 push(@order,&unescape($item));
                   1683:             }
                   1684:         } else {
                   1685:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1686:         }
                   1687:     }
                   1688:     return (\%returnhash,\@order);
                   1689: }
                   1690: 
1.868     raeburn  1691: sub is_domainimage {
                   1692:     my ($url) = @_;
                   1693:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1694:         if (&domain($1) ne '') {
                   1695:             return '1';
                   1696:         }
                   1697:     }
                   1698:     return;
                   1699: }
                   1700: 
1.899     raeburn  1701: sub inst_directory_query {
                   1702:     my ($srch) = @_;
                   1703:     my $udom = $srch->{'srchdomain'};
                   1704:     my %results;
                   1705:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1706:     my $outcome;
1.899     raeburn  1707:     if ($homeserver ne '') {
1.904     albertel 1708: 	my $queryid=&reply("querysend:instdirsearch:".
                   1709: 			   &escape($srch->{'srchby'}).':'.
                   1710: 			   &escape($srch->{'srchterm'}).':'.
                   1711: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1712: 	my $host=&hostname($homeserver);
                   1713: 	if ($queryid !~/^\Q$host\E\_/) {
                   1714: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1715: 	    return;
                   1716: 	}
                   1717: 	my $response = &get_query_reply($queryid);
                   1718: 	my $maxtries = 5;
                   1719: 	my $tries = 1;
                   1720: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1721: 	    $response = &get_query_reply($queryid);
                   1722: 	    $tries ++;
                   1723: 	}
                   1724: 
                   1725:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1726:             if ($response eq 'unavailable') {
                   1727:                 $outcome = $response;
                   1728:             } else {
                   1729:                 $outcome = 'ok';
                   1730:                 my @matches = split(/\n/,$response);
                   1731:                 foreach my $match (@matches) {
                   1732:                     my ($key,$value) = split(/=/,$match);
                   1733:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1734:                 }
1.899     raeburn  1735:             }
                   1736:         }
                   1737:     }
1.909     raeburn  1738:     return ($outcome,%results);
1.899     raeburn  1739: }
                   1740: 
                   1741: sub usersearch {
                   1742:     my ($srch) = @_;
                   1743:     my $dom = $srch->{'srchdomain'};
                   1744:     my %results;
                   1745:     my %libserv = &all_library();
                   1746:     my $query = 'usersearch';
                   1747:     foreach my $tryserver (keys(%libserv)) {
                   1748:         if (&host_domain($tryserver) eq $dom) {
                   1749:             my $host=&hostname($tryserver);
                   1750:             my $queryid=
1.911     raeburn  1751:                 &reply("querysend:".&escape($query).':'.
                   1752:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1753:                        &escape($srch->{'srchtype'}).':'.
                   1754:                        &escape($srch->{'srchterm'}),$tryserver);
                   1755:             if ($queryid !~/^\Q$host\E\_/) {
                   1756:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1757:                 next;
1.899     raeburn  1758:             }
                   1759:             my $reply = &get_query_reply($queryid);
                   1760:             my $maxtries = 1;
                   1761:             my $tries = 1;
                   1762:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1763:                 $reply = &get_query_reply($queryid);
                   1764:                 $tries ++;
                   1765:             }
                   1766:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1767:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1768:             } else {
1.911     raeburn  1769:                 my @matches;
                   1770:                 if ($reply =~ /\n/) {
                   1771:                     @matches = split(/\n/,$reply);
                   1772:                 } else {
                   1773:                     @matches = split(/\&/,$reply);
                   1774:                 }
1.899     raeburn  1775:                 foreach my $match (@matches) {
                   1776:                     my ($uname,$udom,%userhash);
1.911     raeburn  1777:                     foreach my $entry (split(/:/,$match)) {
                   1778:                         my ($key,$value) =
                   1779:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1780:                         $userhash{$key} = $value;
                   1781:                         if ($key eq 'username') {
                   1782:                             $uname = $value;
                   1783:                         } elsif ($key eq 'domain') {
                   1784:                             $udom = $value;
1.911     raeburn  1785:                         }
1.899     raeburn  1786:                     }
                   1787:                     $results{$uname.':'.$udom} = \%userhash;
                   1788:                 }
                   1789:             }
                   1790:         }
                   1791:     }
                   1792:     return %results;
                   1793: }
                   1794: 
1.912     raeburn  1795: sub get_instuser {
                   1796:     my ($udom,$uname,$id) = @_;
                   1797:     my $homeserver = &domain($udom,'primary');
                   1798:     my ($outcome,%results);
                   1799:     if ($homeserver ne '') {
                   1800:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1801:                            &escape($id).':'.&escape($udom),$homeserver);
                   1802:         my $host=&hostname($homeserver);
                   1803:         if ($queryid !~/^\Q$host\E\_/) {
                   1804:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1805:             return;
                   1806:         }
                   1807:         my $response = &get_query_reply($queryid);
                   1808:         my $maxtries = 5;
                   1809:         my $tries = 1;
                   1810:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1811:             $response = &get_query_reply($queryid);
                   1812:             $tries ++;
                   1813:         }
                   1814:         if (!&error($response) && $response ne 'refused') {
                   1815:             if ($response eq 'unavailable') {
                   1816:                 $outcome = $response;
                   1817:             } else {
                   1818:                 $outcome = 'ok';
                   1819:                 my @matches = split(/\n/,$response);
                   1820:                 foreach my $match (@matches) {
                   1821:                     my ($key,$value) = split(/=/,$match);
                   1822:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1823:                 }
                   1824:             }
                   1825:         }
                   1826:     }
                   1827:     my %userinfo;
                   1828:     if (ref($results{$uname}) eq 'HASH') {
                   1829:         %userinfo = %{$results{$uname}};
                   1830:     } 
                   1831:     return ($outcome,%userinfo);
                   1832: }
                   1833: 
                   1834: sub inst_rulecheck {
1.923     raeburn  1835:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1836:     my %returnhash;
                   1837:     if ($udom ne '') {
                   1838:         if (ref($rules) eq 'ARRAY') {
                   1839:             @{$rules} = map {&escape($_);} (@{$rules});
                   1840:             my $rulestr = join(':',@{$rules});
                   1841:             my $homeserver=&domain($udom,'primary');
                   1842:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1843:                 my $response;
                   1844:                 if ($item eq 'username') {                
                   1845:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1846:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1847:                                               $homeserver));
1.923     raeburn  1848:                 } elsif ($item eq 'id') {
                   1849:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1850:                                               ':'.&escape($id).':'.$rulestr,
                   1851:                                               $homeserver));
1.945     raeburn  1852:                 } elsif ($item eq 'selfcreate') {
                   1853:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1854:                                                &escape($udom).':'.&escape($uname).
                   1855:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1856:                 }
1.912     raeburn  1857:                 if ($response ne 'refused') {
                   1858:                     my @pairs=split(/\&/,$response);
                   1859:                     foreach my $item (@pairs) {
                   1860:                         my ($key,$value)=split(/=/,$item,2);
                   1861:                         $key = &unescape($key);
                   1862:                         next if ($key =~ /^error: 2 /);
                   1863:                         $returnhash{$key}=&thaw_unescape($value);
                   1864:                     }
                   1865:                 }
                   1866:             }
                   1867:         }
                   1868:     }
                   1869:     return %returnhash;
                   1870: }
                   1871: 
                   1872: sub inst_userrules {
1.923     raeburn  1873:     my ($udom,$check) = @_;
1.912     raeburn  1874:     my (%ruleshash,@ruleorder);
                   1875:     if ($udom ne '') {
                   1876:         my $homeserver=&domain($udom,'primary');
                   1877:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1878:             my $response;
                   1879:             if ($check eq 'id') {
                   1880:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1881:                                  $homeserver);
1.943     raeburn  1882:             } elsif ($check eq 'email') {
                   1883:                 $response=&reply('instemailrules:'.&escape($udom),
                   1884:                                  $homeserver);
1.923     raeburn  1885:             } else {
                   1886:                 $response=&reply('instuserrules:'.&escape($udom),
                   1887:                                  $homeserver);
                   1888:             }
1.912     raeburn  1889:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1890:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1891:                 ($response ne 'no_such_host')) {
                   1892:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1893:                 my @pairs=split(/\&/,$hashitems);
                   1894:                 foreach my $item (@pairs) {
                   1895:                     my ($key,$value)=split(/=/,$item,2);
                   1896:                     $key = &unescape($key);
                   1897:                     next if ($key =~ /^error: 2 /);
                   1898:                     $ruleshash{$key}=&thaw_unescape($value);
                   1899:                 }
                   1900:                 my @esc_order = split(/\&/,$orderitems);
                   1901:                 foreach my $item (@esc_order) {
                   1902:                     push(@ruleorder,&unescape($item));
                   1903:                 }
                   1904:             }
                   1905:         }
                   1906:     }
                   1907:     return (\%ruleshash,\@ruleorder);
                   1908: }
                   1909: 
1.976     raeburn  1910: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1911: 
                   1912: sub get_domain_defaults {
                   1913:     my ($domain) = @_;
                   1914:     my $cachetime = 60*60*24;
                   1915:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1916:     if (defined($cached)) {
                   1917:         if (ref($result) eq 'HASH') {
                   1918:             return %{$result};
                   1919:         }
                   1920:     }
                   1921:     my %domdefaults;
                   1922:     my %domconfig =
1.989     raeburn  1923:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1924:                                   'requestcourses','inststatus',
1.1073    raeburn  1925:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1926:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1927:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1928:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1929:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1930:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1931:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1932:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1933:     } else {
                   1934:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1935:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1936:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1937:     }
1.976     raeburn  1938:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1939:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1940:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1941:         } else {
                   1942:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1943:         } 
                   1944:         my @usertools = ('aboutme','blog','portfolio');
                   1945:         foreach my $item (@usertools) {
                   1946:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1947:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1948:             }
                   1949:         }
                   1950:     }
1.985     raeburn  1951:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1952:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1953:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1954:         }
                   1955:     }
1.989     raeburn  1956:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1957:         foreach my $item ('inststatustypes','inststatusorder') {
                   1958:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1959:         }
                   1960:     }
1.1047    raeburn  1961:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1962:         foreach my $item ('canuse_pdfforms') {
                   1963:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1964:         }
                   1965:     }
1.1073    raeburn  1966:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1967:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1968:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1969:         }
                   1970:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1971:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1972:         }
                   1973:     }
1.943     raeburn  1974:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1975:                                   $cachetime);
                   1976:     return %domdefaults;
                   1977: }
                   1978: 
1.344     www      1979: # --------------------------------------------------- Assign a key to a student
                   1980: 
                   1981: sub assign_access_key {
1.364     www      1982: #
                   1983: # a valid key looks like uname:udom#comments
                   1984: # comments are being appended
                   1985: #
1.498     www      1986:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1987:     $kdom=
1.620     albertel 1988:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1989:     $knum=
1.620     albertel 1990:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1991:     $cdom=
1.620     albertel 1992:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1993:     $cnum=
1.620     albertel 1994:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1995:     $udom=$env{'user.name'} unless (defined($udom));
                   1996:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1997:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1998:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1999:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2000:                                                   # assigned to this person
                   2001:                                                   # - this should not happen,
1.345     www      2002:                                                   # unless something went wrong
                   2003:                                                   # the first time around
                   2004: # ready to assign
1.364     www      2005:         $logentry=$1.'; '.$logentry;
1.496     www      2006:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2007:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2008: # key now belongs to user
1.346     www      2009: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2010:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2011:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2012:                 return 'ok';
                   2013:             } else {
                   2014:                 return 
                   2015:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2016: 	    }
                   2017:         } else {
                   2018:             return 'error: Could not assign key, try again later.';
                   2019:         }
1.364     www      2020:     } elsif (!$existing{$ckey}) {
1.345     www      2021: # the key does not exist
                   2022: 	return 'error: The key does not exist';
                   2023:     } else {
                   2024: # the key is somebody else's
                   2025: 	return 'error: The key is already in use';
                   2026:     }
1.344     www      2027: }
                   2028: 
1.364     www      2029: # ------------------------------------------ put an additional comment on a key
                   2030: 
                   2031: sub comment_access_key {
                   2032: #
                   2033: # a valid key looks like uname:udom#comments
                   2034: # comments are being appended
                   2035: #
                   2036:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2037:     $cdom=
1.620     albertel 2038:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2039:     $cnum=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2041:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2042:     if ($existing{$ckey}) {
                   2043:         $existing{$ckey}.='; '.$logentry;
                   2044: # ready to assign
1.367     www      2045:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2046:                                                  $cdom,$cnum) eq 'ok') {
                   2047: 	    return 'ok';
                   2048:         } else {
                   2049: 	    return 'error: Count not store comment.';
                   2050:         }
                   2051:     } else {
                   2052: # the key does not exist
                   2053: 	return 'error: The key does not exist';
                   2054:     }
                   2055: }
                   2056: 
1.344     www      2057: # ------------------------------------------------------ Generate a set of keys
                   2058: 
                   2059: sub generate_access_keys {
1.364     www      2060:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2061:     $cdom=
1.620     albertel 2062:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2063:     $cnum=
1.620     albertel 2064:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2065:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2066:     unless (($cdom) && ($cnum)) { return 0; }
                   2067:     if ($number>10000) { return 0; }
                   2068:     sleep(2); # make sure don't get same seed twice
                   2069:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2070:     my $total=0;
                   2071:     for (my $i=1;$i<=$number;$i++) {
                   2072:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2073:                   sprintf("%lx",int(100000*rand)).'-'.
                   2074:                   sprintf("%lx",int(100000*rand));
                   2075:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2076:        $newkey=~s/0/h/g; # and also 0 and O
                   2077:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2078:        if ($existing{$newkey}) {
                   2079:            $i--;
                   2080:        } else {
1.364     www      2081: 	  if (&put('accesskeys',
                   2082:               { $newkey => '# generated '.localtime().
1.620     albertel 2083:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2084:                            '; '.$logentry },
                   2085: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2086:               $total++;
                   2087: 	  }
                   2088:        }
                   2089:     }
1.620     albertel 2090:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2091:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2092:     return $total;
                   2093: }
                   2094: 
                   2095: # ------------------------------------------------------- Validate an accesskey
                   2096: 
                   2097: sub validate_access_key {
                   2098:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2099:     $cdom=
1.620     albertel 2100:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2101:     $cnum=
1.620     albertel 2102:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2103:     $udom=$env{'user.domain'} unless (defined($udom));
                   2104:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2105:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2106:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2107: }
                   2108: 
                   2109: # ------------------------------------- Find the section of student in a course
1.652     albertel 2110: sub devalidate_getsection_cache {
                   2111:     my ($udom,$unam,$courseid)=@_;
                   2112:     my $hashid="$udom:$unam:$courseid";
                   2113:     &devalidate_cache_new('getsection',$hashid);
                   2114: }
1.298     matthew  2115: 
1.815     albertel 2116: sub courseid_to_courseurl {
                   2117:     my ($courseid) = @_;
                   2118:     #already url style courseid
                   2119:     return $courseid if ($courseid =~ m{^/});
                   2120: 
                   2121:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2122: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2123: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2124: 	return "/$cdom/$cnum";
                   2125:     }
                   2126: 
                   2127:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2128:     if (exists($courseinfo{'num'})) {
                   2129: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2130:     }
                   2131: 
                   2132:     return undef;
                   2133: }
                   2134: 
1.298     matthew  2135: sub getsection {
                   2136:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2137:     my $cachetime=1800;
1.551     albertel 2138: 
                   2139:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2140:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2141:     if (defined($cached)) { return $result; }
                   2142: 
1.298     matthew  2143:     my %Pending; 
                   2144:     my %Expired;
                   2145:     #
                   2146:     # Each role can either have not started yet (pending), be active, 
                   2147:     #    or have expired.
                   2148:     #
                   2149:     # If there is an active role, we are done.
                   2150:     #
                   2151:     # If there is more than one role which has not started yet, 
                   2152:     #     choose the one which will start sooner
                   2153:     # If there is one role which has not started yet, return it.
                   2154:     #
                   2155:     # If there is more than one expired role, choose the one which ended last.
                   2156:     # If there is a role which has expired, return it.
                   2157:     #
1.815     albertel 2158:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2159:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2160:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2161:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2162:         my $section=$1;
                   2163:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2164:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2165:         my $now=time;
1.548     albertel 2166:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2167:             $Expired{$end}=$section;
                   2168:             next;
                   2169:         }
1.548     albertel 2170:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2171:             $Pending{$start}=$section;
                   2172:             next;
                   2173:         }
1.599     albertel 2174:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2175:     }
                   2176:     #
                   2177:     # Presumedly there will be few matching roles from the above
                   2178:     # loop and the sorting time will be negligible.
                   2179:     if (scalar(keys(%Pending))) {
                   2180:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2181:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2182:     } 
                   2183:     if (scalar(keys(%Expired))) {
                   2184:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2185:         my $time = pop(@sorted);
1.599     albertel 2186:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2187:     }
1.599     albertel 2188:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2189: }
1.70      www      2190: 
1.599     albertel 2191: sub save_cache {
                   2192:     &purge_remembered();
1.722     albertel 2193:     #&Apache::loncommon::validate_page();
1.620     albertel 2194:     undef(%env);
1.780     albertel 2195:     undef($env_loaded);
1.599     albertel 2196: }
1.452     albertel 2197: 
1.599     albertel 2198: my $to_remember=-1;
                   2199: my %remembered;
                   2200: my %accessed;
                   2201: my $kicks=0;
                   2202: my $hits=0;
1.849     albertel 2203: sub make_key {
                   2204:     my ($name,$id) = @_;
1.872     albertel 2205:     if (length($id) > 65 
                   2206: 	&& length(&escape($id)) > 200) {
                   2207: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2208:     }
1.849     albertel 2209:     return &escape($name.':'.$id);
                   2210: }
                   2211: 
1.599     albertel 2212: sub devalidate_cache_new {
                   2213:     my ($name,$id,$debug) = @_;
                   2214:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2215:     $id=&make_key($name,$id);
1.599     albertel 2216:     $memcache->delete($id);
                   2217:     delete($remembered{$id});
                   2218:     delete($accessed{$id});
                   2219: }
                   2220: 
                   2221: sub is_cached_new {
                   2222:     my ($name,$id,$debug) = @_;
1.849     albertel 2223:     $id=&make_key($name,$id);
1.599     albertel 2224:     if (exists($remembered{$id})) {
1.1133    foxr     2225: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2226: 	$accessed{$id}=[&gettimeofday()];
                   2227: 	$hits++;
                   2228: 	return ($remembered{$id},1);
                   2229:     }
                   2230:     my $value = $memcache->get($id);
                   2231:     if (!(defined($value))) {
                   2232: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2233: 	return (undef,undef);
1.416     albertel 2234:     }
1.599     albertel 2235:     if ($value eq '__undef__') {
                   2236: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2237: 	$value=undef;
                   2238:     }
                   2239:     &make_room($id,$value,$debug);
                   2240:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2241:     return ($value,1);
                   2242: }
                   2243: 
                   2244: sub do_cache_new {
                   2245:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2246:     $id=&make_key($name,$id);
1.599     albertel 2247:     my $setvalue=$value;
                   2248:     if (!defined($setvalue)) {
                   2249: 	$setvalue='__undef__';
                   2250:     }
1.623     albertel 2251:     if (!defined($time) ) {
                   2252: 	$time=600;
                   2253:     }
1.599     albertel 2254:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2255:     my $result = $memcache->set($id,$setvalue,$time);
                   2256:     if (! $result) {
1.872     albertel 2257: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2258: 	$memcache->disconnect_all();
1.872     albertel 2259:     }
1.600     albertel 2260:     # need to make a copy of $value
1.919     albertel 2261:     &make_room($id,$value,$debug);
1.599     albertel 2262:     return $value;
                   2263: }
                   2264: 
                   2265: sub make_room {
                   2266:     my ($id,$value,$debug)=@_;
1.919     albertel 2267: 
                   2268:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2269:                                     : $value;
1.599     albertel 2270:     if ($to_remember<0) { return; }
                   2271:     $accessed{$id}=[&gettimeofday()];
                   2272:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2273:     my $to_kick;
                   2274:     my $max_time=0;
                   2275:     foreach my $other (keys(%accessed)) {
                   2276: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2277: 	    $to_kick=$other;
                   2278: 	    $max_time=&tv_interval($accessed{$other});
                   2279: 	}
                   2280:     }
                   2281:     delete($remembered{$to_kick});
                   2282:     delete($accessed{$to_kick});
                   2283:     $kicks++;
                   2284:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2285:     return;
                   2286: }
                   2287: 
1.599     albertel 2288: sub purge_remembered {
1.604     albertel 2289:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2290:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2291:     undef(%remembered);
                   2292:     undef(%accessed);
1.428     albertel 2293: }
1.70      www      2294: # ------------------------------------- Read an entry from a user's environment
                   2295: 
                   2296: sub userenvironment {
                   2297:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2298:     my $items;
                   2299:     foreach my $item (@what) {
                   2300:         $items.=&escape($item).'&';
                   2301:     }
                   2302:     $items=~s/\&$//;
1.70      www      2303:     my %returnhash=();
1.1009    raeburn  2304:     my $uhome = &homeserver($unam,$udom);
                   2305:     unless ($uhome eq 'no_host') {
                   2306:         my @answer=split(/\&/, 
                   2307:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2308:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2309:             return %returnhash;
                   2310:         }
1.1009    raeburn  2311:         my $i;
                   2312:         for ($i=0;$i<=$#what;$i++) {
                   2313: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2314:         }
1.70      www      2315:     }
                   2316:     return %returnhash;
1.1       albertel 2317: }
                   2318: 
1.617     albertel 2319: # ---------------------------------------------------------- Get a studentphoto
                   2320: sub studentphoto {
                   2321:     my ($udom,$unam,$ext) = @_;
                   2322:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2323:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2324:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2325:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2326:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2327:             } else {
                   2328:                 my ($result,$perm_reqd)=
1.707     albertel 2329: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2330:                 if ($result eq 'ok') {
                   2331:                     if (!($perm_reqd eq 'yes')) {
                   2332:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2333:                     }
                   2334:                 }
                   2335:             }
                   2336:         }
                   2337:     } else {
                   2338:         my ($result,$perm_reqd) = 
1.707     albertel 2339: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2340:         if ($result eq 'ok') {
                   2341:             if (!($perm_reqd eq 'yes')) {
                   2342:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2343:             }
                   2344:         }
                   2345:     }
                   2346:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2347: }
                   2348: 
                   2349: sub retrievestudentphoto {
                   2350:     my ($udom,$unam,$ext,$type) = @_;
                   2351:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2352:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2353:     if ($ret eq 'ok') {
                   2354:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2355:         if ($type eq 'thumbnail') {
                   2356:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2357:         }
                   2358:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2359:         return $tokenurl;
                   2360:     } else {
                   2361:         if ($type eq 'thumbnail') {
                   2362:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2363:         } else { 
                   2364:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2365:         }
1.617     albertel 2366:     }
                   2367: }
                   2368: 
1.263     www      2369: # -------------------------------------------------------------------- New chat
                   2370: 
                   2371: sub chatsend {
1.724     raeburn  2372:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2373:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2374:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2375:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2376:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2377: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2378: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2379: }
                   2380: 
                   2381: # ------------------------------------------ Find current version of a resource
                   2382: 
                   2383: sub getversion {
                   2384:     my $fname=&clutter(shift);
                   2385:     unless ($fname=~/^\/res\//) { return -1; }
                   2386:     return &currentversion(&filelocation('',$fname));
                   2387: }
                   2388: 
                   2389: sub currentversion {
                   2390:     my $fname=shift;
                   2391:     my $author=$fname;
                   2392:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2393:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2394:     my $home=&homeserver($uname,$udom);
1.292     www      2395:     if ($home eq 'no_host') { 
                   2396:         return -1; 
                   2397:     }
1.1112    www      2398:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2399:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2400: 	return -1;
                   2401:     }
1.1112    www      2402:     return $answer;
1.263     www      2403: }
                   2404: 
1.1111    www      2405: #
                   2406: # Return special version number of resource if set by override, empty otherwise
                   2407: #
                   2408: sub usedversion {
                   2409:     my $fname=shift;
                   2410:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2411:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2412:     if ($urlversion) { return $urlversion; }
                   2413:     return '';
                   2414: }
                   2415: 
1.1       albertel 2416: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2417: 
1.1       albertel 2418: sub subscribe {
                   2419:     my $fname=shift;
1.761     raeburn  2420:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2421:     $fname=~s/[\n\r]//g;
1.1       albertel 2422:     my $author=$fname;
                   2423:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2424:     my ($udom,$uname)=split(/\//,$author);
                   2425:     my $home=homeserver($uname,$udom);
1.335     albertel 2426:     if ($home eq 'no_host') {
                   2427:         return 'not_found';
1.1       albertel 2428:     }
                   2429:     my $answer=reply("sub:$fname",$home);
1.64      www      2430:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2431: 	$answer.=' by '.$home;
                   2432:     }
1.1       albertel 2433:     return $answer;
                   2434: }
                   2435:     
1.8       www      2436: # -------------------------------------------------------------- Replicate file
                   2437: 
                   2438: sub repcopy {
                   2439:     my $filename=shift;
1.23      www      2440:     $filename=~s/\/+/\//g;
1.1142    raeburn  2441:     my $londocroot = $perlvar{'lonDocRoot'};
                   2442:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2443:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2444:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2445: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2446: 	return &repcopy_userfile($filename);
                   2447:     }
1.532     albertel 2448:     $filename=~s/[\n\r]//g;
1.8       www      2449:     my $transname="$filename.in.transfer";
1.828     www      2450: # FIXME: this should flock
1.607     raeburn  2451:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2452:     my $remoteurl=subscribe($filename);
1.64      www      2453:     if ($remoteurl =~ /^con_lost by/) {
                   2454: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2455:            return 'unavailable';
1.8       www      2456:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2457: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2458: 	   return 'not_found';
1.64      www      2459:     } elsif ($remoteurl =~ /^rejected by/) {
                   2460: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2461:            return 'forbidden';
1.20      www      2462:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2463:            return 'ok';
1.8       www      2464:     } else {
1.290     www      2465:         my $author=$filename;
                   2466:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2467:         my ($udom,$uname)=split(/\//,$author);
                   2468:         my $home=homeserver($uname,$udom);
                   2469:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2470:            my @parts=split(/\//,$filename);
                   2471:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2472:            if ($path ne "$londocroot/res") {
1.8       www      2473:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2474: 	       return 'bad_request';
1.8       www      2475:            }
                   2476:            my $count;
                   2477:            for ($count=5;$count<$#parts;$count++) {
                   2478:                $path.="/$parts[$count]";
                   2479:                if ((-e $path)!=1) {
                   2480: 		   mkdir($path,0777);
                   2481:                }
                   2482:            }
                   2483:            my $ua=new LWP::UserAgent;
                   2484:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2485:            my $response=$ua->request($request,$transname);
                   2486:            if ($response->is_error()) {
                   2487: 	       unlink($transname);
                   2488:                my $message=$response->status_line;
1.672     albertel 2489:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2490:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2491:                return 'unavailable';
1.8       www      2492:            } else {
1.16      www      2493: 	       if ($remoteurl!~/\.meta$/) {
                   2494:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2495:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2496:                   if ($mresponse->is_error()) {
                   2497: 		      unlink($filename.'.meta');
                   2498:                       &logthis(
1.672     albertel 2499:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2500:                   }
                   2501: 	       }
1.8       www      2502:                rename($transname,$filename);
1.607     raeburn  2503:                return 'ok';
1.8       www      2504:            }
1.290     www      2505:        }
1.8       www      2506:     }
1.330     www      2507: }
                   2508: 
                   2509: # ------------------------------------------------ Get server side include body
                   2510: sub ssi_body {
1.381     albertel 2511:     my ($filelink,%form)=@_;
1.606     matthew  2512:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2513:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2514:     }
1.953     www      2515:     my $output='';
                   2516:     my $response;
1.980     raeburn  2517:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2518:        ($output,$response)=&externalssi($filelink);
1.953     www      2519:     } else {
1.1004    droeschl 2520:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2521:        $filelink .= 'inhibitmenu=yes';
1.953     www      2522:        ($output,$response)=&ssi($filelink,%form);
                   2523:     }
1.778     albertel 2524:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2525:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2526:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2527:     if (wantarray) {
                   2528:         return ($output, $response);
                   2529:     } else {
                   2530:         return $output;
                   2531:     }
1.8       www      2532: }
                   2533: 
1.15      www      2534: # --------------------------------------------------------- Server Side Include
                   2535: 
1.782     albertel 2536: sub absolute_url {
                   2537:     my ($host_name) = @_;
                   2538:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2539:     if ($host_name eq '') {
                   2540: 	$host_name = $ENV{'SERVER_NAME'};
                   2541:     }
                   2542:     return $protocol.$host_name;
                   2543: }
                   2544: 
1.942     foxr     2545: #
                   2546: #   Server side include.
                   2547: # Parameters:
                   2548: #  fn     Possibly encrypted resource name/id.
                   2549: #  form   Hash that describes how the rendering should be done
                   2550: #         and other things.
1.944     foxr     2551: # Returns:
1.950     raeburn  2552: #   Scalar context: The content of the response.
                   2553: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2554: #     
1.15      www      2555: sub ssi {
                   2556: 
1.944     foxr     2557:     my ($fn,%form)=@_;
1.15      www      2558:     my $ua=new LWP::UserAgent;
1.23      www      2559:     my $request;
1.711     albertel 2560: 
                   2561:     $form{'no_update_last_known'}=1;
1.895     albertel 2562:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2563:     if (%form) {
1.782     albertel 2564:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2565:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2566:     } else {
1.782     albertel 2567:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2568:     }
                   2569: 
1.15      www      2570:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2571:     my $response=$ua->request($request);
                   2572: 
1.944     foxr     2573:     if (wantarray) {
                   2574: 	return ($response->content, $response);
                   2575:     } else {
                   2576: 	return $response->content;
1.942     foxr     2577:     }
1.324     www      2578: }
                   2579: 
                   2580: sub externalssi {
                   2581:     my ($url)=@_;
                   2582:     my $ua=new LWP::UserAgent;
                   2583:     my $request=new HTTP::Request('GET',$url);
                   2584:     my $response=$ua->request($request);
1.954     raeburn  2585:     if (wantarray) {
                   2586:         return ($response->content, $response);
                   2587:     } else {
                   2588:         return $response->content;
                   2589:     }
1.15      www      2590: }
1.254     www      2591: 
1.492     albertel 2592: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2593: 
                   2594: sub allowuploaded {
                   2595:     my ($srcurl,$url)=@_;
                   2596:     $url=&clutter(&declutter($url));
                   2597:     my $dir=$url;
                   2598:     $dir=~s/\/[^\/]+$//;
                   2599:     my %httpref=();
                   2600:     my $httpurl=&hreflocation('',$url);
                   2601:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2602:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2603: }
1.477     raeburn  2604: 
1.478     albertel 2605: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2606: # input: action, courseID, current domain, intended
1.637     raeburn  2607: #        path to file, source of file, instruction to parse file for objects,
                   2608: #        ref to hash for embedded objects,
                   2609: #        ref to hash for codebase of java objects.
1.1095    raeburn  2610: #        reference to scalar to accommodate mime type determined
                   2611: #          from File::MMagic if $parser = parse.
1.637     raeburn  2612: #
1.485     raeburn  2613: # output: url to file (if action was uploaddoc), 
                   2614: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2615: #
1.478     albertel 2616: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2617: # course.
1.477     raeburn  2618: #
1.478     albertel 2619: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2620: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2621: #          course's home server.
1.477     raeburn  2622: #
1.478     albertel 2623: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2624: #          be copied from $source (current location) to 
                   2625: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2626: #         and will then be copied to
                   2627: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2628: #         course's home server.
1.485     raeburn  2629: #
1.481     raeburn  2630: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2631: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2632: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2633: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2634: #         in course's home server.
1.637     raeburn  2635: #
1.477     raeburn  2636: 
                   2637: sub process_coursefile {
1.1095    raeburn  2638:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2639:         $mimetype)=@_;
1.477     raeburn  2640:     my $fetchresult;
1.638     albertel 2641:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2642:     if ($action eq 'propagate') {
1.638     albertel 2643:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2644: 			     $home);
1.481     raeburn  2645:     } else {
1.477     raeburn  2646:         my $fpath = '';
                   2647:         my $fname = $file;
1.478     albertel 2648:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2649:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2650:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2651:         if ($action eq 'copy') {
                   2652:             if ($source eq '') {
                   2653:                 $fetchresult = 'no source file';
                   2654:                 return $fetchresult;
                   2655:             } else {
                   2656:                 my $destination = $filepath.'/'.$fname;
                   2657:                 rename($source,$destination);
                   2658:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2659:                                  $home);
1.481     raeburn  2660:             }
                   2661:         } elsif ($action eq 'uploaddoc') {
                   2662:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2663:             print $fh $env{'form.'.$source};
1.481     raeburn  2664:             close($fh);
1.637     raeburn  2665:             if ($parser eq 'parse') {
1.1024    raeburn  2666:                 my $mm = new File::MMagic;
1.1095    raeburn  2667:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2668:                 if ($type eq 'text/html') {
1.1024    raeburn  2669:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2670:                     unless ($parse_result eq 'ok') {
                   2671:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2672:                     }
1.637     raeburn  2673:                 }
1.1095    raeburn  2674:                 if (ref($mimetype)) {
                   2675:                     $$mimetype = $type;
                   2676:                 } 
1.637     raeburn  2677:             }
1.477     raeburn  2678:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2679:                                  $home);
1.481     raeburn  2680:             if ($fetchresult eq 'ok') {
                   2681:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2682:             } else {
                   2683:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2684:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2685:                 return '/adm/notfound.html';
                   2686:             }
1.477     raeburn  2687:         }
                   2688:     }
1.485     raeburn  2689:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2690:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2691:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2692:     }
                   2693:     return $fetchresult;
                   2694: }
                   2695: 
1.637     raeburn  2696: sub build_filepath {
                   2697:     my ($fpath) = @_;
                   2698:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2699:     unless ($fpath eq '') {
                   2700:         my @parts=split('/',$fpath);
                   2701:         foreach my $part (@parts) {
                   2702:             $filepath.= '/'.$part;
                   2703:             if ((-e $filepath)!=1) {
                   2704:                 mkdir($filepath,0777);
                   2705:             }
                   2706:         }
                   2707:     }
                   2708:     return $filepath;
                   2709: }
                   2710: 
                   2711: sub store_edited_file {
1.638     albertel 2712:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2713:     my $file = $primary_url;
                   2714:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2715:     my $fpath = '';
                   2716:     my $fname = $file;
                   2717:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2718:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2719:     my $filepath = &build_filepath($fpath);
                   2720:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2721:     print $fh $content;
                   2722:     close($fh);
1.638     albertel 2723:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2724:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2725: 			  $home);
1.637     raeburn  2726:     if ($$fetchresult eq 'ok') {
                   2727:         return '/uploaded/'.$fpath.'/'.$fname;
                   2728:     } else {
1.638     albertel 2729:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2730: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2731:         return '/adm/notfound.html';
                   2732:     }
                   2733: }
                   2734: 
1.531     albertel 2735: sub clean_filename {
1.831     albertel 2736:     my ($fname,$args)=@_;
1.315     www      2737: # Replace Windows backslashes by forward slashes
1.257     www      2738:     $fname=~s/\\/\//g;
1.831     albertel 2739:     if (!$args->{'keep_path'}) {
                   2740:         # Get rid of everything but the actual filename
                   2741: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2742:     }
1.315     www      2743: # Replace spaces by underscores
                   2744:     $fname=~s/\s+/\_/g;
                   2745: # Replace all other weird characters by nothing
1.831     albertel 2746:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2747: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2748: # numbers
                   2749:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2750:     return $fname;
                   2751: }
1.1051    raeburn  2752: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2753: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2754: # image with the same aspect ratio as the original, but with dimensions which do 
                   2755: # not exceed $resizewidth and $resizeheight.
                   2756:  
1.984     neumanie 2757: sub resizeImage {
1.1051    raeburn  2758:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2759:     my $ima = Image::Magick->new;
                   2760:     my $resized;
                   2761:     if (-e $img_path) {
                   2762:         $ima->Read($img_path);
                   2763:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2764:             my $width = $ima->Get('width');
                   2765:             my $height = $ima->Get('height');
                   2766:             if ($width > $resizewidth) {
                   2767: 	        my $factor = $width/$resizewidth;
                   2768:                 my $newheight = $height/$factor;
                   2769:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2770:                 $resized = 1;
                   2771:             }
                   2772:         }
                   2773:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2774:             my $width = $ima->Get('width');
                   2775:             my $height = $ima->Get('height');
                   2776:             if ($height > $resizeheight) {
                   2777:                 my $factor = $height/$resizeheight;
                   2778:                 my $newwidth = $width/$factor;
                   2779:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2780:                 $resized = 1;
                   2781:             }
                   2782:         }
                   2783:         if ($resized) {
                   2784:             $ima->Write($img_path);
                   2785:         }
                   2786:     }
                   2787:     return;
1.977     amueller 2788: }
                   2789: 
1.608     albertel 2790: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2791: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2792: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2793: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2794: #                                    canceloverwrite, or ''. 
                   2795: #                   if 'coursedoc': upload to the current course
                   2796: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2797: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2798: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2799: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2800: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2801: #        $allfiles - reference to hash for embedded objects
                   2802: #        $codebase - reference to hash for codebase of java objects
                   2803: #        $desuname - username for permanent storage of uploaded file
                   2804: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2805: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2806: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2807: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2808: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2809: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2810: #                    from File::MMagic.
1.858     raeburn  2811: # 
1.686     albertel 2812: # output: url of file in userspace, or error: <message> 
                   2813: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2814: 
1.531     albertel 2815: sub userfileupload {
1.1090    raeburn  2816:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2817:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2818:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2819:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2820:     $fname=&clean_filename($fname);
1.1090    raeburn  2821:     # See if there is anything left
1.257     www      2822:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2823:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2824:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2825:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2826:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2827:         my $now = time;
1.1090    raeburn  2828:         my $filepath;
1.1095    raeburn  2829:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2830:              $filepath = 'tmp/helprequests/'.$now;
                   2831:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2832:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2833:                          '_'.$env{'user.domain'}.'/pending';
                   2834:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2835:             my ($docuname,$docudom);
                   2836:             if ($destudom) {
                   2837:                 $docudom = $destudom;
                   2838:             } else {
                   2839:                 $docudom = $env{'user.domain'};
                   2840:             }
                   2841:             if ($destuname) {
                   2842:                 $docuname = $destuname;
                   2843:             } else {
                   2844:                 $docuname = $env{'user.name'};
                   2845:             }
                   2846:             if (exists($env{'form.group'})) {
                   2847:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2848:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2849:             }
                   2850:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2851:             if ($context eq 'canceloverwrite') {
                   2852:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2853:                 if (-e  $tempfile) {
                   2854:                     my @info = stat($tempfile);
                   2855:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2856:                         unlink($tempfile);
                   2857:                     }
                   2858:                 }
                   2859:                 return;
1.523     raeburn  2860:             }
                   2861:         }
1.1090    raeburn  2862:         # Create the directory if not present
1.741     raeburn  2863:         my @parts=split(/\//,$filepath);
                   2864:         my $fullpath = $perlvar{'lonDaemons'};
                   2865:         for (my $i=0;$i<@parts;$i++) {
                   2866:             $fullpath .= '/'.$parts[$i];
                   2867:             if ((-e $fullpath)!=1) {
                   2868:                 mkdir($fullpath,0777);
                   2869:             }
                   2870:         }
                   2871:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2872:         print $fh $env{'form.'.$formname};
                   2873:         close($fh);
1.1090    raeburn  2874:         if ($context eq 'existingfile') {
                   2875:             my @info = stat($fullpath.'/'.$fname);
                   2876:             return ($fullpath.'/'.$fname,$info[9]);
                   2877:         } else {
                   2878:             return $fullpath.'/'.$fname;
                   2879:         }
1.523     raeburn  2880:     }
1.995     raeburn  2881:     if ($subdir eq 'scantron') {
                   2882:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2883:     } else {
1.995     raeburn  2884:         $fname="$subdir/$fname";
                   2885:     }
1.1090    raeburn  2886:     if ($context eq 'coursedoc') {
1.638     albertel 2887: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2888: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2889:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2890:             return &finishuserfileupload($docuname,$docudom,
                   2891: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2892: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2893:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2894:         } else {
1.620     albertel 2895:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2896:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2897: 				       $fname,$formname,$parser,
1.1095    raeburn  2898: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2899:         }
1.719     banghart 2900:     } elsif (defined($destuname)) {
                   2901:         my $docuname=$destuname;
                   2902:         my $docudom=$destudom;
1.860     raeburn  2903: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2904: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2905:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2906:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2907:     } else {
1.638     albertel 2908:         my $docuname=$env{'user.name'};
                   2909:         my $docudom=$env{'user.domain'};
1.714     raeburn  2910:         if (exists($env{'form.group'})) {
                   2911:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2912:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2913:         }
1.860     raeburn  2914: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2915: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2916:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2917:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2918:     }
1.271     www      2919: }
                   2920: 
                   2921: sub finishuserfileupload {
1.860     raeburn  2922:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2923:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2924:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2925:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2926:   
1.860     raeburn  2927:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2928:     $file=$fname;
                   2929:     if ($fname=~m|/|) {
                   2930:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2931: 	$path.=$fnamepath.'/';
                   2932:     }
1.259     www      2933:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2934:     my $count;
                   2935:     for ($count=4;$count<=$#parts;$count++) {
                   2936:         $filepath.="/$parts[$count]";
                   2937:         if ((-e $filepath)!=1) {
                   2938: 	    mkdir($filepath,0777);
                   2939:         }
                   2940:     }
1.984     neumanie 2941: 
1.258     www      2942: # Save the file
                   2943:     {
1.701     albertel 2944: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2945: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2946: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2947: 	    return '/adm/notfound.html';
                   2948: 	}
1.1090    raeburn  2949:         if ($context eq 'overwrite') {
1.1117    foxr     2950:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2951:             my $target = $filepath.'/'.$file;
                   2952:             if (-e $source) {
                   2953:                 my @info = stat($source);
                   2954:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2955:                     unless (&File::Copy::move($source,$target)) {
                   2956:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2957:                         return "Moving from $source failed";
                   2958:                     }
                   2959:                 } else {
                   2960:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2961:                 }
                   2962:             } else {
                   2963:                 return "Temporary file: $source missing";
                   2964:             }
                   2965:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2966: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2967: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2968: 	    return '/adm/notfound.html';
                   2969: 	}
1.570     albertel 2970: 	close(FH);
1.1051    raeburn  2971:         if ($resizewidth && $resizeheight) {
                   2972:             my $mm = new File::MMagic;
                   2973:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2974:             if ($mime_type =~ m{^image/}) {
                   2975: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2976:             }  
1.977     amueller 2977: 	}
1.258     www      2978:     }
1.1152    raeburn  2979:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   2980:         if (ref($mimetype)) {
                   2981:             if ($$mimetype eq '') {
                   2982:                 my $mm = new File::MMagic;
                   2983:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2984:                 $$mimetype = $type;
                   2985:             }
                   2986:         }
                   2987:     }
1.637     raeburn  2988:     if ($parser eq 'parse') {
1.1152    raeburn  2989:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  2990:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2991:                                                        $allfiles,$codebase);
                   2992:             unless ($parse_result eq 'ok') {
                   2993:                 &logthis('Failed to parse '.$filepath.$file.
                   2994: 	   	         ' for embedded media: '.$parse_result); 
                   2995:             }
1.637     raeburn  2996:         }
                   2997:     }
1.860     raeburn  2998:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2999:         my $input = $filepath.'/'.$file;
                   3000:         my $output = $filepath.'/'.'tn-'.$file;
                   3001:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3002:         system("convert -sample $thumbsize $input $output");
                   3003:         if (-e $filepath.'/'.'tn-'.$file) {
                   3004:             $fetchthumb  = 1; 
                   3005:         }
                   3006:     }
1.858     raeburn  3007:  
1.259     www      3008: # Notify homeserver to grep it
                   3009: #
1.984     neumanie 3010:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3011:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3012:     if ($fetchresult eq 'ok') {
1.860     raeburn  3013:         if ($fetchthumb) {
                   3014:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3015:             if ($thumbresult ne 'ok') {
                   3016:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3017:                          $docuhome.': '.$thumbresult);
                   3018:             }
                   3019:         }
1.259     www      3020: #
1.258     www      3021: # Return the URL to it
1.494     albertel 3022:         return '/uploaded/'.$path.$file;
1.263     www      3023:     } else {
1.494     albertel 3024:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3025: 		 ': '.$fetchresult);
1.263     www      3026:         return '/adm/notfound.html';
1.858     raeburn  3027:     }
1.493     albertel 3028: }
                   3029: 
1.637     raeburn  3030: sub extract_embedded_items {
1.961     raeburn  3031:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3032:     my @state = ();
1.1164    raeburn  3033:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3034:     my %javafiles = (
                   3035:                       codebase => '',
                   3036:                       code => '',
                   3037:                       archive => ''
                   3038:                     );
                   3039:     my %mediafiles = (
                   3040:                       src => '',
                   3041:                       movie => '',
                   3042:                      );
1.648     raeburn  3043:     my $p;
                   3044:     if ($content) {
                   3045:         $p = HTML::LCParser->new($content);
                   3046:     } else {
1.961     raeburn  3047:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3048:     }
1.641     albertel 3049:     while (my $t=$p->get_token()) {
1.640     albertel 3050: 	if ($t->[0] eq 'S') {
                   3051: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3052: 	    push(@state, $tagname);
1.648     raeburn  3053:             if (lc($tagname) eq 'allow') {
                   3054:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3055:             }
1.640     albertel 3056: 	    if (lc($tagname) eq 'img') {
                   3057: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3058: 	    }
1.886     albertel 3059: 	    if (lc($tagname) eq 'a') {
                   3060: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3061: 	    }
1.645     raeburn  3062:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3063:                 my $src;
1.645     raeburn  3064:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3065:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3066:                 } else {
1.1164    raeburn  3067:                     if ($attr->{'src'} ne '') {
                   3068:                         $src = $attr->{'src'};
                   3069:                         &add_filetype($allfiles,$src,'src');
                   3070:                     }
                   3071:                 }
                   3072:                 my $text = $p->get_trimmed_text();
                   3073:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3074:                     my @swfargs = split(/,/,$1);
                   3075:                     foreach my $item (@swfargs) {
                   3076:                         $item =~ s/["']//g;
                   3077:                         $item =~ s/^\s+//;
                   3078:                         $item =~ s/\s+$//;
                   3079:                     }
                   3080:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3081:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3082:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3083:                         } else {
                   3084:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3085:                         }
                   3086:                     }
1.645     raeburn  3087:                 }
                   3088:             }
                   3089:             if (lc($tagname) eq 'link') {
                   3090:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3091:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3092:                 }
                   3093:             }
1.640     albertel 3094: 	    if (lc($tagname) eq 'object' ||
                   3095: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3096: 		foreach my $item (keys(%javafiles)) {
                   3097: 		    $javafiles{$item} = '';
                   3098: 		}
1.1164    raeburn  3099:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3100:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3101:                 }
1.640     albertel 3102: 	    }
                   3103: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3104: 		my $name = lc($attr->{'name'});
                   3105: 		foreach my $item (keys(%javafiles)) {
                   3106: 		    if ($name eq $item) {
                   3107: 			$javafiles{$item} = $attr->{'value'};
                   3108: 			last;
                   3109: 		    }
                   3110: 		}
1.1164    raeburn  3111:                 my $pathfrom;
1.640     albertel 3112: 		foreach my $item (keys(%mediafiles)) {
                   3113: 		    if ($name eq $item) {
1.1164    raeburn  3114:                         $pathfrom = $attr->{'value'};
                   3115:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3116: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3117: 			last;
                   3118: 		    }
                   3119: 		}
1.1164    raeburn  3120:                 if ($name eq 'flashvars') {
                   3121:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3122:                 }
                   3123:                 if ($pathfrom ne '') {
                   3124:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3125:                                          $pathfrom);
                   3126:                 }
1.640     albertel 3127: 	    }
                   3128: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3129: 		foreach my $item (keys(%javafiles)) {
                   3130: 		    if ($attr->{$item}) {
                   3131: 			$javafiles{$item} = $attr->{$item};
                   3132: 			last;
                   3133: 		    }
                   3134: 		}
                   3135: 		foreach my $item (keys(%mediafiles)) {
                   3136: 		    if ($attr->{$item}) {
                   3137: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3138: 			last;
                   3139: 		    }
                   3140: 		}
1.1164    raeburn  3141:                 if (lc($tagname) eq 'embed') {
                   3142:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3143:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3144:                                              $attr->{'src'});
                   3145:                     }
                   3146:                 }
1.640     albertel 3147: 	    }
1.1164    raeburn  3148:             if ($t->[4] =~ m{/>$}) {
                   3149:                 pop(@state);  
                   3150:             }
1.640     albertel 3151: 	} elsif ($t->[0] eq 'E') {
                   3152: 	    my ($tagname) = ($t->[1]);
                   3153: 	    if ($javafiles{'codebase'} ne '') {
                   3154: 		$javafiles{'codebase'} .= '/';
                   3155: 	    }  
                   3156: 	    if (lc($tagname) eq 'applet' ||
                   3157: 		lc($tagname) eq 'object' ||
                   3158: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3159: 		) {
                   3160: 		foreach my $item (keys(%javafiles)) {
                   3161: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3162: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3163: 			&add_filetype($allfiles,$file,$item);
                   3164: 		    }
                   3165: 		}
                   3166: 	    } 
                   3167: 	    pop @state;
                   3168: 	}
                   3169:     }
1.1164    raeburn  3170:     foreach my $id (sort(keys(%flashvars))) {
                   3171:         if ($shockwave{$id} ne '') {
                   3172:             my @pairs = split(/\&/,$flashvars{$id});
                   3173:             foreach my $pair (@pairs) {
                   3174:                 my ($key,$value) = split(/\=/,$pair);
                   3175:                 if ($key eq 'thumb') {
                   3176:                     &add_filetype($allfiles,$value,$key);
                   3177:                 } elsif ($key eq 'content') {
                   3178:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3179:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3180:                     if ($ext ne '') {
                   3181:                         &add_filetype($allfiles,$path.$value,$ext);
                   3182:                     }
                   3183:                 }
                   3184:             }
                   3185:         }
                   3186:     }
1.637     raeburn  3187:     return 'ok';
                   3188: }
                   3189: 
1.639     albertel 3190: sub add_filetype {
                   3191:     my ($allfiles,$file,$type)=@_;
                   3192:     if (exists($allfiles->{$file})) {
                   3193: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3194: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3195: 	}
                   3196:     } else {
                   3197: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3198:     }
                   3199: }
                   3200: 
1.1164    raeburn  3201: sub embedded_dependency {
                   3202:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3203:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3204:         if (($identifier ne '') &&
                   3205:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3206:             ($pathfrom ne '')) {
                   3207:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3208:             foreach my $dep (@{$related->{$identifier}}) {
                   3209:                 &add_filetype($allfiles,$path.$dep,'object');
                   3210:             }
                   3211:         }
                   3212:     }
                   3213:     return;
                   3214: }
                   3215: 
1.493     albertel 3216: sub removeuploadedurl {
1.984     neumanie 3217:     my ($url)=@_;	
                   3218:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3219:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3220: }
                   3221: 
                   3222: sub removeuserfile {
                   3223:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3224:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3225:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3226:     if ($result eq 'ok') {	
1.798     raeburn  3227:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3228:             my $metafile = $fname.'.meta';
                   3229:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3230: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3231:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3232:             my $sqlresult = 
1.823     albertel 3233:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3234:                                         'portfolio_metadata',$group,
                   3235:                                         'delete');
1.798     raeburn  3236:         }
                   3237:     }
                   3238:     return $result;
1.257     www      3239: }
1.15      www      3240: 
1.530     albertel 3241: sub mkdiruserfile {
                   3242:     my ($docuname,$docudom,$dir)=@_;
                   3243:     my $home=&homeserver($docuname,$docudom);
                   3244:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3245: }
                   3246: 
1.531     albertel 3247: sub renameuserfile {
                   3248:     my ($docuname,$docudom,$old,$new)=@_;
                   3249:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3250:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3251:                         &escape("$old").':'.&escape("$new"),$home);
                   3252:     if ($result eq 'ok') {
                   3253:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3254:             my $oldmeta = $old.'.meta';
                   3255:             my $newmeta = $new.'.meta';
                   3256:             my $metaresult = 
                   3257:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3258: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3259:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3260:             my $sqlresult = 
1.823     albertel 3261:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3262:                                         'portfolio_metadata',$group,
                   3263:                                         'delete');
1.798     raeburn  3264:         }
                   3265:     }
                   3266:     return $result;
1.531     albertel 3267: }
                   3268: 
1.14      www      3269: # ------------------------------------------------------------------------- Log
                   3270: 
                   3271: sub log {
                   3272:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3273:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3274: }
                   3275: 
                   3276: # ------------------------------------------------------------------ Course Log
1.352     www      3277: #
                   3278: # This routine flushes several buffers of non-mission-critical nature
                   3279: #
1.157     www      3280: 
                   3281: sub flushcourselogs {
1.352     www      3282:     &logthis('Flushing log buffers');
                   3283: #
                   3284: # course logs
                   3285: # This is a log of all transactions in a course, which can be used
                   3286: # for data mining purposes
                   3287: #
                   3288: # It also collects the courseid database, which lists last transaction
                   3289: # times and course titles for all courseids
                   3290: #
                   3291:     my %courseidbuffer=();
1.921     raeburn  3292:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3293:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3294: 		          &escape($courselogs{$crsid}),
                   3295: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3296: 	    delete $courselogs{$crsid};
                   3297:         } else {
                   3298:             &logthis('Failed to flush log buffer for '.$crsid);
                   3299:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3300:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3301:                         " exceeded maximum size, deleting.</font>");
                   3302:                delete $courselogs{$crsid};
                   3303:             }
1.352     www      3304:         }
1.920     raeburn  3305:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3306:             'description' => $coursedescrbuf{$crsid},
                   3307:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3308:             'type'        => $coursetypebuf{$crsid},
                   3309:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3310:         };
1.191     harris41 3311:     }
1.352     www      3312: #
                   3313: # Write course id database (reverse lookup) to homeserver of courses 
                   3314: # Is used in pickcourse
                   3315: #
1.840     albertel 3316:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3317:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3318:                                     $courseidbuffer{$crs_home},
                   3319:                                     $crs_home,'timeonly');
1.352     www      3320:     }
                   3321: #
                   3322: # File accesses
                   3323: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3324: #
1.449     matthew  3325:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3326:         if ($entry =~ /___count$/) {
                   3327:             my ($dom,$name);
1.807     albertel 3328:             ($dom,$name,undef)=
1.811     albertel 3329: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3330:             if (! defined($dom) || $dom eq '' || 
                   3331:                 ! defined($name) || $name eq '') {
1.620     albertel 3332:                 my $cid = $env{'request.course.id'};
                   3333:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3334:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3335:             }
1.450     matthew  3336:             my $value = $accesshash{$entry};
                   3337:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3338:             my %temphash=($url => $value);
1.449     matthew  3339:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3340:             if ($result eq 'ok') {
                   3341:                 delete $accesshash{$entry};
                   3342:             }
                   3343:         } else {
1.811     albertel 3344:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3345:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3346:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3347:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3348:                 delete $accesshash{$entry};
                   3349:             }
1.185     www      3350:         }
1.191     harris41 3351:     }
1.352     www      3352: #
                   3353: # Roles
                   3354: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3355: #
1.800     albertel 3356:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3357:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3358: 	    split(/\:/,$entry);
                   3359:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3360:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3361:                 $rudom,$runame) eq 'ok') {
                   3362: 	    delete $userrolehash{$entry};
                   3363:         }
                   3364:     }
1.662     raeburn  3365: #
                   3366: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3367: #
                   3368:     my %domrolebuffer = ();
1.1000    raeburn  3369:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3370:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3371:         if ($domrolebuffer{$rudom}) {
                   3372:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3373:                       '='.&escape($domainrolehash{$entry});
                   3374:         } else {
                   3375:             $domrolebuffer{$rudom}.=&escape($entry).
                   3376:                       '='.&escape($domainrolehash{$entry});
                   3377:         }
                   3378:         delete $domainrolehash{$entry};
                   3379:     }
                   3380:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3381: 	my %servers = &get_servers($dom,'library');
                   3382: 	foreach my $tryserver (keys(%servers)) {
                   3383: 	    unless (&reply('domroleput:'.$dom.':'.
                   3384: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3385: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3386: 	    }
1.662     raeburn  3387:         }
                   3388:     }
1.186     www      3389:     $dumpcount++;
1.157     www      3390: }
                   3391: 
                   3392: sub courselog {
                   3393:     my $what=shift;
1.158     www      3394:     $what=time.':'.$what;
1.620     albertel 3395:     unless ($env{'request.course.id'}) { return ''; }
                   3396:     $coursedombuf{$env{'request.course.id'}}=
                   3397:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3398:     $coursenumbuf{$env{'request.course.id'}}=
                   3399:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3400:     $coursehombuf{$env{'request.course.id'}}=
                   3401:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3402:     $coursedescrbuf{$env{'request.course.id'}}=
                   3403:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3404:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3405:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3406:     $courseownerbuf{$env{'request.course.id'}}=
                   3407:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3408:     $coursetypebuf{$env{'request.course.id'}}=
                   3409:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3410:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3411: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3412:     } else {
1.620     albertel 3413: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3414:     }
1.620     albertel 3415:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3416: 	&flushcourselogs();
                   3417:     }
1.158     www      3418: }
                   3419: 
                   3420: sub courseacclog {
                   3421:     my $fnsymb=shift;
1.620     albertel 3422:     unless ($env{'request.course.id'}) { return ''; }
                   3423:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3424:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3425:         $what.=':POST';
1.583     matthew  3426:         # FIXME: Probably ought to escape things....
1.800     albertel 3427: 	foreach my $key (keys(%env)) {
                   3428:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3429:                 my $formitem = $1;
                   3430:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3431:                     $what.=':'.$formitem.'='.$env{$key};
                   3432:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3433:                     $what.=':'.$formitem.'='.$env{$key};
                   3434:                 }
1.158     www      3435:             }
1.191     harris41 3436:         }
1.583     matthew  3437:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3438:         # FIXME: We should not be depending on a form parameter that someone
                   3439:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3440:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3441:             $what.= ':POST';
                   3442:             # FIXME: Probably ought to escape things....
                   3443:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3444:                                  'crsdiscuss') {
1.620     albertel 3445:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3446:             }
                   3447:         }
1.158     www      3448:     }
                   3449:     &courselog($what);
1.149     www      3450: }
                   3451: 
1.185     www      3452: sub countacc {
                   3453:     my $url=&declutter(shift);
1.458     matthew  3454:     return if (! defined($url) || $url eq '');
1.620     albertel 3455:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3456: #
                   3457: # Mark that this url was used in this course
                   3458: #
1.620     albertel 3459:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3460: #
                   3461: # Increase the access count for this resource in this child process
                   3462: #
1.281     www      3463:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3464:     $accesshash{$key}++;
1.185     www      3465: }
1.349     www      3466: 
1.361     www      3467: sub linklog {
                   3468:     my ($from,$to)=@_;
                   3469:     $from=&declutter($from);
                   3470:     $to=&declutter($to);
                   3471:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3472:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3473: }
1.1160    www      3474: 
                   3475: sub statslog {
                   3476:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3477:     if ($users<2) { return; }
                   3478:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3479:             'course'       => $env{'request.course.id'},
                   3480:             'sections'     => '"all"',
                   3481:             'num_students' => $users,
                   3482:             'part'         => $part,
                   3483:             'symb'         => $symb,
                   3484:             'mean_tries'   => $av_attempts,
                   3485:             'deg_of_diff'  => $degdiff});
                   3486:     foreach my $key (keys(%dynstore)) {
                   3487:         $accesshash{$key}=$dynstore{$key};
                   3488:     }
                   3489: }
1.361     www      3490:   
1.349     www      3491: sub userrolelog {
                   3492:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169  ! droeschl 3493:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3494:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3495:        $userrolehash
                   3496:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3497:                     =$tend.':'.$tstart;
1.662     raeburn  3498:     }
1.1169  ! droeschl 3499:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3500:        $userrolehash
                   3501:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3502:                     =$tend.':'.$tstart;
                   3503:     }
1.1169  ! droeschl 3504:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3505:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3506:        $domainrolehash
                   3507:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3508:                     = $tend.':'.$tstart;
                   3509:     }
1.351     www      3510: }
                   3511: 
1.957     raeburn  3512: sub courserolelog {
                   3513:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3514:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3515:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3516:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3517:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3518:         ($trole eq 'co')) {
1.957     raeburn  3519:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3520:             my $cdom = $1;
                   3521:             my $cnum = $2;
                   3522:             my $sec = $3;
                   3523:             my $namespace = 'rolelog';
                   3524:             my %storehash = (
                   3525:                                role    => $trole,
                   3526:                                start   => $tstart,
                   3527:                                end     => $tend,
                   3528:                                selfenroll => $selfenroll,
                   3529:                                context    => $context,
                   3530:                             );
                   3531:             if ($trole eq 'gr') {
                   3532:                 $namespace = 'groupslog';
                   3533:                 $storehash{'group'} = $sec;
                   3534:             } else {
                   3535:                 $storehash{'section'} = $sec;
                   3536:             }
                   3537:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3538:             if (($trole ne 'st') || ($sec ne '')) {
                   3539:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3540:             }
1.957     raeburn  3541:         }
                   3542:     }
                   3543:     return;
                   3544: }
                   3545: 
1.351     www      3546: sub get_course_adv_roles {
1.948     raeburn  3547:     my ($cid,$codes) = @_;
1.620     albertel 3548:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3549:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3550:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3551:     my %nothide=();
1.800     albertel 3552:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3553:         if ($user !~ /:/) {
                   3554: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3555:         } else {
                   3556:             $nothide{$user}=1;
                   3557:         }
1.470     www      3558:     }
1.351     www      3559:     my %returnhash=();
                   3560:     my %dumphash=
                   3561:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3562:     my $now=time;
1.997     raeburn  3563:     my %privileged;
1.1000    raeburn  3564:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3565: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3566:         if (($tstart) && ($tstart<0)) { next; }
                   3567:         if (($tend) && ($tend<$now)) { next; }
                   3568:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3569:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3570: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3571:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3572:             my %dompersonnel =
1.998     raeburn  3573:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3574:             $privileged{$domain} = {};
                   3575:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3576:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3577:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3578:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3579:                         $privileged{$udom}{$uname} = 1;
                   3580:                     }
                   3581:                 }
                   3582:             }
                   3583:         }
                   3584:         if ((exists($privileged{$domain}{$username})) && 
                   3585:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3586: 	if ($role eq 'cr') { next; }
1.948     raeburn  3587:         if ($codes) {
                   3588:             if ($section) { $role .= ':'.$section; }
                   3589:             if ($returnhash{$role}) {
                   3590:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3591:             } else {
                   3592:                 $returnhash{$role}=$username.':'.$domain;
                   3593:             }
1.351     www      3594:         } else {
1.988     raeburn  3595:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3596:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3597:             if ($returnhash{$key}) {
                   3598: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3599:             } else {
                   3600:                 $returnhash{$key}=$username.':'.$domain;
                   3601:             }
1.351     www      3602:         }
1.948     raeburn  3603:     }
1.400     www      3604:     return %returnhash;
                   3605: }
                   3606: 
                   3607: sub get_my_roles {
1.937     raeburn  3608:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3609:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3610:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3611:     my (%dumphash,%nothide);
1.1086    raeburn  3612:     if ($context eq 'userroles') {
1.1166    raeburn  3613:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3614:     } else {
                   3615:         %dumphash=
1.400     www      3616:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3617:         if ($hidepriv) {
                   3618:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3619:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3620:                 if ($user !~ /:/) {
                   3621:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3622:                 } else {
                   3623:                     $nothide{$user} = 1;
                   3624:                 }
                   3625:             }
                   3626:         }
1.858     raeburn  3627:     }
1.400     www      3628:     my %returnhash=();
                   3629:     my $now=time;
1.999     raeburn  3630:     my %privileged;
1.800     albertel 3631:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3632:         my ($role,$tend,$tstart);
                   3633:         if ($context eq 'userroles') {
1.1149    raeburn  3634:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3635: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3636:         } else {
                   3637:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3638:         }
1.400     www      3639:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3640:         my $status = 'active';
1.939     raeburn  3641:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3642:             $status = 'previous';
                   3643:         } 
                   3644:         if (($tstart) && ($now<$tstart)) {
                   3645:             $status = 'future';
                   3646:         }
                   3647:         if (ref($types) eq 'ARRAY') {
                   3648:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3649:                 next;
                   3650:             } 
                   3651:         } else {
                   3652:             if ($status ne 'active') {
                   3653:                 next;
                   3654:             }
                   3655:         }
1.867     raeburn  3656:         my ($rolecode,$username,$domain,$section,$area);
                   3657:         if ($context eq 'userroles') {
                   3658:             ($area,$rolecode) = split(/_/,$entry);
                   3659:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3660:         } else {
                   3661:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3662:         }
1.832     raeburn  3663:         if (ref($roledoms) eq 'ARRAY') {
                   3664:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3665:                 next;
                   3666:             }
                   3667:         }
                   3668:         if (ref($roles) eq 'ARRAY') {
                   3669:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3670:                 if ($role =~ /^cr\//) {
                   3671:                     if (!grep(/^cr$/,@{$roles})) {
                   3672:                         next;
                   3673:                     }
1.1104    raeburn  3674:                 } elsif ($role =~ /^gr\//) {
                   3675:                     if (!grep(/^gr$/,@{$roles})) {
                   3676:                         next;
                   3677:                     }
1.922     raeburn  3678:                 } else {
                   3679:                     next;
                   3680:                 }
1.832     raeburn  3681:             }
1.867     raeburn  3682:         }
1.937     raeburn  3683:         if ($hidepriv) {
1.999     raeburn  3684:             if ($context eq 'userroles') {
                   3685:                 if ((&privileged($username,$domain)) &&
                   3686:                     (!$nothide{$username.':'.$domain})) {
                   3687:                     next;
                   3688:                 }
                   3689:             } else {
                   3690:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3691:                     my %dompersonnel =
                   3692:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3693:                     $privileged{$domain} = {};
                   3694:                     if (keys(%dompersonnel)) {
                   3695:                         foreach my $server (keys(%dompersonnel)) {
                   3696:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3697:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3698:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3699:                                     $privileged{$udom}{$uname} = $trole;
                   3700:                                 }
                   3701:                             }
                   3702:                         }
                   3703:                     }
                   3704:                 }
                   3705:                 if (exists($privileged{$domain}{$username})) {
                   3706:                     if (!$nothide{$username.':'.$domain}) {
                   3707:                         next;
                   3708:                     }
                   3709:                 }
1.937     raeburn  3710:             }
                   3711:         }
1.933     raeburn  3712:         if ($withsec) {
                   3713:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3714:                 $tstart.':'.$tend;
                   3715:         } else {
                   3716:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3717:         }
1.832     raeburn  3718:     }
1.373     www      3719:     return %returnhash;
1.399     www      3720: }
                   3721: 
                   3722: # ----------------------------------------------------- Frontpage Announcements
                   3723: #
                   3724: #
                   3725: 
                   3726: sub postannounce {
                   3727:     my ($server,$text)=@_;
1.844     albertel 3728:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3729:     unless ($text=~/\w/) { $text=''; }
                   3730:     return &reply('setannounce:'.&escape($text),$server);
                   3731: }
                   3732: 
                   3733: sub getannounce {
1.448     albertel 3734: 
                   3735:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3736: 	my $announcement='';
1.800     albertel 3737: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3738: 	close($fh);
1.399     www      3739: 	if ($announcement=~/\w/) { 
                   3740: 	    return 
                   3741:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3742:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3743: 	} else {
                   3744: 	    return '';
                   3745: 	}
                   3746:     } else {
                   3747: 	return '';
                   3748:     }
1.351     www      3749: }
1.353     www      3750: 
                   3751: # ---------------------------------------------------------- Course ID routines
                   3752: # Deal with domain's nohist_courseid.db files
                   3753: #
                   3754: 
                   3755: sub courseidput {
1.921     raeburn  3756:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3757:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3758:     my $outcome;
                   3759:     if ($caller eq 'timeonly') {
                   3760:         my $cids = '';
                   3761:         foreach my $item (keys(%$storehash)) {
                   3762:             $cids.=&escape($item).'&';
                   3763:         }
                   3764:         $cids=~s/\&$//;
                   3765:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3766:                           $coursehome);       
                   3767:     } else {
                   3768:         my $items = '';
                   3769:         foreach my $item (keys(%$storehash)) {
                   3770:             $items.= &escape($item).'='.
                   3771:                      &freeze_escape($$storehash{$item}).'&';
                   3772:         }
                   3773:         $items=~s/\&$//;
                   3774:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3775:                           $coursehome);
1.918     raeburn  3776:     }
                   3777:     if ($outcome eq 'unknown_cmd') {
                   3778:         my $what;
                   3779:         foreach my $cid (keys(%$storehash)) {
                   3780:             $what .= &escape($cid).'=';
1.921     raeburn  3781:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3782:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3783:             }
                   3784:             $what =~ s/\:$/&/;
                   3785:         }
                   3786:         $what =~ s/\&$//;  
                   3787:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3788:     } else {
                   3789:         return $outcome;
                   3790:     }
1.353     www      3791: }
                   3792: 
                   3793: sub courseiddump {
1.921     raeburn  3794:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3795:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3796:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3797:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3798:     my $as_hash = 1;
                   3799:     my %returnhash;
                   3800:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3801:     my %libserv = &all_library();
                   3802:     foreach my $tryserver (keys(%libserv)) {
                   3803:         if ( (  $hostidflag == 1 
                   3804: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3805: 	     || (!defined($hostidflag)) ) {
                   3806: 
1.918     raeburn  3807: 	    if (($domfilter eq '') ||
                   3808: 		(&host_domain($tryserver) eq $domfilter)) {
                   3809:                 my $rep = 
                   3810:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3811:                          $sincefilter.':'.&escape($descfilter).':'.
                   3812:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3813:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3814:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3815:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3816:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3817:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3818:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3819:                          &escape($creationcontext).':'.$domcloner,
                   3820:                          $tryserver);
1.918     raeburn  3821:                 my @pairs=split(/\&/,$rep);
                   3822:                 foreach my $item (@pairs) {
                   3823:                     my ($key,$value)=split(/\=/,$item,2);
                   3824:                     $key = &unescape($key);
                   3825:                     next if ($key =~ /^error: 2 /);
                   3826:                     my $result = &thaw_unescape($value);
                   3827:                     if (ref($result) eq 'HASH') {
                   3828:                         $returnhash{$key}=$result;
                   3829:                     } else {
1.921     raeburn  3830:                         my @responses = split(/:/,$value);
                   3831:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3832:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3833:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3834:                         }
1.1008    raeburn  3835:                     }
1.353     www      3836:                 }
                   3837:             }
                   3838:         }
                   3839:     }
                   3840:     return %returnhash;
                   3841: }
                   3842: 
1.1055    raeburn  3843: sub courselastaccess {
                   3844:     my ($cdom,$cnum,$hostidref) = @_;
                   3845:     my %returnhash;
                   3846:     if ($cdom && $cnum) {
                   3847:         my $chome = &homeserver($cnum,$cdom);
                   3848:         if ($chome ne 'no_host') {
                   3849:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3850:             &extract_lastaccess(\%returnhash,$rep);
                   3851:         }
                   3852:     } else {
                   3853:         if (!$cdom) { $cdom=''; }
                   3854:         my %libserv = &all_library();
                   3855:         foreach my $tryserver (keys(%libserv)) {
                   3856:             if (ref($hostidref) eq 'ARRAY') {
                   3857:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3858:             } 
                   3859:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3860:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3861:                 &extract_lastaccess(\%returnhash,$rep);
                   3862:             }
                   3863:         }
                   3864:     }
                   3865:     return %returnhash;
                   3866: }
                   3867: 
                   3868: sub extract_lastaccess {
                   3869:     my ($returnhash,$rep) = @_;
                   3870:     if (ref($returnhash) eq 'HASH') {
                   3871:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3872:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3873:                  $rep eq '') {
                   3874:             my @pairs=split(/\&/,$rep);
                   3875:             foreach my $item (@pairs) {
                   3876:                 my ($key,$value)=split(/\=/,$item,2);
                   3877:                 $key = &unescape($key);
                   3878:                 next if ($key =~ /^error: 2 /);
                   3879:                 $returnhash->{$key} = &thaw_unescape($value);
                   3880:             }
                   3881:         }
                   3882:     }
                   3883:     return;
                   3884: }
                   3885: 
1.658     raeburn  3886: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3887: 
                   3888: sub dcmailput {
1.685     raeburn  3889:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3890:     my $status = &Apache::lonnet::critical(
1.740     www      3891:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3892:        &escape($message),$server);
1.662     raeburn  3893:     return $status;
                   3894: }
                   3895: 
1.658     raeburn  3896: sub dcmaildump {
                   3897:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3898:     my %returnhash=();
1.846     albertel 3899: 
                   3900:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3901:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3902:                                                          &escape($enddate).':';
                   3903: 	my @esc_senders=map { &escape($_)} @$senders;
                   3904: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3905: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3906:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3907:             if (($key) && ($value)) {
                   3908:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3909:             }
                   3910:         }
                   3911:     }
                   3912:     return %returnhash;
                   3913: }
1.662     raeburn  3914: # ---------------------------------------------------------- Domain roles
                   3915: 
                   3916: sub get_domain_roles {
                   3917:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3918:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3919:         $startdate = '.';
                   3920:     }
1.1018    raeburn  3921:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3922:         $enddate = '.';
                   3923:     }
1.922     raeburn  3924:     my $rolelist;
                   3925:     if (ref($roles) eq 'ARRAY') {
                   3926:         $rolelist = join(':',@{$roles});
                   3927:     }
1.662     raeburn  3928:     my %personnel = ();
1.841     albertel 3929: 
                   3930:     my %servers = &get_servers($dom,'library');
                   3931:     foreach my $tryserver (keys(%servers)) {
                   3932: 	%{$personnel{$tryserver}}=();
                   3933: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3934: 					    &escape($startdate).':'.
                   3935: 					    &escape($enddate).':'.
                   3936: 					    &escape($rolelist), $tryserver))) {
                   3937: 	    my ($key,$value) = split(/\=/,$line,2);
                   3938: 	    if (($key) && ($value)) {
                   3939: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3940: 	    }
                   3941: 	}
1.662     raeburn  3942:     }
                   3943:     return %personnel;
                   3944: }
1.658     raeburn  3945: 
1.1057    www      3946: # ----------------------------------------------------------- Interval timing 
1.149     www      3947: 
1.1153    www      3948: {
                   3949: # Caches needed for speedup of navmaps
                   3950: # We don't want to cache this for very long at all (5 seconds at most)
                   3951: # 
                   3952: # The user for whom we cache
                   3953: my $cachedkey='';
                   3954: # The cached times for this user
                   3955: my %cachedtimes=();
                   3956: # When this was last done
                   3957: my $cachedtime=();
                   3958: 
                   3959: sub load_all_first_access {
1.1154    raeburn  3960:     my ($uname,$udom)=@_;
1.1156    www      3961:     if (($cachedkey eq $uname.':'.$udom) &&
1.1154    raeburn  3962:         (abs($cachedtime-time)<5)) {
                   3963:         return;
                   3964:     }
                   3965:     $cachedtime=time;
                   3966:     $cachedkey=$uname.':'.$udom;
                   3967:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      3968: }
                   3969: 
1.504     albertel 3970: sub get_first_access {
1.1162    raeburn  3971:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 3972:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3973:     if ($argsymb) { $symb=$argsymb; }
                   3974:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  3975:     if ($argmap) { $map = $argmap; }
1.926     albertel 3976:     if ($type eq 'course') {
                   3977: 	$res='course';
                   3978:     } elsif ($type eq 'map') {
1.588     albertel 3979: 	$res=&symbread($map);
                   3980:     } else {
                   3981: 	$res=$symb;
                   3982:     }
1.1153    www      3983:     &load_all_first_access($uname,$udom);
                   3984:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 3985: }
                   3986: 
                   3987: sub set_first_access {
1.1162    raeburn  3988:     my ($type,$interval)=@_;
1.790     albertel 3989:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3990:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3991:     if ($type eq 'course') {
                   3992: 	$res='course';
                   3993:     } elsif ($type eq 'map') {
1.588     albertel 3994: 	$res=&symbread($map);
                   3995:     } else {
                   3996: 	$res=$symb;
                   3997:     }
1.1153    www      3998:     $cachedkey='';
1.1162    raeburn  3999:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4000:     if (!$firstaccess) {
1.1162    raeburn  4001:         my $start = time;
                   4002: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4003:                           $udom,$uname);
                   4004:         if ($putres eq 'ok') {
                   4005:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4006:                  $udom,$uname); 
                   4007:             &appenv(
                   4008:                      {
                   4009:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4010:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4011:                      }
                   4012:                   );
                   4013:         }
                   4014:         return $putres;
1.505     albertel 4015:     }
                   4016:     return 'already_set';
1.504     albertel 4017: }
1.1153    www      4018: }
1.110     www      4019: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4020: 
                   4021: sub expirespread {
                   4022:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4023:     my $cid=$env{'request.course.id'}; 
1.110     www      4024:     if ($cid) {
                   4025:        my $now=time;
                   4026:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4027:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4028:                             $env{'course.'.$cid.'.num'}.
1.110     www      4029: 	        	    ':nohist_expirationdates:'.
                   4030:                             &escape($key).'='.$now,
1.620     albertel 4031:                             $env{'course.'.$cid.'.home'})
1.110     www      4032:     }
                   4033:     return 'ok';
1.14      www      4034: }
                   4035: 
1.109     www      4036: # ----------------------------------------------------- Devalidate Spreadsheets
                   4037: 
                   4038: sub devalidate {
1.325     www      4039:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4040:     my $cid=$env{'request.course.id'}; 
1.109     www      4041:     if ($cid) {
1.391     matthew  4042:         # delete the stored spreadsheets for
                   4043:         # - the student level sheet of this user in course's homespace
                   4044:         # - the assessment level sheet for this resource 
                   4045:         #   for this user in user's homespace
1.553     albertel 4046: 	# - current conditional state info
1.325     www      4047: 	my $key=$uname.':'.$udom.':';
1.109     www      4048:         my $status=
1.299     matthew  4049: 	    &del('nohist_calculatedsheets',
1.391     matthew  4050: 		 [$key.'studentcalc:'],
1.620     albertel 4051: 		 $env{'course.'.$cid.'.domain'},
                   4052: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4053: 		.' '.
                   4054: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4055: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4056:         unless ($status eq 'ok ok') {
                   4057:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4058:                     $uname.' at '.$udom.' for '.
1.109     www      4059: 		    $symb.': '.$status);
1.133     albertel 4060:         }
1.553     albertel 4061: 	&delenv('user.state.'.$cid);
1.109     www      4062:     }
                   4063: }
                   4064: 
1.265     albertel 4065: sub get_scalar {
                   4066:     my ($string,$end) = @_;
                   4067:     my $value;
                   4068:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4069: 	$value = $1;
                   4070:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4071: 	$value = $1;
                   4072:     }
                   4073:     return &unescape($value);
                   4074: }
                   4075: 
                   4076: sub array2str {
                   4077:   my (@array) = @_;
                   4078:   my $result=&arrayref2str(\@array);
                   4079:   $result=~s/^__ARRAY_REF__//;
                   4080:   $result=~s/__END_ARRAY_REF__$//;
                   4081:   return $result;
                   4082: }
                   4083: 
1.204     albertel 4084: sub arrayref2str {
                   4085:   my ($arrayref) = @_;
1.265     albertel 4086:   my $result='__ARRAY_REF__';
1.204     albertel 4087:   foreach my $elem (@$arrayref) {
1.265     albertel 4088:     if(ref($elem) eq 'ARRAY') {
                   4089:       $result.=&arrayref2str($elem).'&';
                   4090:     } elsif(ref($elem) eq 'HASH') {
                   4091:       $result.=&hashref2str($elem).'&';
                   4092:     } elsif(ref($elem)) {
                   4093:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4094:     } else {
                   4095:       $result.=&escape($elem).'&';
                   4096:     }
                   4097:   }
                   4098:   $result=~s/\&$//;
1.265     albertel 4099:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4100:   return $result;
                   4101: }
                   4102: 
1.168     albertel 4103: sub hash2str {
1.204     albertel 4104:   my (%hash) = @_;
                   4105:   my $result=&hashref2str(\%hash);
1.265     albertel 4106:   $result=~s/^__HASH_REF__//;
                   4107:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4108:   return $result;
                   4109: }
                   4110: 
                   4111: sub hashref2str {
                   4112:   my ($hashref)=@_;
1.265     albertel 4113:   my $result='__HASH_REF__';
1.800     albertel 4114:   foreach my $key (sort(keys(%$hashref))) {
                   4115:     if (ref($key) eq 'ARRAY') {
                   4116:       $result.=&arrayref2str($key).'=';
                   4117:     } elsif (ref($key) eq 'HASH') {
                   4118:       $result.=&hashref2str($key).'=';
                   4119:     } elsif (ref($key)) {
1.265     albertel 4120:       $result.='=';
1.800     albertel 4121:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4122:     } else {
1.1132    raeburn  4123: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4124:     }
                   4125: 
1.800     albertel 4126:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4127:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4128:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4129:       $result.=&hashref2str($hashref->{$key}).'&';
                   4130:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4131:        $result.='&';
1.800     albertel 4132:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4133:     } else {
1.800     albertel 4134:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4135:     }
                   4136:   }
1.168     albertel 4137:   $result=~s/\&$//;
1.265     albertel 4138:   $result .= '__END_HASH_REF__';
1.168     albertel 4139:   return $result;
                   4140: }
                   4141: 
                   4142: sub str2hash {
1.265     albertel 4143:     my ($string)=@_;
                   4144:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4145:     return %$hash;
                   4146: }
                   4147: 
                   4148: sub str2hashref {
1.168     albertel 4149:   my ($string) = @_;
1.265     albertel 4150: 
                   4151:   my %hash;
                   4152: 
                   4153:   if($string !~ /^__HASH_REF__/) {
                   4154:       if (! ($string eq '' || !defined($string))) {
                   4155: 	  $hash{'error'}='Not hash reference';
                   4156:       }
                   4157:       return (\%hash, $string);
                   4158:   }
                   4159: 
                   4160:   $string =~ s/^__HASH_REF__//;
                   4161: 
                   4162:   while($string !~ /^__END_HASH_REF__/) {
                   4163:       #key
                   4164:       my $key='';
                   4165:       if($string =~ /^__HASH_REF__/) {
                   4166:           ($key, $string)=&str2hashref($string);
                   4167:           if(defined($key->{'error'})) {
                   4168:               $hash{'error'}='Bad data';
                   4169:               return (\%hash, $string);
                   4170:           }
                   4171:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4172:           ($key, $string)=&str2arrayref($string);
                   4173:           if($key->[0] eq 'Array reference error') {
                   4174:               $hash{'error'}='Bad data';
                   4175:               return (\%hash, $string);
                   4176:           }
                   4177:       } else {
                   4178:           $string =~ s/^(.*?)=//;
1.267     albertel 4179: 	  $key=&unescape($1);
1.265     albertel 4180:       }
                   4181:       $string =~ s/^=//;
                   4182: 
                   4183:       #value
                   4184:       my $value='';
                   4185:       if($string =~ /^__HASH_REF__/) {
                   4186:           ($value, $string)=&str2hashref($string);
                   4187:           if(defined($value->{'error'})) {
                   4188:               $hash{'error'}='Bad data';
                   4189:               return (\%hash, $string);
                   4190:           }
                   4191:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4192:           ($value, $string)=&str2arrayref($string);
                   4193:           if($value->[0] eq 'Array reference error') {
                   4194:               $hash{'error'}='Bad data';
                   4195:               return (\%hash, $string);
                   4196:           }
                   4197:       } else {
                   4198: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4199:       }
                   4200:       $string =~ s/^&//;
                   4201: 
                   4202:       $hash{$key}=$value;
1.204     albertel 4203:   }
1.265     albertel 4204: 
                   4205:   $string =~ s/^__END_HASH_REF__//;
                   4206: 
                   4207:   return (\%hash, $string);
1.204     albertel 4208: }
                   4209: 
                   4210: sub str2array {
1.265     albertel 4211:     my ($string)=@_;
                   4212:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4213:     return @$array;
                   4214: }
                   4215: 
                   4216: sub str2arrayref {
1.204     albertel 4217:   my ($string) = @_;
1.265     albertel 4218:   my @array;
                   4219: 
                   4220:   if($string !~ /^__ARRAY_REF__/) {
                   4221:       if (! ($string eq '' || !defined($string))) {
                   4222: 	  $array[0]='Array reference error';
                   4223:       }
                   4224:       return (\@array, $string);
                   4225:   }
                   4226: 
                   4227:   $string =~ s/^__ARRAY_REF__//;
                   4228: 
                   4229:   while($string !~ /^__END_ARRAY_REF__/) {
                   4230:       my $value='';
                   4231:       if($string =~ /^__HASH_REF__/) {
                   4232:           ($value, $string)=&str2hashref($string);
                   4233:           if(defined($value->{'error'})) {
                   4234:               $array[0] ='Array reference error';
                   4235:               return (\@array, $string);
                   4236:           }
                   4237:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4238:           ($value, $string)=&str2arrayref($string);
                   4239:           if($value->[0] eq 'Array reference error') {
                   4240:               $array[0] ='Array reference error';
                   4241:               return (\@array, $string);
                   4242:           }
                   4243:       } else {
                   4244: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4245:       }
                   4246:       $string =~ s/^&//;
                   4247: 
                   4248:       push(@array, $value);
1.191     harris41 4249:   }
1.265     albertel 4250: 
                   4251:   $string =~ s/^__END_ARRAY_REF__//;
                   4252: 
                   4253:   return (\@array, $string);
1.168     albertel 4254: }
                   4255: 
1.167     albertel 4256: # -------------------------------------------------------------------Temp Store
                   4257: 
1.168     albertel 4258: sub tmpreset {
                   4259:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4260:   if (!$symb) {
                   4261:     $symb=&symbread();
1.620     albertel 4262:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4263:   }
                   4264:   $symb=escape($symb);
                   4265: 
1.620     albertel 4266:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4267:   $namespace=~s/\//\_/g;
                   4268:   $namespace=~s/\W//g;
                   4269: 
1.620     albertel 4270:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4271:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4272:   if ($domain eq 'public' && $stuname eq 'public') {
                   4273:       $stuname=$ENV{'REMOTE_ADDR'};
                   4274:   }
1.1117    foxr     4275:   my $path=LONCAPA::tempdir();
1.168     albertel 4276:   my %hash;
                   4277:   if (tie(%hash,'GDBM_File',
                   4278: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4279: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4280:     foreach my $key (keys(%hash)) {
1.180     albertel 4281:       if ($key=~ /:$symb/) {
1.168     albertel 4282: 	delete($hash{$key});
                   4283:       }
                   4284:     }
                   4285:   }
                   4286: }
                   4287: 
1.167     albertel 4288: sub tmpstore {
1.168     albertel 4289:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4290: 
                   4291:   if (!$symb) {
                   4292:     $symb=&symbread();
1.620     albertel 4293:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4294:   }
                   4295:   $symb=escape($symb);
                   4296: 
                   4297:   if (!$namespace) {
                   4298:     # I don't think we would ever want to store this for a course.
                   4299:     # it seems this will only be used if we don't have a course.
1.620     albertel 4300:     #$namespace=$env{'request.course.id'};
1.168     albertel 4301:     #if (!$namespace) {
1.620     albertel 4302:       $namespace=$env{'request.state'};
1.168     albertel 4303:     #}
                   4304:   }
                   4305:   $namespace=~s/\//\_/g;
                   4306:   $namespace=~s/\W//g;
1.620     albertel 4307:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4308:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4309:   if ($domain eq 'public' && $stuname eq 'public') {
                   4310:       $stuname=$ENV{'REMOTE_ADDR'};
                   4311:   }
1.168     albertel 4312:   my $now=time;
                   4313:   my %hash;
1.1117    foxr     4314:   my $path=LONCAPA::tempdir();
1.168     albertel 4315:   if (tie(%hash,'GDBM_File',
                   4316: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4317: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4318:     $hash{"version:$symb"}++;
                   4319:     my $version=$hash{"version:$symb"};
                   4320:     my $allkeys=''; 
                   4321:     foreach my $key (keys(%$storehash)) {
                   4322:       $allkeys.=$key.':';
1.591     albertel 4323:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4324:     }
                   4325:     $hash{"$version:$symb:timestamp"}=$now;
                   4326:     $allkeys.='timestamp';
                   4327:     $hash{"$version:keys:$symb"}=$allkeys;
                   4328:     if (untie(%hash)) {
                   4329:       return 'ok';
                   4330:     } else {
                   4331:       return "error:$!";
                   4332:     }
                   4333:   } else {
                   4334:     return "error:$!";
                   4335:   }
                   4336: }
1.167     albertel 4337: 
1.168     albertel 4338: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4339: 
1.168     albertel 4340: sub tmprestore {
                   4341:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4342: 
1.168     albertel 4343:   if (!$symb) {
                   4344:     $symb=&symbread();
1.620     albertel 4345:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4346:   }
                   4347:   $symb=escape($symb);
                   4348: 
1.620     albertel 4349:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4350: 
1.620     albertel 4351:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4352:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4353:   if ($domain eq 'public' && $stuname eq 'public') {
                   4354:       $stuname=$ENV{'REMOTE_ADDR'};
                   4355:   }
1.168     albertel 4356:   my %returnhash;
                   4357:   $namespace=~s/\//\_/g;
                   4358:   $namespace=~s/\W//g;
                   4359:   my %hash;
1.1117    foxr     4360:   my $path=LONCAPA::tempdir();
1.168     albertel 4361:   if (tie(%hash,'GDBM_File',
                   4362: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4363: 	  &GDBM_READER(),0640)) {
1.168     albertel 4364:     my $version=$hash{"version:$symb"};
                   4365:     $returnhash{'version'}=$version;
                   4366:     my $scope;
                   4367:     for ($scope=1;$scope<=$version;$scope++) {
                   4368:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4369:       my @keys=split(/:/,$vkeys);
                   4370:       my $key;
                   4371:       $returnhash{"$scope:keys"}=$vkeys;
                   4372:       foreach $key (@keys) {
1.591     albertel 4373: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4374: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4375:       }
                   4376:     }
1.168     albertel 4377:     if (!(untie(%hash))) {
                   4378:       return "error:$!";
                   4379:     }
                   4380:   } else {
                   4381:     return "error:$!";
                   4382:   }
                   4383:   return %returnhash;
1.167     albertel 4384: }
                   4385: 
1.9       www      4386: # ----------------------------------------------------------------------- Store
                   4387: 
                   4388: sub store {
1.124     www      4389:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4390:     my $home='';
                   4391: 
1.168     albertel 4392:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4393: 
1.213     www      4394:     $symb=&symbclean($symb);
1.122     albertel 4395:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4396: 
1.620     albertel 4397:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4398:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4399: 
                   4400:     &devalidate($symb,$stuname,$domain);
1.109     www      4401: 
                   4402:     $symb=escape($symb);
1.187     www      4403:     if (!$namespace) { 
1.620     albertel 4404:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4405:           return ''; 
                   4406:        } 
                   4407:     }
1.620     albertel 4408:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4409: 
                   4410:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4411:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4412: 
1.12      www      4413:     my $namevalue='';
1.800     albertel 4414:     foreach my $key (keys(%$storehash)) {
                   4415:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4416:     }
1.12      www      4417:     $namevalue=~s/\&$//;
1.187     www      4418:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4419:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4420: }
                   4421: 
1.47      www      4422: # -------------------------------------------------------------- Critical Store
                   4423: 
                   4424: sub cstore {
1.124     www      4425:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4426:     my $home='';
                   4427: 
1.168     albertel 4428:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4429: 
1.213     www      4430:     $symb=&symbclean($symb);
1.122     albertel 4431:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4432: 
1.620     albertel 4433:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4434:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4435: 
                   4436:     &devalidate($symb,$stuname,$domain);
1.109     www      4437: 
                   4438:     $symb=escape($symb);
1.187     www      4439:     if (!$namespace) { 
1.620     albertel 4440:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4441:           return ''; 
                   4442:        } 
                   4443:     }
1.620     albertel 4444:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4445: 
                   4446:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4447:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4448: 
1.47      www      4449:     my $namevalue='';
1.800     albertel 4450:     foreach my $key (keys(%$storehash)) {
                   4451:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4452:     }
1.47      www      4453:     $namevalue=~s/\&$//;
1.187     www      4454:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4455:     return critical
                   4456:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4457: }
                   4458: 
1.9       www      4459: # --------------------------------------------------------------------- Restore
                   4460: 
                   4461: sub restore {
1.124     www      4462:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4463:     my $home='';
                   4464: 
1.168     albertel 4465:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4466: 
1.122     albertel 4467:     if (!$symb) {
                   4468:       unless ($symb=escape(&symbread())) { return ''; }
                   4469:     } else {
1.213     www      4470:       $symb=&escape(&symbclean($symb));
1.122     albertel 4471:     }
1.188     www      4472:     if (!$namespace) { 
1.620     albertel 4473:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4474:           return ''; 
                   4475:        } 
                   4476:     }
1.620     albertel 4477:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4478:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4479:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4480:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4481: 
1.12      www      4482:     my %returnhash=();
1.800     albertel 4483:     foreach my $line (split(/\&/,$answer)) {
                   4484: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4485:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4486:     }
1.75      www      4487:     my $version;
                   4488:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4489:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4490:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4491:        }
1.75      www      4492:     }
1.13      www      4493:     return %returnhash;
1.34      www      4494: }
                   4495: 
                   4496: # ---------------------------------------------------------- Course Description
1.1118    foxr     4497: #
                   4498: #  
1.34      www      4499: 
                   4500: sub coursedescription {
1.731     albertel 4501:     my ($courseid,$args)=@_;
1.34      www      4502:     $courseid=~s/^\///;
1.49      www      4503:     $courseid=~s/\_/\//g;
1.34      www      4504:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4505:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4506:     my $normalid=$cdomain.'_'.$cnum;
                   4507:     # need to always cache even if we get errors otherwise we keep 
                   4508:     # trying and trying and trying to get the course description.
                   4509:     my %envhash=();
                   4510:     my %returnhash=();
1.731     albertel 4511:     
                   4512:     my $expiretime=600;
                   4513:     if ($env{'request.course.id'} eq $normalid) {
                   4514: 	$expiretime=120;
                   4515:     }
                   4516: 
                   4517:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4518:     if (!$args->{'freshen_cache'}
                   4519: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4520: 	foreach my $key (keys(%env)) {
                   4521: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4522: 	    my ($setting) = $1;
                   4523: 	    $returnhash{$setting} = $env{$key};
                   4524: 	}
                   4525: 	return %returnhash;
                   4526:     }
                   4527: 
1.1118    foxr     4528:     # get the data again
                   4529: 
1.731     albertel 4530:     if (!$args->{'one_time'}) {
                   4531: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4532:     }
1.811     albertel 4533: 
1.34      www      4534:     if ($chome ne 'no_host') {
1.302     albertel 4535:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4536:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4537: 	   my $username = $env{'user.name'}; # Defult username
                   4538: 	   if(defined $args->{'user'}) {
                   4539: 	       $username = $args->{'user'};
                   4540: 	   }
1.129     albertel 4541:            $returnhash{'home'}= $chome;
                   4542: 	   $returnhash{'domain'} = $cdomain;
                   4543: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4544:            if (!defined($returnhash{'type'})) {
                   4545:                $returnhash{'type'} = 'Course';
                   4546:            }
1.130     albertel 4547:            while (my ($name,$value) = each %returnhash) {
1.53      www      4548:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4549:            }
1.270     www      4550:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4551:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4552: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4553:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4554:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4555:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4556:        }
                   4557:     }
1.731     albertel 4558:     if (!$args->{'one_time'}) {
1.949     raeburn  4559: 	&appenv(\%envhash);
1.731     albertel 4560:     }
1.302     albertel 4561:     return %returnhash;
1.461     www      4562: }
                   4563: 
1.1080    raeburn  4564: sub update_released_required {
                   4565:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4566:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4567:         $cid = $env{'request.course.id'};
                   4568:         $cdom = $env{'course.'.$cid.'.domain'};
                   4569:         $cnum = $env{'course.'.$cid.'.num'};
                   4570:         $chome = $env{'course.'.$cid.'.home'};
                   4571:     }
                   4572:     if ($needsrelease) {
                   4573:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4574:         my $needsupdate;
                   4575:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4576:             $needsupdate = 1;
                   4577:         } else {
                   4578:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4579:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4580:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4581:                 $needsupdate = 1;
                   4582:             }
                   4583:         }
                   4584:         if ($needsupdate) {
                   4585:             my %needshash = (
                   4586:                              'internal.releaserequired' => $needsrelease,
                   4587:                             );
                   4588:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4589:             if ($putresult eq 'ok') {
                   4590:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4591:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4592:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4593:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4594:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4595:                 }
                   4596:             }
                   4597:         }
                   4598:     }
                   4599:     return;
                   4600: }
                   4601: 
1.461     www      4602: # -------------------------------------------------See if a user is privileged
                   4603: 
                   4604: sub privileged {
                   4605:     my ($username,$domain)=@_;
                   4606:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4607: 			&homeserver($username,$domain));
1.1033    raeburn  4608:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4609:         ($rolesdump =~ /^error:/)) {
                   4610:         return 0;
                   4611:     }
1.461     www      4612:     my $now=time;
                   4613:     if ($rolesdump ne '') {
1.800     albertel 4614:         foreach my $entry (split(/&/,$rolesdump)) {
                   4615: 	    if ($entry!~/^rolesdef_/) {
                   4616: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4617: 		$area=~s/\_\w\w$//;
                   4618: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4619: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4620: 		    my $active=1;
                   4621: 		    if ($tend) {
                   4622: 			if ($tend<$now) { $active=0; }
                   4623: 		    }
                   4624: 		    if ($tstart) {
                   4625: 			if ($tstart>$now) { $active=0; }
                   4626: 		    }
                   4627: 		    if ($active) { return 1; }
                   4628: 		}
                   4629: 	    }
                   4630: 	}
                   4631:     }
                   4632:     return 0;
1.9       www      4633: }
1.1       albertel 4634: 
1.103     harris41 4635: # -------------------------------------------------------- Get user privileges
1.11      www      4636: 
                   4637: sub rolesinit {
1.1169  ! droeschl 4638:     my ($domain, $username) = @_;
        !          4639:     my %userroles = ('user.login.time' => time);
        !          4640:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
        !          4641: 
        !          4642:     # firstaccess and timerinterval are related to timed maps/resources. 
        !          4643:     # also, blocking can be triggered by an activating timer
        !          4644:     # it's saved in the user's %env.
        !          4645:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
        !          4646:     my %timerinterval = &dump('timerinterval', $domain, $username);
        !          4647:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
        !          4648:         %timerintchk, %timerintenv);
        !          4649: 
1.1162    raeburn  4650:     foreach my $key (keys(%firstaccess)) {
1.1169  ! droeschl 4651:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4652:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4653:     }
1.1169  ! droeschl 4654: 
1.1162    raeburn  4655:     foreach my $key (keys(%timerinterval)) {
                   4656:         my ($cid,$rest) = split(/\0/,$key);
                   4657:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4658:     }
1.1169  ! droeschl 4659: 
1.11      www      4660:     my %allroles=();
1.1162    raeburn  4661:     my %allgroups=();
1.11      www      4662: 
1.1169  ! droeschl 4663:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
        !          4664:         my $role = $rolesdump{$area};
        !          4665:         $area =~ s/\_\w\w$//;
        !          4666: 
        !          4667:         my ($trole, $tend, $tstart, $group_privs);
        !          4668: 
        !          4669:         if ($role =~ /^cr/) {
        !          4670:         # Custom role, defined by a user 
        !          4671:         # e.g., user.role.cr/msu/smith/mynewrole
        !          4672:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
        !          4673:                 $trole = $1;
        !          4674:                 ($tend, $tstart) = split('_', $2);
        !          4675:             } else {
        !          4676:                 $trole = $role;
        !          4677:             }
        !          4678:         } elsif ($role =~ m|^gr/|) {
        !          4679:         # Role of member in a group, defined within a course/community
        !          4680:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
        !          4681:             ($trole, $tend, $tstart) = split(/_/, $role);
        !          4682:             next if $tstart eq '-1';
        !          4683:             ($trole, $group_privs) = split(/\//, $trole);
        !          4684:             $group_privs = &unescape($group_privs);
        !          4685:         } else {
        !          4686:         # Just a normal role, defined in roles.tab
        !          4687:             ($trole, $tend, $tstart) = split(/_/,$role);
        !          4688:         }
        !          4689: 
        !          4690:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
        !          4691:                  $username);
        !          4692:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
        !          4693: 
        !          4694:         # role expired or not available yet?
        !          4695:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
        !          4696:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
        !          4697: 
        !          4698:         next if $area eq '' or $trole eq '';
        !          4699: 
        !          4700:         my $spec = "$trole.$area";
        !          4701:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
        !          4702: 
        !          4703:         if ($trole =~ /^cr\//) {
        !          4704:         # Custom role, defined by a user
        !          4705:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
        !          4706:         } elsif ($trole eq 'gr') {
        !          4707:         # Role of a member in a group, defined within a course/community
        !          4708:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
        !          4709:             next;
        !          4710:         } else {
        !          4711:         # Normal role, defined in roles.tab
        !          4712:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
        !          4713:         }
        !          4714: 
        !          4715:         my $cid = $tdomain.'_'.$trest;
        !          4716:         unless ($firstaccchk{$cid}) {
        !          4717:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
        !          4718:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
        !          4719:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
        !          4720:                         $coursetimerstarts{$cid}{$item}; 
        !          4721:                 }
        !          4722:             }
        !          4723:             $firstaccchk{$cid} = 1;
        !          4724:         }
        !          4725:         unless ($timerintchk{$cid}) {
        !          4726:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
        !          4727:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
        !          4728:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
        !          4729:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4730:                 }
1.12      www      4731:             }
1.1169  ! droeschl 4732:             $timerintchk{$cid} = 1;
1.191     harris41 4733:         }
1.11      www      4734:     }
1.1169  ! droeschl 4735: 
        !          4736:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
        !          4737:         \%allroles, \%allgroups);
        !          4738:     $env{'user.adv'} = $userroles{'user.adv'};
        !          4739: 
1.1162    raeburn  4740:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4741: }
                   4742: 
1.567     raeburn  4743: sub set_arearole {
                   4744:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4745: # log the associated role with the area
                   4746:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4747:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4748: }
                   4749: 
                   4750: sub custom_roleprivs {
                   4751:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4752:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4753:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4754:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4755:         my ($rdummy,$roledef)=
                   4756:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4757:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4758:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4759:             if (defined($syspriv)) {
1.1043    raeburn  4760:                 if ($trest =~ /^$match_community$/) {
                   4761:                     $syspriv =~ s/bre\&S//; 
                   4762:                 }
1.567     raeburn  4763:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4764:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4765:             }
                   4766:             if ($tdomain ne '') {
                   4767:                 if (defined($dompriv)) {
                   4768:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4769:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4770:                 }
                   4771:                 if (($trest ne '') && (defined($coursepriv))) {
                   4772:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4773:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4774:                 }
                   4775:             }
                   4776:         }
                   4777:     }
                   4778: }
                   4779: 
1.678     raeburn  4780: sub group_roleprivs {
                   4781:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4782:     my $access = 1;
                   4783:     my $now = time;
                   4784:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4785:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4786:     if ($access) {
1.811     albertel 4787:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4788:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4789:     }
                   4790: }
1.567     raeburn  4791: 
                   4792: sub standard_roleprivs {
                   4793:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4794:     if (defined($pr{$trole.':s'})) {
                   4795:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4796:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4797:     }
                   4798:     if ($tdomain ne '') {
                   4799:         if (defined($pr{$trole.':d'})) {
                   4800:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4801:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4802:         }
                   4803:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4804:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4805:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4806:         }
                   4807:     }
                   4808: }
                   4809: 
                   4810: sub set_userprivs {
1.1064    raeburn  4811:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4812:     my $author=0;
                   4813:     my $adv=0;
1.678     raeburn  4814:     my %grouproles = ();
                   4815:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4816:         my @groupkeys; 
1.1000    raeburn  4817:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4818:             push(@groupkeys,$role);
                   4819:         }
                   4820:         if (ref($groups_roles) eq 'HASH') {
                   4821:             foreach my $key (keys(%{$groups_roles})) {
                   4822:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4823:                     push(@groupkeys,$key);
                   4824:                 }
                   4825:             }
                   4826:         }
                   4827:         if (@groupkeys > 0) {
                   4828:             foreach my $role (@groupkeys) {
                   4829:                 my ($trole,$area,$sec,$extendedarea);
                   4830:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4831:                     $trole = $1;
                   4832:                     $area = $2;
                   4833:                     $sec = $3;
                   4834:                     $extendedarea = $area.$sec;
                   4835:                     if (exists($$allgroups{$area})) {
                   4836:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4837:                             my $spec = $trole.'.'.$extendedarea;
                   4838:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4839:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4840:                         }
1.678     raeburn  4841:                     }
                   4842:                 }
                   4843:             }
                   4844:         }
                   4845:     }
1.800     albertel 4846:     foreach my $group (keys(%grouproles)) {
                   4847:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4848:     }
1.800     albertel 4849:     foreach my $role (keys(%{$allroles})) {
                   4850:         my %thesepriv;
1.941     raeburn  4851:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4852:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4853:             if ($item ne '') {
                   4854:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4855:                 if ($restrictions eq '') {
                   4856:                     $thesepriv{$privilege}='F';
                   4857:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4858:                     $thesepriv{$privilege}.=$restrictions;
                   4859:                 }
                   4860:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4861:             }
                   4862:         }
                   4863:         my $thesestr='';
1.1104    raeburn  4864:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4865: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4866: 	}
                   4867:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4868:     }
                   4869:     return ($author,$adv);
                   4870: }
                   4871: 
1.994     raeburn  4872: sub role_status {
1.1104    raeburn  4873:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4874:     my @pwhere = ();
                   4875:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4876:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4877:         unless (!defined($$role) || $$role eq '') {
                   4878:             $$where=join('.',@pwhere);
                   4879:             $$trolecode=$$role.'.'.$$where;
                   4880:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4881:             $$tstatus='is';
1.1104    raeburn  4882:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4883:                 $$tstatus='future';
1.1034    raeburn  4884:                 if ($$tstart<$now) {
                   4885:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4886:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4887:                             my (%allroles,%allgroups,$group_privs,
                   4888:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4889:                             my %userroles = (
                   4890:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4891:                             );
1.1064    raeburn  4892:                             @rolecodes = ('cm'); 
1.1002    raeburn  4893:                             my $spec=$$role.'.'.$$where;
                   4894:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4895:                             if ($$role =~ /^cr\//) {
                   4896:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4897:                                 push(@rolecodes,'cr');
1.1002    raeburn  4898:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4899:                                 push(@rolecodes,$$role);
1.1002    raeburn  4900:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4901:                                                     $env{'user.name'});
1.1064    raeburn  4902:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4903:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4904:                                 $group_privs = &unescape($group_privs);
                   4905:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4906:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104    raeburn  4907:                                 &get_groups_roles($tdomain,$trest,
                   4908:                                                   \%course_roles,\@rolecodes,
                   4909:                                                   \%groups_roles);
1.1002    raeburn  4910:                             } else {
1.1064    raeburn  4911:                                 push(@rolecodes,$$role);
1.1002    raeburn  4912:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4913:                             }
1.1064    raeburn  4914:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4915:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4916:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4917:                         }
                   4918:                     }
1.1034    raeburn  4919:                     $$tstatus = 'is';
1.1002    raeburn  4920:                 }
1.994     raeburn  4921:             }
                   4922:             if ($$tend) {
1.1104    raeburn  4923:                 if ($$tend<$update) {
1.994     raeburn  4924:                     $$tstatus='expired';
                   4925:                 } elsif ($$tend<$now) {
                   4926:                     $$tstatus='will_not';
                   4927:                 }
                   4928:             }
                   4929:         }
                   4930:     }
                   4931: }
                   4932: 
1.1104    raeburn  4933: sub get_groups_roles {
                   4934:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4935:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4936:                   (ref($rolecodes) eq 'ARRAY') && 
                   4937:                   (ref($groups_roles) eq 'HASH')); 
                   4938:     if (keys(%{$cdom_courseroles}) > 0) {
                   4939:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4940:         if ($cdom ne '' && $cnum ne '') {
                   4941:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4942:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4943:                     my $crsrole = $1;
                   4944:                     my $crssec = $2;
                   4945:                     if ($crsrole =~ /^cr/) {
                   4946:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4947:                             push(@{$rolecodes},'cr');
                   4948:                         }
                   4949:                     } else {
                   4950:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4951:                             push(@{$rolecodes},$crsrole);
                   4952:                         }
                   4953:                     }
                   4954:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4955:                     if ($crssec ne '') {
                   4956:                         $rolekey .= "/$crssec";
                   4957:                     }
                   4958:                     $rolekey .= './';
                   4959:                     $groups_roles->{$rolekey} = $rolecodes;
                   4960:                 }
                   4961:             }
                   4962:         }
                   4963:     }
                   4964:     return;
                   4965: }
                   4966: 
                   4967: sub delete_env_groupprivs {
                   4968:     my ($where,$courseroles,$possroles) = @_;
                   4969:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4970:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4971:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4972:         %{$courseroles->{$udom}} =
                   4973:             &get_my_roles('','','userroles',['active'],
                   4974:                           $possroles,[$udom],1);
                   4975:     }
                   4976:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4977:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4978:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4979:             my $area = '/'.$cdom.'/'.$cnum;
                   4980:             my $privkey = "user.priv.$crsrole.$area";
                   4981:             if ($crssec ne '') {
                   4982:                 $privkey .= '/'.$crssec;
                   4983:             }
                   4984:             $privkey .= ".$area/$group";
                   4985:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4986:         }
                   4987:     }
                   4988:     return;
                   4989: }
                   4990: 
1.994     raeburn  4991: sub check_adhoc_privs {
1.1104    raeburn  4992:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4993:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4994:     if ($env{$cckey}) {
                   4995:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4996:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4997:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4998:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4999:         }
                   5000:     } else {
1.1088    raeburn  5001:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  5002:     }
                   5003: }
                   5004: 
                   5005: sub set_adhoc_privileges {
                   5006: # role can be cc or ca
1.1088    raeburn  5007:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5008:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5009:     my $spec = $role.'.'.$area;
                   5010:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5011:                                   $env{'user.name'});
                   5012:     my %ccrole = ();
                   5013:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5014:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5015:     &appenv(\%userroles,[$role,'cm']);
                   5016:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5017:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5018:         &appenv( {'request.role'        => $spec,
                   5019:                   'request.role.domain' => $dcdom,
                   5020:                   'request.course.sec'  => ''
                   5021:                  }
                   5022:                );
                   5023:         my $tadv=0;
                   5024:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5025:         &appenv({'request.role.adv'    => $tadv});
                   5026:     }
1.994     raeburn  5027: }
                   5028: 
1.12      www      5029: # --------------------------------------------------------------- get interface
                   5030: 
                   5031: sub get {
1.131     albertel 5032:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5033:    my $items='';
1.800     albertel 5034:    foreach my $item (@$storearr) {
                   5035:        $items.=&escape($item).'&';
1.191     harris41 5036:    }
1.12      www      5037:    $items=~s/\&$//;
1.620     albertel 5038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5039:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5040:    my $uhome=&homeserver($uname,$udomain);
                   5041: 
1.133     albertel 5042:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5043:    my @pairs=split(/\&/,$rep);
1.273     albertel 5044:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5045:      return @pairs;
                   5046:    }
1.15      www      5047:    my %returnhash=();
1.42      www      5048:    my $i=0;
1.800     albertel 5049:    foreach my $item (@$storearr) {
                   5050:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5051:       $i++;
1.191     harris41 5052:    }
1.15      www      5053:    return %returnhash;
1.27      www      5054: }
                   5055: 
                   5056: # --------------------------------------------------------------- del interface
                   5057: 
                   5058: sub del {
1.133     albertel 5059:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5060:    my $items='';
1.800     albertel 5061:    foreach my $item (@$storearr) {
                   5062:        $items.=&escape($item).'&';
1.191     harris41 5063:    }
1.984     neumanie 5064: 
1.27      www      5065:    $items=~s/\&$//;
1.620     albertel 5066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5067:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5068:    my $uhome=&homeserver($uname,$udomain);
                   5069:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5070: }
                   5071: 
                   5072: # -------------------------------------------------------------- dump interface
                   5073: 
                   5074: sub dump {
1.1166    raeburn  5075:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5076:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5077:     if (!$uname) { $uname=$env{'user.name'}; }
                   5078:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5079: 
1.755     albertel 5080:     if ($regexp) {
                   5081: 	$regexp=&escape($regexp);
                   5082:     } else {
                   5083: 	$regexp='.';
                   5084:     }
1.1166    raeburn  5085:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5086:     my @pairs=split(/\&/,$rep);
                   5087:     my %returnhash=();
1.1098    foxr     5088:     if (!($rep =~ /^error/ )) {
                   5089: 	foreach my $item (@pairs) {
                   5090: 	    my ($key,$value)=split(/=/,$item,2);
                   5091: 	    $key = &unescape($key);
                   5092: 	    next if ($key =~ /^error: 2 /);
                   5093: 	    $returnhash{$key}=&thaw_unescape($value);
                   5094: 	}
1.755     albertel 5095:     }
                   5096:     return %returnhash;
1.407     www      5097: }
                   5098: 
1.1098    foxr     5099: 
1.717     albertel 5100: # --------------------------------------------------------- dumpstore interface
                   5101: 
                   5102: sub dumpstore {
                   5103:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5104:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5105:    if (!$uname) { $uname=$env{'user.name'}; }
                   5106:    my $uhome=&homeserver($uname,$udomain);
                   5107:    if ($regexp) {
                   5108:        $regexp=&escape($regexp);
                   5109:    } else {
                   5110:        $regexp='.';
                   5111:    }
                   5112:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5113:    my @pairs=split(/\&/,$rep);
                   5114:    my %returnhash=();
                   5115:    foreach my $item (@pairs) {
                   5116:        my ($key,$value)=split(/=/,$item,2);
                   5117:        next if ($key =~ /^error: 2 /);
                   5118:        $returnhash{$key}=&thaw_unescape($value);
                   5119:    }
                   5120:    return %returnhash;
1.717     albertel 5121: }
                   5122: 
1.407     www      5123: # -------------------------------------------------------------- keys interface
                   5124: 
                   5125: sub getkeys {
                   5126:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5127:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5128:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5129:    my $uhome=&homeserver($uname,$udomain);
                   5130:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5131:    my @keyarray=();
1.800     albertel 5132:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5133:       next if ($key =~ /^error: 2 /);
1.800     albertel 5134:       push(@keyarray,&unescape($key));
1.407     www      5135:    }
                   5136:    return @keyarray;
1.318     matthew  5137: }
                   5138: 
1.319     matthew  5139: # --------------------------------------------------------------- currentdump
                   5140: sub currentdump {
1.328     matthew  5141:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5142:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5143:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5144:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5145:    my $uhome = &homeserver($sname,$sdom);
                   5146:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5147:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5148:    #
1.318     matthew  5149:    my %returnhash=();
1.319     matthew  5150:    #
                   5151:    if ($rep eq "unknown_cmd") { 
                   5152:        # an old lond will not know currentdump
                   5153:        # Do a dump and make it look like a currentdump
1.822     albertel 5154:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5155:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5156:        my %hash = @tmp;
                   5157:        @tmp=();
1.424     matthew  5158:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5159:    } else {
                   5160:        my @pairs=split(/\&/,$rep);
1.800     albertel 5161:        foreach my $pair (@pairs) {
                   5162:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5163:            my ($symb,$param) = split(/:/,$key);
                   5164:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5165:                                                         &thaw_unescape($value);
1.319     matthew  5166:        }
1.191     harris41 5167:    }
1.12      www      5168:    return %returnhash;
1.424     matthew  5169: }
                   5170: 
                   5171: sub convert_dump_to_currentdump{
                   5172:     my %hash = %{shift()};
                   5173:     my %returnhash;
                   5174:     # Code ripped from lond, essentially.  The only difference
                   5175:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5176:     # we might run in to problems with parameter names =~ /^v\./
                   5177:     while (my ($key,$value) = each(%hash)) {
                   5178:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5179: 	$symb  = &unescape($symb);
                   5180: 	$param = &unescape($param);
1.424     matthew  5181:         next if ($v eq 'version' || $symb eq 'keys');
                   5182:         next if (exists($returnhash{$symb}) &&
                   5183:                  exists($returnhash{$symb}->{$param}) &&
                   5184:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5185:         $returnhash{$symb}->{$param}=$value;
                   5186:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5187:     }
                   5188:     #
                   5189:     # Remove all of the keys in the hashes which keep track of
                   5190:     # the version of the parameter.
                   5191:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5192:         # use a foreach because we are going to delete from the hash.
                   5193:         foreach my $key (keys(%$param_hash)) {
                   5194:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5195:         }
                   5196:     }
                   5197:     return \%returnhash;
1.12      www      5198: }
                   5199: 
1.627     albertel 5200: # ------------------------------------------------------ critical inc interface
                   5201: 
                   5202: sub cinc {
                   5203:     return &inc(@_,'critical');
                   5204: }
                   5205: 
1.449     matthew  5206: # --------------------------------------------------------------- inc interface
                   5207: 
                   5208: sub inc {
1.627     albertel 5209:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5210:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5211:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5212:     my $uhome=&homeserver($uname,$udomain);
                   5213:     my $items='';
                   5214:     if (! ref($store)) {
                   5215:         # got a single value, so use that instead
                   5216:         $items = &escape($store).'=&';
                   5217:     } elsif (ref($store) eq 'SCALAR') {
                   5218:         $items = &escape($$store).'=&';        
                   5219:     } elsif (ref($store) eq 'ARRAY') {
                   5220:         $items = join('=&',map {&escape($_);} @{$store});
                   5221:     } elsif (ref($store) eq 'HASH') {
                   5222:         while (my($key,$value) = each(%{$store})) {
                   5223:             $items.= &escape($key).'='.&escape($value).'&';
                   5224:         }
                   5225:     }
                   5226:     $items=~s/\&$//;
1.627     albertel 5227:     if ($critical) {
                   5228: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5229:     } else {
                   5230: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5231:     }
1.449     matthew  5232: }
                   5233: 
1.12      www      5234: # --------------------------------------------------------------- put interface
                   5235: 
                   5236: sub put {
1.134     albertel 5237:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5239:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5240:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5241:    my $items='';
1.800     albertel 5242:    foreach my $item (keys(%$storehash)) {
                   5243:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5244:    }
1.12      www      5245:    $items=~s/\&$//;
1.134     albertel 5246:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5247: }
                   5248: 
1.631     albertel 5249: # ------------------------------------------------------------ newput interface
                   5250: 
                   5251: sub newput {
                   5252:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5254:    if (!$uname) { $uname=$env{'user.name'}; }
                   5255:    my $uhome=&homeserver($uname,$udomain);
                   5256:    my $items='';
                   5257:    foreach my $key (keys(%$storehash)) {
                   5258:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5259:    }
                   5260:    $items=~s/\&$//;
                   5261:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5262: }
                   5263: 
                   5264: # ---------------------------------------------------------  putstore interface
                   5265: 
1.524     raeburn  5266: sub putstore {
1.715     albertel 5267:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5268:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5269:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5270:    my $uhome=&homeserver($uname,$udomain);
                   5271:    my $items='';
1.715     albertel 5272:    foreach my $key (keys(%$storehash)) {
                   5273:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5274:    }
1.715     albertel 5275:    $items=~s/\&$//;
1.716     albertel 5276:    my $esc_symb=&escape($symb);
                   5277:    my $esc_v=&escape($version);
1.715     albertel 5278:    my $reply =
1.716     albertel 5279:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5280: 	      $uhome);
                   5281:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5282:        # gfall back to way things use to be done
1.715     albertel 5283:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5284: 			    $uname);
1.524     raeburn  5285:    }
1.715     albertel 5286:    return $reply;
                   5287: }
                   5288: 
                   5289: sub old_putstore {
1.716     albertel 5290:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5291:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5292:     if (!$uname) { $uname=$env{'user.name'}; }
                   5293:     my $uhome=&homeserver($uname,$udomain);
                   5294:     my %newstorehash;
1.800     albertel 5295:     foreach my $item (keys(%$storehash)) {
                   5296: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5297: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5298:     }
                   5299:     my $items='';
                   5300:     my %allitems = ();
1.800     albertel 5301:     foreach my $item (keys(%newstorehash)) {
                   5302: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5303: 	    my $key = $1.':keys:'.$2;
                   5304: 	    $allitems{$key} .= $3.':';
                   5305: 	}
1.800     albertel 5306: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5307:     }
1.800     albertel 5308:     foreach my $item (keys(%allitems)) {
                   5309: 	$allitems{$item} =~ s/\:$//;
                   5310: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5311:     }
                   5312:     $items=~s/\&$//;
                   5313:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5314: }
                   5315: 
1.47      www      5316: # ------------------------------------------------------ critical put interface
                   5317: 
                   5318: sub cput {
1.134     albertel 5319:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5320:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5321:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5322:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5323:    my $items='';
1.800     albertel 5324:    foreach my $item (keys(%$storehash)) {
                   5325:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5326:    }
1.47      www      5327:    $items=~s/\&$//;
1.134     albertel 5328:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5329: }
                   5330: 
                   5331: # -------------------------------------------------------------- eget interface
                   5332: 
                   5333: sub eget {
1.133     albertel 5334:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5335:    my $items='';
1.800     albertel 5336:    foreach my $item (@$storearr) {
                   5337:        $items.=&escape($item).'&';
1.191     harris41 5338:    }
1.12      www      5339:    $items=~s/\&$//;
1.620     albertel 5340:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5341:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5342:    my $uhome=&homeserver($uname,$udomain);
                   5343:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5344:    my @pairs=split(/\&/,$rep);
                   5345:    my %returnhash=();
1.42      www      5346:    my $i=0;
1.800     albertel 5347:    foreach my $item (@$storearr) {
                   5348:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5349:       $i++;
1.191     harris41 5350:    }
1.12      www      5351:    return %returnhash;
                   5352: }
                   5353: 
1.667     albertel 5354: # ------------------------------------------------------------ tmpput interface
                   5355: sub tmpput {
1.802     raeburn  5356:     my ($storehash,$server,$context)=@_;
1.667     albertel 5357:     my $items='';
1.800     albertel 5358:     foreach my $item (keys(%$storehash)) {
                   5359: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5360:     }
                   5361:     $items=~s/\&$//;
1.802     raeburn  5362:     if (defined($context)) {
                   5363:         $items .= ':'.&escape($context);
                   5364:     }
1.667     albertel 5365:     return &reply("tmpput:$items",$server);
                   5366: }
                   5367: 
                   5368: # ------------------------------------------------------------ tmpget interface
                   5369: sub tmpget {
1.688     albertel 5370:     my ($token,$server)=@_;
                   5371:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5372:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5373:     my %returnhash;
                   5374:     foreach my $item (split(/\&/,$rep)) {
                   5375: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5376:         next if ($key =~ /^error: 2 /);
1.667     albertel 5377: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5378:     }
                   5379:     return %returnhash;
                   5380: }
                   5381: 
1.1113    raeburn  5382: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5383: sub tmpdel {
                   5384:     my ($token,$server)=@_;
                   5385:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5386:     return &reply("tmpdel:$token",$server);
                   5387: }
                   5388: 
1.765     albertel 5389: # -------------------------------------------------- portfolio access checking
                   5390: 
                   5391: sub portfolio_access {
1.766     albertel 5392:     my ($requrl) = @_;
1.765     albertel 5393:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5394:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5395:     if ($result) {
                   5396:         my %setters;
                   5397:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5398:             my ($startblock,$endblock) =
                   5399:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5400:             if ($startblock && $endblock) {
                   5401:                 return 'B';
                   5402:             }
                   5403:         } else {
                   5404:             my ($startblock,$endblock) =
                   5405:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5406:             if ($startblock && $endblock) {
                   5407:                 return 'B';
                   5408:             }
                   5409:         }
                   5410:     }
1.765     albertel 5411:     if ($result eq 'ok') {
1.766     albertel 5412:        return 'F';
1.765     albertel 5413:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5414:        return 'A';
1.765     albertel 5415:     }
1.766     albertel 5416:     return '';
1.765     albertel 5417: }
                   5418: 
                   5419: sub get_portfolio_access {
1.767     albertel 5420:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5421: 
                   5422:     if (!ref($access_hash)) {
                   5423: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5424: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5425: 						   $file_name);
                   5426: 	$access_hash = $access_controls{$file_name};
                   5427:     }
                   5428: 
1.765     albertel 5429:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5430:     my $now = time;
                   5431:     if (ref($access_hash) eq 'HASH') {
                   5432:         foreach my $key (keys(%{$access_hash})) {
                   5433:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5434:             if ($start > $now) {
                   5435:                 next;
                   5436:             }
                   5437:             if ($end && $end<$now) {
                   5438:                 next;
                   5439:             }
                   5440:             if ($scope eq 'public') {
                   5441:                 $public = $key;
                   5442:                 last;
                   5443:             } elsif ($scope eq 'guest') {
                   5444:                 $guest = $key;
                   5445:             } elsif ($scope eq 'domains') {
                   5446:                 push(@domains,$key);
                   5447:             } elsif ($scope eq 'users') {
                   5448:                 push(@users,$key);
                   5449:             } elsif ($scope eq 'course') {
                   5450:                 push(@courses,$key);
                   5451:             } elsif ($scope eq 'group') {
                   5452:                 push(@groups,$key);
                   5453:             }
                   5454:         }
                   5455:         if ($public) {
                   5456:             return 'ok';
                   5457:         }
                   5458:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5459:             if ($guest) {
                   5460:                 return $guest;
                   5461:             }
                   5462:         } else {
                   5463:             if (@domains > 0) {
                   5464:                 foreach my $domkey (@domains) {
                   5465:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5466:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5467:                             return 'ok';
                   5468:                         }
                   5469:                     }
                   5470:                 }
                   5471:             }
                   5472:             if (@users > 0) {
                   5473:                 foreach my $userkey (@users) {
1.865     raeburn  5474:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5475:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5476:                             if (ref($item) eq 'HASH') {
                   5477:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5478:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5479:                                     return 'ok';
                   5480:                                 }
                   5481:                             }
                   5482:                         }
                   5483:                     } 
1.765     albertel 5484:                 }
                   5485:             }
                   5486:             my %roleshash;
                   5487:             my @courses_and_groups = @courses;
                   5488:             push(@courses_and_groups,@groups); 
                   5489:             if (@courses_and_groups > 0) {
                   5490:                 my (%allgroups,%allroles); 
                   5491:                 my ($start,$end,$role,$sec,$group);
                   5492:                 foreach my $envkey (%env) {
1.1060    raeburn  5493:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5494:                         my $cid = $2.'_'.$3; 
                   5495:                         if ($1 eq 'gr') {
                   5496:                             $group = $4;
                   5497:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5498:                         } else {
                   5499:                             if ($4 eq '') {
                   5500:                                 $sec = 'none';
                   5501:                             } else {
                   5502:                                 $sec = $4;
                   5503:                             }
                   5504:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5505:                         }
1.811     albertel 5506:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5507:                         my $cid = $2.'_'.$3;
                   5508:                         if ($4 eq '') {
                   5509:                             $sec = 'none';
                   5510:                         } else {
                   5511:                             $sec = $4;
                   5512:                         }
                   5513:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5514:                     }
                   5515:                 }
                   5516:                 if (keys(%allroles) == 0) {
                   5517:                     return;
                   5518:                 }
                   5519:                 foreach my $key (@courses_and_groups) {
                   5520:                     my %content = %{$$access_hash{$key}};
                   5521:                     my $cnum = $content{'number'};
                   5522:                     my $cdom = $content{'domain'};
                   5523:                     my $cid = $cdom.'_'.$cnum;
                   5524:                     if (!exists($allroles{$cid})) {
                   5525:                         next;
                   5526:                     }    
                   5527:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5528:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5529:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5530:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5531:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5532:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5533:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5534:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5535:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5536:                                         if (grep/^all$/,@sections) {
                   5537:                                             return 'ok';
                   5538:                                         } else {
                   5539:                                             if (grep/^$sec$/,@sections) {
                   5540:                                                 return 'ok';
                   5541:                                             }
                   5542:                                         }
                   5543:                                     }
                   5544:                                 }
                   5545:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5546:                                     if (grep/^none$/,@groups) {
                   5547:                                         return 'ok';
                   5548:                                     }
                   5549:                                 } else {
                   5550:                                     if (grep/^all$/,@groups) {
                   5551:                                         return 'ok';
                   5552:                                     } 
                   5553:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5554:                                         if (grep/^$group$/,@groups) {
                   5555:                                             return 'ok';
                   5556:                                         }
                   5557:                                     }
                   5558:                                 } 
                   5559:                             }
                   5560:                         }
                   5561:                     }
                   5562:                 }
                   5563:             }
                   5564:             if ($guest) {
                   5565:                 return $guest;
                   5566:             }
                   5567:         }
                   5568:     }
                   5569:     return;
                   5570: }
                   5571: 
                   5572: sub course_group_datechecker {
                   5573:     my ($dates,$now,$status) = @_;
                   5574:     my ($start,$end) = split(/\./,$dates);
                   5575:     if (!$start && !$end) {
                   5576:         return 'ok';
                   5577:     }
                   5578:     if (grep/^active$/,@{$status}) {
                   5579:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5580:             return 'ok';
                   5581:         }
                   5582:     }
                   5583:     if (grep/^previous$/,@{$status}) {
                   5584:         if ($end > $now ) {
                   5585:             return 'ok';
                   5586:         }
                   5587:     }
                   5588:     if (grep/^future$/,@{$status}) {
                   5589:         if ($start > $now) {
                   5590:             return 'ok';
                   5591:         }
                   5592:     }
                   5593:     return; 
                   5594: }
                   5595: 
                   5596: sub parse_portfolio_url {
                   5597:     my ($url) = @_;
                   5598: 
                   5599:     my ($type,$udom,$unum,$group,$file_name);
                   5600:     
1.823     albertel 5601:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5602: 	$type = 1;
                   5603:         $udom = $1;
                   5604:         $unum = $2;
                   5605:         $file_name = $3;
1.823     albertel 5606:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5607: 	$type = 2;
                   5608:         $udom = $1;
                   5609:         $unum = $2;
                   5610:         $group = $3;
                   5611:         $file_name = $3.'/'.$4;
                   5612:     }
                   5613:     if (wantarray) {
                   5614: 	return ($type,$udom,$unum,$file_name,$group);
                   5615:     }
                   5616:     return $type;
                   5617: }
                   5618: 
                   5619: sub is_portfolio_url {
                   5620:     my ($url) = @_;
                   5621:     return scalar(&parse_portfolio_url($url));
                   5622: }
                   5623: 
1.798     raeburn  5624: sub is_portfolio_file {
                   5625:     my ($file) = @_;
1.820     raeburn  5626:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5627:         return 1;
                   5628:     }
                   5629:     return;
                   5630: }
                   5631: 
1.976     raeburn  5632: sub usertools_access {
1.1084    raeburn  5633:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5634:     my ($access,%tools);
                   5635:     if ($context eq '') {
                   5636:         $context = 'tools';
                   5637:     }
                   5638:     if ($context eq 'requestcourses') {
                   5639:         %tools = (
                   5640:                       official   => 1,
                   5641:                       unofficial => 1,
1.1006    raeburn  5642:                       community  => 1,
1.985     raeburn  5643:                  );
                   5644:     } else {
                   5645:         %tools = (
                   5646:                       aboutme   => 1,
                   5647:                       blog      => 1,
                   5648:                       portfolio => 1,
                   5649:                  );
                   5650:     }
1.976     raeburn  5651:     return if (!defined($tools{$tool}));
                   5652: 
                   5653:     if ((!defined($udom)) || (!defined($uname))) {
                   5654:         $udom = $env{'user.domain'};
                   5655:         $uname = $env{'user.name'};
                   5656:     }
                   5657: 
1.978     raeburn  5658:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5659:         if ($action ne 'reload') {
1.985     raeburn  5660:             if ($context eq 'requestcourses') {
                   5661:                 return $env{'environment.canrequest.'.$tool};
                   5662:             } else {
                   5663:                 return $env{'environment.availabletools.'.$tool};
                   5664:             }
                   5665:         }
1.976     raeburn  5666:     }
                   5667: 
                   5668:     my ($toolstatus,$inststatus);
                   5669: 
1.985     raeburn  5670:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5671:          ($action ne 'reload')) {
                   5672:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5673:         $inststatus = $env{'environment.inststatus'};
                   5674:     } else {
1.1084    raeburn  5675:         if (ref($userenvref) eq 'HASH') {
                   5676:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5677:             $inststatus = $userenvref->{'inststatus'};
                   5678:         } else {
                   5679:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5680:             $toolstatus = $userenv{$context.'.'.$tool};
                   5681:             $inststatus = $userenv{'inststatus'};
                   5682:         }
1.976     raeburn  5683:     }
                   5684: 
                   5685:     if ($toolstatus ne '') {
                   5686:         if ($toolstatus) {
                   5687:             $access = 1;
                   5688:         } else {
                   5689:             $access = 0;
                   5690:         }
                   5691:         return $access;
                   5692:     }
                   5693: 
1.1084    raeburn  5694:     my ($is_adv,%domdef);
                   5695:     if (ref($is_advref) eq 'HASH') {
                   5696:         $is_adv = $is_advref->{'is_adv'};
                   5697:     } else {
                   5698:         $is_adv = &is_advanced_user($udom,$uname);
                   5699:     }
                   5700:     if (ref($domdefref) eq 'HASH') {
                   5701:         %domdef = %{$domdefref};
                   5702:     } else {
                   5703:         %domdef = &get_domain_defaults($udom);
                   5704:     }
1.976     raeburn  5705:     if (ref($domdef{$tool}) eq 'HASH') {
                   5706:         if ($is_adv) {
                   5707:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5708:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5709:                     $access = 1;
                   5710:                 } else {
                   5711:                     $access = 0;
                   5712:                 }
                   5713:                 return $access;
                   5714:             }
                   5715:         }
                   5716:         if ($inststatus ne '') {
                   5717:             my ($hasaccess,$hasnoaccess);
                   5718:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5719:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5720:                     if ($domdef{$tool}{$affiliation}) {
                   5721:                         $hasaccess = 1;
                   5722:                     } else {
                   5723:                         $hasnoaccess = 1;
                   5724:                     }
                   5725:                 }
                   5726:             }
                   5727:             if ($hasaccess || $hasnoaccess) {
                   5728:                 if ($hasaccess) {
                   5729:                     $access = 1;
                   5730:                 } elsif ($hasnoaccess) {
                   5731:                     $access = 0; 
                   5732:                 }
                   5733:                 return $access;
                   5734:             }
                   5735:         } else {
                   5736:             if ($domdef{$tool}{'default'} ne '') {
                   5737:                 if ($domdef{$tool}{'default'}) {
                   5738:                     $access = 1;
                   5739:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5740:                     $access = 0;
                   5741:                 }
                   5742:                 return $access;
                   5743:             }
                   5744:         }
                   5745:     } else {
1.985     raeburn  5746:         if ($context eq 'tools') {
                   5747:             $access = 1;
                   5748:         } else {
                   5749:             $access = 0;
                   5750:         }
1.976     raeburn  5751:         return $access;
                   5752:     }
                   5753: }
                   5754: 
1.1050    raeburn  5755: sub is_course_owner {
                   5756:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5757:     if (($udom eq '') || ($uname eq '')) {
                   5758:         $udom = $env{'user.domain'};
                   5759:         $uname = $env{'user.name'};
                   5760:     }
                   5761:     unless (($udom eq '') || ($uname eq '')) {
                   5762:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5763:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5764:                 return 1;
                   5765:             } else {
                   5766:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5767:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5768:                     return 1;
                   5769:                 }
                   5770:             }
                   5771:         }
                   5772:     }
                   5773:     return;
                   5774: }
                   5775: 
1.976     raeburn  5776: sub is_advanced_user {
                   5777:     my ($udom,$uname) = @_;
1.1085    raeburn  5778:     if ($udom ne '' && $uname ne '') {
                   5779:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5780:             if (wantarray) {
                   5781:                 return ($env{'user.adv'},$env{'user.author'});
                   5782:             } else {
                   5783:                 return $env{'user.adv'};
                   5784:             }
1.1085    raeburn  5785:         }
                   5786:     }
1.976     raeburn  5787:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5788:     my %allroles;
1.1128    raeburn  5789:     my ($is_adv,$is_author);
1.976     raeburn  5790:     foreach my $role (keys(%roleshash)) {
                   5791:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5792:         my $area = '/'.$tdomain.'/'.$trest;
                   5793:         if ($sec ne '') {
                   5794:             $area .= '/'.$sec;
                   5795:         }
                   5796:         if (($area ne '') && ($trole ne '')) {
                   5797:             my $spec=$trole.'.'.$area;
                   5798:             if ($trole =~ /^cr\//) {
                   5799:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5800:             } elsif ($trole ne 'gr') {
                   5801:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5802:             }
1.1128    raeburn  5803:             if ($trole eq 'au') {
                   5804:                 $is_author = 1;
                   5805:             }
1.976     raeburn  5806:         }
                   5807:     }
                   5808:     foreach my $role (keys(%allroles)) {
                   5809:         last if ($is_adv);
                   5810:         foreach my $item (split(/:/,$allroles{$role})) {
                   5811:             if ($item ne '') {
                   5812:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5813:                 if ($privilege eq 'adv') {
                   5814:                     $is_adv = 1;
                   5815:                     last;
                   5816:                 }
                   5817:             }
                   5818:         }
                   5819:     }
1.1128    raeburn  5820:     if (wantarray) {
                   5821:         return ($is_adv,$is_author);
                   5822:     }
1.976     raeburn  5823:     return $is_adv;
                   5824: }
1.798     raeburn  5825: 
1.1035    raeburn  5826: sub check_can_request {
1.1036    raeburn  5827:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5828:     my $canreq = 0;
                   5829:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5830:     my @options = ('approval','validate','autolimit');
                   5831:     my $optregex = join('|',@options);
                   5832:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5833:         foreach my $type (@{$types}) {
                   5834:             if (&usertools_access($env{'user.name'},
                   5835:                                   $env{'user.domain'},
                   5836:                                   $type,undef,'requestcourses')) {
                   5837:                 $canreq ++;
1.1036    raeburn  5838:                 if (ref($request_domains) eq 'HASH') {
                   5839:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5840:                 }
1.1035    raeburn  5841:                 if ($dom eq $env{'user.domain'}) {
                   5842:                     $can_request->{$type} = 1;
                   5843:                 }
                   5844:             }
                   5845:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5846:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5847:                 if (@curr > 0) {
1.1036    raeburn  5848:                     foreach my $item (@curr) {
                   5849:                         if (ref($request_domains) eq 'HASH') {
                   5850:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5851:                             if ($otherdom ne '') {
                   5852:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5853:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5854:                                         push(@{$request_domains->{$type}},$otherdom);
                   5855:                                     }
                   5856:                                 } else {
                   5857:                                     push(@{$request_domains->{$type}},$otherdom);
                   5858:                                 }
                   5859:                             }
                   5860:                         }
                   5861:                     }
                   5862:                     unless($dom eq $env{'user.domain'}) {
                   5863:                         $canreq ++;
1.1035    raeburn  5864:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5865:                             $can_request->{$type} = 1;
                   5866:                         }
                   5867:                     }
                   5868:                 }
                   5869:             }
                   5870:         }
                   5871:     }
                   5872:     return $canreq;
                   5873: }
                   5874: 
1.341     www      5875: # ---------------------------------------------- Custom access rule evaluation
                   5876: 
                   5877: sub customaccess {
                   5878:     my ($priv,$uri)=@_;
1.807     albertel 5879:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5880:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5881:     $udom = &LONCAPA::clean_domain($udom);
                   5882:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5883:     my $access=0;
1.800     albertel 5884:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5885: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5886: 	if ($type eq 'user') {
                   5887: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5888: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5889: 		if ($tdom) {
                   5890: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5891: 		}
1.896     albertel 5892: 		if ($tuname) {
                   5893: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5894: 		}
                   5895: 		$access=($effect eq 'allow');
                   5896: 		last;
                   5897: 	    }
                   5898: 	} else {
                   5899: 	    if ($role) {
                   5900: 		if ($role ne $urole) { next; }
                   5901: 	    }
                   5902: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5903: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5904: 		if ($tdom) {
                   5905: 		    if ($tdom ne $udom) { next; }
                   5906: 		}
                   5907: 		if ($tcrs) {
                   5908: 		    if ($tcrs ne $ucrs) { next; }
                   5909: 		}
                   5910: 		if ($tsec) {
                   5911: 		    if ($tsec ne $usec) { next; }
                   5912: 		}
                   5913: 		$access=($effect eq 'allow');
                   5914: 		last;
                   5915: 	    }
                   5916: 	    if ($realm eq '' && $role eq '') {
                   5917: 		$access=($effect eq 'allow');
                   5918: 	    }
1.402     bowersj2 5919: 	}
1.341     www      5920:     }
                   5921:     return $access;
                   5922: }
                   5923: 
1.103     harris41 5924: # ------------------------------------------------- Check for a user privilege
1.12      www      5925: 
                   5926: sub allowed {
1.810     raeburn  5927:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5928:     my $ver_orguri=$uri;
1.439     www      5929:     $uri=&deversion($uri);
1.152     www      5930:     my $orguri=$uri;
1.52      www      5931:     $uri=&declutter($uri);
1.809     raeburn  5932: 
1.810     raeburn  5933:     if ($priv eq 'evb') {
                   5934: # Evade communication block restrictions for specified role in a course
                   5935:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5936:             return $1;
                   5937:         } else {
                   5938:             return;
                   5939:         }
                   5940:     }
                   5941: 
1.620     albertel 5942:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5943: # Free bre access to adm and meta resources
1.775     albertel 5944:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5945: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5946: 	&& ($priv eq 'bre')) {
1.14      www      5947: 	return 'F';
1.159     www      5948:     }
                   5949: 
1.545     banghart 5950: # Free bre access to user's own portfolio contents
1.714     raeburn  5951:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5952:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5953: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5954:         my %setters;
                   5955:         my ($startblock,$endblock) = 
                   5956:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5957:         if ($startblock && $endblock) {
                   5958:             return 'B';
                   5959:         } else {
                   5960:             return 'F';
                   5961:         }
1.545     banghart 5962:     }
                   5963: 
1.762     raeburn  5964: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5965:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5966:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5967:         if (exists($env{'request.course.id'})) {
                   5968:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5969:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5970:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5971:                 my $courseprivid=$env{'request.course.id'};
                   5972:                 $courseprivid=~s/\_/\//;
                   5973:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5974:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5975:                     return $1; 
1.762     raeburn  5976:                 } else {
                   5977:                     if ($env{'request.course.sec'}) {
                   5978:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5979:                     }
                   5980:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5981:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5982:                         return $2;
                   5983:                     }
1.714     raeburn  5984:                 }
                   5985:             }
                   5986:         }
                   5987:     }
                   5988: 
1.159     www      5989: # Free bre to public access
                   5990: 
                   5991:     if ($priv eq 'bre') {
1.238     www      5992:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5993: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5994:            return 'F'; 
                   5995:         }
1.238     www      5996:         if ($copyright eq 'priv') {
                   5997:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5998: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5999: 		return '';
                   6000:             }
                   6001:         }
                   6002:         if ($copyright eq 'domain') {
                   6003:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6004: 	    unless (($env{'user.domain'} eq $1) ||
                   6005:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6006: 		return '';
                   6007:             }
1.262     matthew  6008:         }
1.620     albertel 6009:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6010:             # Library role, so allow browsing of resources in this domain.
                   6011:             return 'F';
1.238     www      6012:         }
1.341     www      6013:         if ($copyright eq 'custom') {
                   6014: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6015:         }
1.14      www      6016:     }
1.264     matthew  6017:     # Domain coordinator is trying to create a course
1.620     albertel 6018:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6019:         # uri is the requested domain in this case.
                   6020:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6021:         # a role of dc for the domain in question.
1.620     albertel 6022:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6023:     }
1.29      www      6024: 
1.52      www      6025:     my $thisallowed='';
                   6026:     my $statecond=0;
                   6027:     my $courseprivid='';
                   6028: 
1.1039    raeburn  6029:     my $ownaccess;
1.1043    raeburn  6030:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6031:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6032:         if ($uri eq '') {
                   6033:             $ownaccess = 1;
                   6034:         } else {
                   6035:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6036:                 my $udom = $env{'user.domain'};
                   6037:                 my $uname = $env{'user.name'};
                   6038:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6039:                     $ownaccess = 1;
1.1040    raeburn  6040:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6041:                     unless ($uri =~ m{\.\./}) {
                   6042:                         $ownaccess = 1;
                   6043:                     }
                   6044:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6045:                     my $now = time;
                   6046:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6047:                         my $adom = $1;
                   6048:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6049:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6050:                                 my ($start,$end) = split('.',$env{$key});
                   6051:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6052:                                     $ownaccess = 1;
                   6053:                                     last;
                   6054:                                 }
                   6055:                             }
                   6056:                         }
                   6057:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6058:                         my $adom = $1;
                   6059:                         my $aname = $2;
1.1042    raeburn  6060:                         foreach my $role ('ca','aa') { 
                   6061:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6062:                                 my ($start,$end) =
                   6063:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6064:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6065:                                     $ownaccess = 1;
                   6066:                                     last;
                   6067:                                 }
1.1039    raeburn  6068:                             }
                   6069:                         }
                   6070:                     }
                   6071:                 }
                   6072:             }
                   6073:         }
                   6074:     }
                   6075: 
1.52      www      6076: # Course
                   6077: 
1.620     albertel 6078:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6079:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6080:             $thisallowed.=$1;
                   6081:         }
1.52      www      6082:     }
1.29      www      6083: 
1.52      www      6084: # Domain
                   6085: 
1.620     albertel 6086:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6087:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6088:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6089:             $thisallowed.=$1;
                   6090:         }
1.12      www      6091:     }
1.52      www      6092: 
1.1141    raeburn  6093: # User who is not author or co-author might still be able to edit
                   6094: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6095:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6096:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6097:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6098:             $thisallowed.=$1;
                   6099:         }
                   6100:     }
                   6101: 
1.52      www      6102: # Course: uri itself is a course
1.66      www      6103:     my $courseuri=$uri;
                   6104:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6105:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6106: 
1.620     albertel 6107:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6108:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6109:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6110:             $thisallowed.=$1;
                   6111:         }
1.12      www      6112:     }
1.29      www      6113: 
1.665     albertel 6114: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6115: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6116:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6117: 	$thisallowed='';
1.671     raeburn  6118:         my ($match)=&is_on_map($uri);
                   6119:         if ($match) {
                   6120:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6121:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6122:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6123:                 if (@blockers > 0) {
                   6124:                     $thisallowed = 'B';
                   6125:                 } else {
                   6126:                     $thisallowed.=$1;
                   6127:                 }
1.671     raeburn  6128:             }
                   6129:         } else {
1.705     albertel 6130:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6131:             if ($refuri) {
                   6132:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6133:                     $thisallowed='F';
1.671     raeburn  6134:                 } else {
                   6135:                     $refuri=&declutter($refuri);
                   6136:                     my ($match) = &is_on_map($refuri);
                   6137:                     if ($match) {
1.1162    raeburn  6138:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6139:                         if (@blockers > 0) {
                   6140:                             $thisallowed = 'B';
                   6141:                         } else {
                   6142:                             $thisallowed='F';
                   6143:                         }
1.671     raeburn  6144:                     }
1.669     raeburn  6145:                 }
1.671     raeburn  6146:             }
                   6147:         }
1.314     www      6148:     }
1.492     albertel 6149: 
1.766     albertel 6150:     if ($priv eq 'bre'
                   6151: 	&& $thisallowed ne 'F' 
                   6152: 	&& $thisallowed ne '2'
                   6153: 	&& &is_portfolio_url($uri)) {
                   6154: 	$thisallowed = &portfolio_access($uri);
                   6155:     }
                   6156:     
1.52      www      6157: # Full access at system, domain or course-wide level? Exit.
1.29      www      6158:     if ($thisallowed=~/F/) {
                   6159: 	return 'F';
                   6160:     }
                   6161: 
1.52      www      6162: # If this is generating or modifying users, exit with special codes
1.29      www      6163: 
1.643     www      6164:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6165: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6166: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6167: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6168: 	    unless ($auname) { return $thisallowed; }
                   6169: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6170: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6171: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6172: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6173: 	}
1.52      www      6174: 	return $thisallowed;
                   6175:     }
                   6176: #
1.103     harris41 6177: # Gathered so far: system, domain and course wide privileges
1.52      www      6178: #
                   6179: # Course: See if uri or referer is an individual resource that is part of 
                   6180: # the course
                   6181: 
1.620     albertel 6182:     if ($env{'request.course.id'}) {
1.232     www      6183: 
1.620     albertel 6184:        $courseprivid=$env{'request.course.id'};
                   6185:        if ($env{'request.course.sec'}) {
                   6186:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6187:        }
                   6188:        $courseprivid=~s/\_/\//;
                   6189:        my $checkreferer=1;
1.232     www      6190:        my ($match,$cond)=&is_on_map($uri);
                   6191:        if ($match) {
                   6192:            $statecond=$cond;
1.620     albertel 6193:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6194:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6195:                my $value = $1;
                   6196:                if ($priv eq 'bre') {
                   6197:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6198:                    if (@blockers > 0) {
                   6199:                        $thisallowed = 'B';
                   6200:                    } else {
                   6201:                        $thisallowed.=$value;
                   6202:                    }
                   6203:                } else {
                   6204:                    $thisallowed.=$value;
                   6205:                }
1.52      www      6206:                $checkreferer=0;
                   6207:            }
1.29      www      6208:        }
1.83      www      6209:        
1.148     www      6210:        if ($checkreferer) {
1.620     albertel 6211: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6212:             unless ($refuri) {
1.800     albertel 6213:                 foreach my $key (keys(%env)) {
                   6214: 		    if ($key=~/^httpref\..*\*/) {
                   6215: 			my $pattern=$key;
1.156     www      6216:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6217:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6218:                         $pattern=~s/\//\\\//g;
1.152     www      6219:                         if ($orguri=~/$pattern/) {
1.800     albertel 6220: 			    $refuri=$env{$key};
1.148     www      6221:                         }
                   6222:                     }
1.191     harris41 6223:                 }
1.148     www      6224:             }
1.232     www      6225: 
1.148     www      6226:          if ($refuri) { 
1.152     www      6227: 	  $refuri=&declutter($refuri);
1.232     www      6228:           my ($match,$cond)=&is_on_map($refuri);
                   6229:             if ($match) {
                   6230:               my $refstatecond=$cond;
1.620     albertel 6231:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6232:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6233:                   my $value = $1;
                   6234:                   if ($priv eq 'bre') {
                   6235:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6236:                       if (@blockers > 0) {
                   6237:                           $thisallowed = 'B';
                   6238:                       } else {
                   6239:                           $thisallowed.=$value;
                   6240:                       }
                   6241:                   } else {
                   6242:                       $thisallowed.=$value;
                   6243:                   }
1.53      www      6244:                   $uri=$refuri;
                   6245:                   $statecond=$refstatecond;
1.52      www      6246:               }
                   6247:           }
1.148     www      6248:         }
1.29      www      6249:        }
1.52      www      6250:    }
1.29      www      6251: 
1.52      www      6252: #
1.103     harris41 6253: # Gathered now: all privileges that could apply, and condition number
1.52      www      6254: # 
                   6255: #
                   6256: # Full or no access?
                   6257: #
1.29      www      6258: 
1.52      www      6259:     if ($thisallowed=~/F/) {
                   6260: 	return 'F';
                   6261:     }
1.29      www      6262: 
1.52      www      6263:     unless ($thisallowed) {
                   6264:         return '';
                   6265:     }
1.29      www      6266: 
1.52      www      6267: # Restrictions exist, deal with them
                   6268: #
                   6269: #   C:according to course preferences
                   6270: #   R:according to resource settings
                   6271: #   L:unless locked
                   6272: #   X:according to user session state
                   6273: #
                   6274: 
                   6275: # Possibly locked functionality, check all courses
1.54      www      6276: # Locks might take effect only after 10 minutes cache expiration for other
                   6277: # courses, and 2 minutes for current course
1.52      www      6278: 
                   6279:     my $envkey;
                   6280:     if ($thisallowed=~/L/) {
1.1000    raeburn  6281:         foreach $envkey (keys(%env)) {
1.54      www      6282:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6283:                my $courseid=$2;
                   6284:                my $roleid=$1.'.'.$2;
1.92      www      6285:                $courseid=~s/^\///;
1.54      www      6286:                my $expiretime=600;
1.620     albertel 6287:                if ($env{'request.role'} eq $roleid) {
1.54      www      6288: 		  $expiretime=120;
                   6289:                }
                   6290: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6291:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6292:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6293: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6294:                }
1.620     albertel 6295:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6296:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6297: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6298:                        &log($env{'user.domain'},$env{'user.name'},
                   6299:                             $env{'user.home'},
1.57      www      6300:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6301:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6302:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6303: 		       return '';
                   6304:                    }
                   6305:                }
1.620     albertel 6306:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6307:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6308: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6309:                        &log($env{'user.domain'},$env{'user.name'},
                   6310:                             $env{'user.home'},
1.57      www      6311:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6312:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6313:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6314: 		       return '';
                   6315:                    }
                   6316:                }
                   6317: 	   }
1.29      www      6318:        }
1.52      www      6319:     }
                   6320:    
                   6321: #
                   6322: # Rest of the restrictions depend on selected course
                   6323: #
                   6324: 
1.620     albertel 6325:     unless ($env{'request.course.id'}) {
1.766     albertel 6326: 	if ($thisallowed eq 'A') {
                   6327: 	    return 'A';
1.814     raeburn  6328:         } elsif ($thisallowed eq 'B') {
                   6329:             return 'B';
1.766     albertel 6330: 	} else {
                   6331: 	    return '1';
                   6332: 	}
1.52      www      6333:     }
1.29      www      6334: 
1.52      www      6335: #
                   6336: # Now user is definitely in a course
                   6337: #
1.53      www      6338: 
                   6339: 
                   6340: # Course preferences
                   6341: 
                   6342:    if ($thisallowed=~/C/) {
1.620     albertel 6343:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6344:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6345:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6346: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6347: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6348: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6349: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6350: 			$env{'request.course.id'});
                   6351: 	   }
1.237     www      6352:            return '';
                   6353:        }
                   6354: 
1.620     albertel 6355:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6356: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6357: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6358: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6359: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6360: 			$env{'request.course.id'});
                   6361: 	   }
1.54      www      6362:            return '';
                   6363:        }
1.53      www      6364:    }
                   6365: 
                   6366: # Resource preferences
                   6367: 
                   6368:    if ($thisallowed=~/R/) {
1.620     albertel 6369:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6370:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6371: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6372: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6373: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6374: 	   }
                   6375: 	   return '';
1.54      www      6376:        }
1.53      www      6377:    }
1.30      www      6378: 
1.246     www      6379: # Restricted by state or randomout?
1.30      www      6380: 
1.52      www      6381:    if ($thisallowed=~/X/) {
1.620     albertel 6382:       if ($env{'acc.randomout'}) {
1.579     albertel 6383: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6384:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6385:             return ''; 
                   6386:          }
1.247     www      6387:       }
                   6388:       if (&condval($statecond)) {
1.52      www      6389: 	 return '2';
                   6390:       } else {
                   6391:          return '';
                   6392:       }
                   6393:    }
1.30      www      6394: 
1.766     albertel 6395:     if ($thisallowed eq 'A') {
                   6396: 	return 'A';
1.814     raeburn  6397:     } elsif ($thisallowed eq 'B') {
                   6398:         return 'B';
1.766     albertel 6399:     }
1.52      www      6400:    return 'F';
1.232     www      6401: }
1.1162    raeburn  6402: 
                   6403: sub get_comm_blocks {
                   6404:     my ($cdom,$cnum) = @_;
                   6405:     if ($cdom eq '' || $cnum eq '') {
                   6406:         return unless ($env{'request.course.id'});
                   6407:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6408:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6409:     }
                   6410:     my %commblocks;
                   6411:     my $hashid=$cdom.'_'.$cnum;
                   6412:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6413:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6414:         %commblocks = %{$blocksref};
                   6415:     } else {
                   6416:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6417:         my $cachetime = 600;
                   6418:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6419:     }
                   6420:     return %commblocks;
                   6421: }
                   6422: 
                   6423: sub has_comm_blocking {
                   6424:     my ($priv,$symb,$uri,$blocks) = @_;
                   6425:     return unless ($env{'request.course.id'});
                   6426:     return unless ($priv eq 'bre');
                   6427:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6428:     my %commblocks;
                   6429:     if (ref($blocks) eq 'HASH') {
                   6430:         %commblocks = %{$blocks};
                   6431:     } else {
                   6432:         %commblocks = &get_comm_blocks();
                   6433:     }
                   6434:     return unless (keys(%commblocks) > 0);
                   6435:     if (!$symb) { $symb=&symbread($uri,1); }
                   6436:     my ($map,$resid,undef)=&decode_symb($symb);
                   6437:     my %tocheck = (
                   6438:                     maps      => $map,
                   6439:                     resources => $symb,
                   6440:                   );
                   6441:     my @blockers;
                   6442:     my $now = time;
1.1163    raeburn  6443:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6444:     foreach my $block (keys(%commblocks)) {
                   6445:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6446:             my ($start,$end) = ($1,$2);
                   6447:             if ($start <= $now && $end >= $now) {
                   6448:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6449:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6450:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6451:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6452:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6453:                                     push(@blockers,$block);
                   6454:                                 }
                   6455:                             }
                   6456:                         }
                   6457:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6458:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6459:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6460:                                     push(@blockers,$block);
                   6461:                                 }
                   6462:                             }
                   6463:                         }
                   6464:                     }
                   6465:                 }
                   6466:             }
                   6467:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6468:             my $item = $1;
1.1163    raeburn  6469:             my @to_test;
1.1162    raeburn  6470:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6471:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6472:                     my $check_interval;
                   6473:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6474:                         my @interval;
                   6475:                         my $type = 'map';
                   6476:                         if ($item eq 'course') {
                   6477:                             $type = 'course';
                   6478:                             @interval=&EXT("resource.0.interval");
                   6479:                         } else {
                   6480:                             if ($item =~ /___\d+___/) {
                   6481:                                 $type = 'resource';
                   6482:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6483:                                 if (ref($navmap)) {                        
                   6484:                                     my $res = $navmap->getBySymb($item); 
                   6485:                                     push(@to_test,$res);
                   6486:                                 }
1.1162    raeburn  6487:                             } else {
                   6488:                                 my $mapsymb = &symbread($item,1);
                   6489:                                 if ($mapsymb) {
                   6490:                                     if (ref($navmap)) {
                   6491:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6492:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6493:                                         foreach my $res (@to_test) {
1.1162    raeburn  6494:                                             my $symb = $res->symb();
                   6495:                                             next if ($symb eq $mapsymb);
                   6496:                                             if ($symb ne '') {
                   6497:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6498:                                                 last;
                   6499:                                             }
                   6500:                                         }
                   6501:                                     }
                   6502:                                 }
                   6503:                             }
                   6504:                         }
                   6505:                         if ($interval[0] =~ /\d+/) {
                   6506:                             my $first_access;
                   6507:                             if ($type eq 'resource') {
                   6508:                                 $first_access=&get_first_access($interval[1],$item);
                   6509:                             } elsif ($type eq 'map') {
                   6510:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6511:                             } else {
                   6512:                                 $first_access=&get_first_access($interval[1]);
                   6513:                             }
                   6514:                             if ($first_access) {
                   6515:                                 my $timesup = $first_access+$interval[0];
                   6516:                                 if ($timesup > $now) {
1.1163    raeburn  6517:                                     foreach my $res (@to_test) {
                   6518:                                         if ($res->is_problem()) {
                   6519:                                             if ($res->completable()) {
                   6520:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6521:                                                     push(@blockers,$block);
                   6522:                                                 }
                   6523:                                                 last;
                   6524:                                             }
                   6525:                                         }
1.1162    raeburn  6526:                                     }
                   6527:                                 }
                   6528:                             }
                   6529:                         }
                   6530:                     }
                   6531:                 }
                   6532:             }
                   6533:         }
                   6534:     }
                   6535:     return @blockers;
                   6536: }
                   6537: 
                   6538: sub check_docs_block {
                   6539:     my ($docsblock,$tocheck) =@_;
                   6540:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6541:         return;
                   6542:     }
                   6543:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6544:         if ($tocheck->{'maps'}) {
                   6545:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6546:                 return 1;
                   6547:             }
                   6548:         }
                   6549:     }
                   6550:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6551:         if ($tocheck->{'resources'}) {
                   6552:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6553:                 return 1;
                   6554:             }
                   6555:         }
                   6556:     }
                   6557:     return;
                   6558: }
                   6559: 
1.1133    foxr     6560: #
                   6561: #   Removes the versino from a URI and
                   6562: #   splits it in to its filename and path to the filename.
                   6563: #   Seems like File::Basename could have done this more clearly.
                   6564: #   Parameters:
                   6565: #      $uri   - input URI
                   6566: #   Returns:
                   6567: #     Two element list consisting of 
                   6568: #     $pathname  - the URI up to and excluding the trailing /
                   6569: #     $filename  - The part of the URI following the last /
                   6570: #  NOTE:
                   6571: #    Another realization of this is simply:
                   6572: #    use File::Basename;
                   6573: #    ...
                   6574: #    $uri = shift;
                   6575: #    $filename = basename($uri);
                   6576: #    $path     = dirname($uri);
                   6577: #    return ($filename, $path);
                   6578: #
                   6579: #     The implementation below is probably faster however.
                   6580: #
1.710     albertel 6581: sub split_uri_for_cond {
                   6582:     my $uri=&deversion(&declutter(shift));
                   6583:     my @uriparts=split(/\//,$uri);
                   6584:     my $filename=pop(@uriparts);
                   6585:     my $pathname=join('/',@uriparts);
                   6586:     return ($pathname,$filename);
                   6587: }
1.232     www      6588: # --------------------------------------------------- Is a resource on the map?
                   6589: 
                   6590: sub is_on_map {
1.710     albertel 6591:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6592:     #Trying to find the conditional for the file
1.620     albertel 6593:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6594: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6595:     if ($match) {
1.289     bowersj2 6596: 	return (1,$1);
                   6597:     } else {
1.434     www      6598: 	return (0,0);
1.289     bowersj2 6599:     }
1.12      www      6600: }
                   6601: 
1.427     www      6602: # --------------------------------------------------------- Get symb from alias
                   6603: 
                   6604: sub get_symb_from_alias {
                   6605:     my $symb=shift;
                   6606:     my ($map,$resid,$url)=&decode_symb($symb);
                   6607: # Already is a symb
                   6608:     if ($url) { return $symb; }
                   6609: # Must be an alias
                   6610:     my $aliassymb='';
                   6611:     my %bighash;
1.620     albertel 6612:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6613:                             &GDBM_READER(),0640)) {
                   6614:         my $rid=$bighash{'mapalias_'.$symb};
                   6615: 	if ($rid) {
                   6616: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6617: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6618: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6619: 	}
                   6620:         untie %bighash;
                   6621:     }
                   6622:     return $aliassymb;
                   6623: }
                   6624: 
1.12      www      6625: # ----------------------------------------------------------------- Define Role
                   6626: 
                   6627: sub definerole {
                   6628:   if (allowed('mcr','/')) {
                   6629:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6630:     foreach my $role (split(':',$sysrole)) {
                   6631: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6632:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6633:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6634: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6635:                return "refused:s:$crole&$cqual"; 
                   6636:             }
                   6637:         }
1.191     harris41 6638:     }
1.800     albertel 6639:     foreach my $role (split(':',$domrole)) {
                   6640: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6641:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6642:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6643: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6644:                return "refused:d:$crole&$cqual"; 
                   6645:             }
                   6646:         }
1.191     harris41 6647:     }
1.800     albertel 6648:     foreach my $role (split(':',$courole)) {
                   6649: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6650:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6651:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6652: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6653:                return "refused:c:$crole&$cqual"; 
                   6654:             }
                   6655:         }
1.191     harris41 6656:     }
1.620     albertel 6657:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6658:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6659: 	        "rolesdef_$rolename=".
                   6660:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6661:     return reply($command,$env{'user.home'});
1.12      www      6662:   } else {
                   6663:     return 'refused';
                   6664:   }
1.105     harris41 6665: }
                   6666: 
                   6667: # ---------------- Make a metadata query against the network of library servers
                   6668: 
                   6669: sub metadata_query {
1.244     matthew  6670:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6671:     my %rhash;
1.845     albertel 6672:     my %libserv = &all_library();
1.244     matthew  6673:     my @server_list = (defined($server_array) ? @$server_array
                   6674:                                               : keys(%libserv) );
                   6675:     for my $server (@server_list) {
1.118     harris41 6676: 	unless ($custom or $customshow) {
                   6677: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6678: 	    $rhash{$server}=$reply;
                   6679: 	}
                   6680: 	else {
                   6681: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6682: 			     &escape($custom).':'.&escape($customshow),
                   6683: 			     $server);
                   6684: 	    $rhash{$server}=$reply;
                   6685: 	}
1.112     harris41 6686:     }
1.118     harris41 6687:     return \%rhash;
1.240     www      6688: }
                   6689: 
                   6690: # ----------------------------------------- Send log queries and wait for reply
                   6691: 
                   6692: sub log_query {
                   6693:     my ($uname,$udom,$query,%filters)=@_;
                   6694:     my $uhome=&homeserver($uname,$udom);
                   6695:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6696:     my $uhost=&hostname($uhome);
1.800     albertel 6697:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6698:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6699:                        $uhome);
1.479     albertel 6700:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6701:     return get_query_reply($queryid);
                   6702: }
                   6703: 
1.818     raeburn  6704: # -------------------------- Update MySQL table for portfolio file
                   6705: 
                   6706: sub update_portfolio_table {
1.821     raeburn  6707:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6708:     if ($group ne '') {
                   6709:         $file_name =~s /^\Q$group\E//;
                   6710:     }
1.818     raeburn  6711:     my $homeserver = &homeserver($uname,$udom);
                   6712:     my $queryid=
1.821     raeburn  6713:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6714:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6715:     my $reply = &get_query_reply($queryid);
                   6716:     return $reply;
                   6717: }
                   6718: 
1.899     raeburn  6719: # -------------------------- Update MySQL allusers table
                   6720: 
                   6721: sub update_allusers_table {
                   6722:     my ($uname,$udom,$names) = @_;
                   6723:     my $homeserver = &homeserver($uname,$udom);
                   6724:     my $queryid=
                   6725:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6726:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6727:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6728:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6729:                'generation='.&escape($names->{'generation'}).'%%'.
                   6730:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6731:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6732:     return;
1.899     raeburn  6733: }
                   6734: 
1.508     raeburn  6735: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6736: 
                   6737: sub fetch_enrollment_query {
1.511     raeburn  6738:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6739:     my $homeserver;
1.547     raeburn  6740:     my $maxtries = 1;
1.508     raeburn  6741:     if ($context eq 'automated') {
                   6742:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6743:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6744:     } else {
                   6745:         $homeserver = &homeserver($cnum,$dom);
                   6746:     }
1.838     albertel 6747:     my $host=&hostname($homeserver);
1.506     raeburn  6748:     my $cmd = '';
1.1000    raeburn  6749:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6750:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6751:     }
                   6752:     $cmd =~ s/%%$//;
                   6753:     $cmd = &escape($cmd);
                   6754:     my $query = 'fetchenrollment';
1.620     albertel 6755:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6756:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6757:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6758:         return 'error: '.$queryid;
                   6759:     }
1.506     raeburn  6760:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6761:     my $tries = 1;
                   6762:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6763:         $reply = &get_query_reply($queryid);
                   6764:         $tries ++;
                   6765:     }
1.526     raeburn  6766:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6767:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6768:     } else {
1.901     albertel 6769:         my @responses = split(/:/,$reply);
1.515     raeburn  6770:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6771:             foreach my $line (@responses) {
                   6772:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6773:                 $$replyref{$key} = $value;
                   6774:             }
                   6775:         } else {
1.1117    foxr     6776:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6777:             foreach my $line (@responses) {
                   6778:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6779:                 $$replyref{$key} = $value;
                   6780:                 if ($value > 0) {
1.800     albertel 6781:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6782:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6783:                         my $destname = $pathname.'/'.$filename;
                   6784:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6785:                         if ($xml_classlist =~ /^error/) {
                   6786:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6787:                         } else {
1.506     raeburn  6788:                             if ( open(FILE,">$destname") ) {
                   6789:                                 print FILE &unescape($xml_classlist);
                   6790:                                 close(FILE);
1.526     raeburn  6791:                             } else {
                   6792:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6793:                             }
                   6794:                         }
                   6795:                     }
                   6796:                 }
                   6797:             }
                   6798:         }
                   6799:         return 'ok';
                   6800:     }
                   6801:     return 'error';
                   6802: }
                   6803: 
1.242     www      6804: sub get_query_reply {
                   6805:     my $queryid=shift;
1.1117    foxr     6806:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6807:     my $reply='';
                   6808:     for (1..100) {
                   6809: 	sleep 2;
                   6810:         if (-e $replyfile.'.end') {
1.448     albertel 6811: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6812: 		$reply = join('',<$fh>);
                   6813: 		close($fh);
1.240     www      6814: 	   } else { return 'error: reply_file_error'; }
1.242     www      6815:            return &unescape($reply);
                   6816: 	}
1.240     www      6817:     }
1.242     www      6818:     return 'timeout:'.$queryid;
1.240     www      6819: }
                   6820: 
                   6821: sub courselog_query {
1.241     www      6822: #
                   6823: # possible filters:
                   6824: # url: url or symb
                   6825: # username
                   6826: # domain
                   6827: # action: view, submit, grade
                   6828: # start: timestamp
                   6829: # end: timestamp
                   6830: #
1.240     www      6831:     my (%filters)=@_;
1.620     albertel 6832:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6833:     if ($filters{'url'}) {
                   6834: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6835:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6836:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6837:     }
1.620     albertel 6838:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6839:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6840:     return &log_query($cname,$cdom,'courselog',%filters);
                   6841: }
                   6842: 
                   6843: sub userlog_query {
1.858     raeburn  6844: #
                   6845: # possible filters:
                   6846: # action: log check role
                   6847: # start: timestamp
                   6848: # end: timestamp
                   6849: #
1.240     www      6850:     my ($uname,$udom,%filters)=@_;
                   6851:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6852: }
                   6853: 
1.506     raeburn  6854: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6855: 
                   6856: sub auto_run {
1.508     raeburn  6857:     my ($cnum,$cdom) = @_;
1.876     raeburn  6858:     my $response = 0;
                   6859:     my $settings;
                   6860:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6861:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6862:         $settings = $domconfig{'autoenroll'};
                   6863:         if ($settings->{'run'} eq '1') {
                   6864:             $response = 1;
                   6865:         }
                   6866:     } else {
1.934     raeburn  6867:         my $homeserver;
                   6868:         if (&is_course($cdom,$cnum)) {
                   6869:             $homeserver = &homeserver($cnum,$cdom);
                   6870:         } else {
                   6871:             $homeserver = &domain($cdom,'primary');
                   6872:         }
                   6873:         if ($homeserver ne 'no_host') {
                   6874:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6875:         }
1.876     raeburn  6876:     }
1.506     raeburn  6877:     return $response;
                   6878: }
1.776     albertel 6879: 
1.506     raeburn  6880: sub auto_get_sections {
1.508     raeburn  6881:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6882:     my $homeserver;
                   6883:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6884:         $homeserver = &homeserver($cnum,$cdom);
                   6885:     }
                   6886:     if (!defined($homeserver)) { 
                   6887:         if ($cdom =~ /^$match_domain$/) {
                   6888:             $homeserver = &domain($cdom,'primary');
                   6889:         }
                   6890:     }
                   6891:     my @secs;
                   6892:     if (defined($homeserver)) {
                   6893:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6894:         unless ($response eq 'refused') {
                   6895:             @secs = split(/:/,$response);
                   6896:         }
1.506     raeburn  6897:     }
                   6898:     return @secs;
                   6899: }
1.776     albertel 6900: 
1.506     raeburn  6901: sub auto_new_course {
1.1099    raeburn  6902:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6903:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6904:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6905:     return $response;
                   6906: }
1.776     albertel 6907: 
1.506     raeburn  6908: sub auto_validate_courseID {
1.508     raeburn  6909:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6910:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6911:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6912:     return $response;
                   6913: }
1.776     albertel 6914: 
1.1007    raeburn  6915: sub auto_validate_instcode {
1.1020    raeburn  6916:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6917:     my ($homeserver,$response);
                   6918:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6919:         $homeserver = &homeserver($cnum,$cdom);
                   6920:     }
                   6921:     if (!defined($homeserver)) {
                   6922:         if ($cdom =~ /^$match_domain$/) {
                   6923:             $homeserver = &domain($cdom,'primary');
                   6924:         }
                   6925:     }
1.1065    raeburn  6926:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6927:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6928:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6929:     return ($outcome,$description);
1.1007    raeburn  6930: }
                   6931: 
1.506     raeburn  6932: sub auto_create_password {
1.873     raeburn  6933:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6934:     my ($homeserver,$response);
1.506     raeburn  6935:     my $create_passwd = 0;
                   6936:     my $authchk = '';
1.873     raeburn  6937:     if ($udom =~ /^$match_domain$/) {
                   6938:         $homeserver = &domain($udom,'primary');
                   6939:     }
                   6940:     if ($homeserver eq '') {
                   6941:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6942:             $homeserver = &homeserver($cnum,$cdom);
                   6943:         }
                   6944:     }
                   6945:     if ($homeserver eq '') {
                   6946:         $authchk = 'nodomain';
1.506     raeburn  6947:     } else {
1.873     raeburn  6948:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6949:         if ($response eq 'refused') {
                   6950:             $authchk = 'refused';
                   6951:         } else {
1.901     albertel 6952:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6953:         }
1.506     raeburn  6954:     }
                   6955:     return ($authparam,$create_passwd,$authchk);
                   6956: }
                   6957: 
1.706     raeburn  6958: sub auto_photo_permission {
                   6959:     my ($cnum,$cdom,$students) = @_;
                   6960:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6961:     my ($outcome,$perm_reqd,$conditions) = 
                   6962: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6963:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6964: 	return (undef,undef);
                   6965:     }
1.706     raeburn  6966:     return ($outcome,$perm_reqd,$conditions);
                   6967: }
                   6968: 
                   6969: sub auto_checkphotos {
                   6970:     my ($uname,$udom,$pid) = @_;
                   6971:     my $homeserver = &homeserver($uname,$udom);
                   6972:     my ($result,$resulttype);
                   6973:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6974: 				   &escape($uname).':'.&escape($pid),
                   6975: 				   $homeserver));
1.709     albertel 6976:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6977: 	return (undef,undef);
                   6978:     }
1.706     raeburn  6979:     if ($outcome) {
                   6980:         ($result,$resulttype) = split(/:/,$outcome);
                   6981:     } 
                   6982:     return ($result,$resulttype);
                   6983: }
                   6984: 
                   6985: sub auto_photochoice {
                   6986:     my ($cnum,$cdom) = @_;
                   6987:     my $homeserver = &homeserver($cnum,$cdom);
                   6988:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6989: 						       &escape($cdom),
                   6990: 						       $homeserver)));
1.709     albertel 6991:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6992: 	return (undef,undef);
                   6993:     }
1.706     raeburn  6994:     return ($update,$comment);
                   6995: }
                   6996: 
                   6997: sub auto_photoupdate {
                   6998:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6999:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7000:     my $host=&hostname($homeserver);
1.706     raeburn  7001:     my $cmd = '';
                   7002:     my $maxtries = 1;
1.800     albertel 7003:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7004:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7005:     }
                   7006:     $cmd =~ s/%%$//;
                   7007:     $cmd = &escape($cmd);
                   7008:     my $query = 'institutionalphotos';
                   7009:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7010:     unless ($queryid=~/^\Q$host\E\_/) {
                   7011:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7012:         return 'error: '.$queryid;
                   7013:     }
                   7014:     my $reply = &get_query_reply($queryid);
                   7015:     my $tries = 1;
                   7016:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7017:         $reply = &get_query_reply($queryid);
                   7018:         $tries ++;
                   7019:     }
                   7020:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7021:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7022:     } else {
                   7023:         my @responses = split(/:/,$reply);
                   7024:         my $outcome = shift(@responses); 
                   7025:         foreach my $item (@responses) {
                   7026:             my ($key,$value) = split(/=/,$item);
                   7027:             $$photo{$key} = $value;
                   7028:         }
                   7029:         return $outcome;
                   7030:     }
                   7031:     return 'error';
                   7032: }
                   7033: 
1.521     raeburn  7034: sub auto_instcode_format {
1.793     albertel 7035:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7036: 	$cat_order) = @_;
1.521     raeburn  7037:     my $courses = '';
1.772     raeburn  7038:     my @homeservers;
1.521     raeburn  7039:     if ($caller eq 'global') {
1.841     albertel 7040: 	my %servers = &get_servers($codedom,'library');
                   7041: 	foreach my $tryserver (keys(%servers)) {
                   7042: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7043: 		push(@homeservers,$tryserver);
                   7044: 	    }
1.584     raeburn  7045:         }
1.1022    raeburn  7046:     } elsif ($caller eq 'requests') {
                   7047:         if ($codedom =~ /^$match_domain$/) {
                   7048:             my $chome = &domain($codedom,'primary');
                   7049:             unless ($chome eq 'no_host') {
                   7050:                 push(@homeservers,$chome);
                   7051:             }
                   7052:         }
1.521     raeburn  7053:     } else {
1.772     raeburn  7054:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7055:     }
1.793     albertel 7056:     foreach my $code (keys(%{$instcodes})) {
                   7057:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7058:     }
                   7059:     chop($courses);
1.772     raeburn  7060:     my $ok_response = 0;
                   7061:     my $response;
                   7062:     while (@homeservers > 0 && $ok_response == 0) {
                   7063:         my $server = shift(@homeservers); 
                   7064:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7065:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7066:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7067: 		split(/:/,$response);
1.772     raeburn  7068:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7069:             push(@{$codetitles},&str2array($codetitles_str));
                   7070:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7071:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7072:             $ok_response = 1;
                   7073:         }
                   7074:     }
                   7075:     if ($ok_response) {
1.521     raeburn  7076:         return 'ok';
1.772     raeburn  7077:     } else {
                   7078:         return $response;
1.521     raeburn  7079:     }
                   7080: }
                   7081: 
1.792     raeburn  7082: sub auto_instcode_defaults {
                   7083:     my ($domain,$returnhash,$code_order) = @_;
                   7084:     my @homeservers;
1.841     albertel 7085: 
                   7086:     my %servers = &get_servers($domain,'library');
                   7087:     foreach my $tryserver (keys(%servers)) {
                   7088: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7089: 	    push(@homeservers,$tryserver);
                   7090: 	}
1.792     raeburn  7091:     }
1.841     albertel 7092: 
1.792     raeburn  7093:     my $response;
1.841     albertel 7094:     foreach my $server (@homeservers) {
1.792     raeburn  7095:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7096:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7097: 	
                   7098: 	foreach my $pair (split(/\&/,$response)) {
                   7099: 	    my ($name,$value)=split(/\=/,$pair);
                   7100: 	    if ($name eq 'code_order') {
                   7101: 		@{$code_order} = split(/\&/,&unescape($value));
                   7102: 	    } else {
                   7103: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7104: 	    }
                   7105: 	}
                   7106: 	return 'ok';
1.792     raeburn  7107:     }
1.841     albertel 7108: 
                   7109:     return $response;
1.1003    raeburn  7110: }
                   7111: 
                   7112: sub auto_possible_instcodes {
1.1007    raeburn  7113:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7114:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7115:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7116:         return;
                   7117:     }
1.1003    raeburn  7118:     my (@homeservers,$uhome);
                   7119:     if (defined(&domain($domain,'primary'))) {
                   7120:         $uhome=&domain($domain,'primary');
                   7121:         push(@homeservers,&domain($domain,'primary'));
                   7122:     } else {
                   7123:         my %servers = &get_servers($domain,'library');
                   7124:         foreach my $tryserver (keys(%servers)) {
                   7125:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7126:                 push(@homeservers,$tryserver);
                   7127:             }
                   7128:         }
                   7129:     }
                   7130:     my $response;
                   7131:     foreach my $server (@homeservers) {
                   7132:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7133:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7134:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7135:             split(':',$response);
                   7136:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7137:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7138:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7139:             my ($name,$value)=split('=',$item);
                   7140:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7141:         }
                   7142:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7143:             my ($name,$value)=split('=',$item);
                   7144:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7145:         }
                   7146:         return 'ok';
                   7147:     }
                   7148:     return $response;
                   7149: }
1.792     raeburn  7150: 
1.1010    raeburn  7151: sub auto_courserequest_checks {
                   7152:     my ($dom) = @_;
1.1020    raeburn  7153:     my ($homeserver,%validations);
                   7154:     if ($dom =~ /^$match_domain$/) {
                   7155:         $homeserver = &domain($dom,'primary');
                   7156:     }
                   7157:     unless ($homeserver eq 'no_host') {
                   7158:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7159:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7160:             my @items = split(/&/,$response);
                   7161:             foreach my $item (@items) {
                   7162:                 my ($key,$value) = split('=',$item);
                   7163:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7164:             }
                   7165:         }
                   7166:     }
1.1010    raeburn  7167:     return %validations; 
                   7168: }
                   7169: 
1.1020    raeburn  7170: sub auto_courserequest_validation {
                   7171:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7172:     my ($homeserver,$response);
                   7173:     if ($dom =~ /^$match_domain$/) {
                   7174:         $homeserver = &domain($dom,'primary');
                   7175:     }
                   7176:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7177:           
1.1020    raeburn  7178:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7179:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7180:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7181:                                     $homeserver));
                   7182:     }
                   7183:     return $response;
                   7184: }
                   7185: 
1.777     albertel 7186: sub auto_validate_class_sec {
1.918     raeburn  7187:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7188:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7189:     my $ownerlist;
                   7190:     if (ref($owners) eq 'ARRAY') {
                   7191:         $ownerlist = join(',',@{$owners});
                   7192:     } else {
                   7193:         $ownerlist = $owners;
                   7194:     }
1.773     raeburn  7195:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7196:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7197:     return $response;
                   7198: }
                   7199: 
1.679     raeburn  7200: # ------------------------------------------------------- Course Group routines
                   7201: 
                   7202: sub get_coursegroups {
1.809     raeburn  7203:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7204:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7205: }
                   7206: 
1.679     raeburn  7207: sub modify_coursegroup {
                   7208:     my ($cdom,$cnum,$groupsettings) = @_;
                   7209:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7210: }
                   7211: 
1.809     raeburn  7212: sub toggle_coursegroup_status {
                   7213:     my ($cdom,$cnum,$group,$action) = @_;
                   7214:     my ($from_namespace,$to_namespace);
                   7215:     if ($action eq 'delete') {
                   7216:         $from_namespace = 'coursegroups';
                   7217:         $to_namespace = 'deleted_groups';
                   7218:     } else {
                   7219:         $from_namespace = 'deleted_groups';
                   7220:         $to_namespace = 'coursegroups';
                   7221:     }
                   7222:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7223:     if (my $tmp = &error(%curr_group)) {
                   7224:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7225:         return ('read error',$tmp);
                   7226:     } else {
                   7227:         my %savedsettings = %curr_group; 
1.809     raeburn  7228:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7229:         my $deloutcome;
                   7230:         if ($result eq 'ok') {
1.809     raeburn  7231:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7232:         } else {
                   7233:             return ('write error',$result);
                   7234:         }
                   7235:         if ($deloutcome eq 'ok') {
                   7236:             return 'ok';
                   7237:         } else {
                   7238:             return ('delete error',$deloutcome);
                   7239:         }
                   7240:     }
                   7241: }
                   7242: 
1.679     raeburn  7243: sub modify_group_roles {
1.957     raeburn  7244:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7245:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7246:     my $role = 'gr/'.&escape($userprivs);
                   7247:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7248:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7249:     if ($result eq 'ok') {
                   7250:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7251:     }
1.679     raeburn  7252:     return $result;
                   7253: }
                   7254: 
                   7255: sub modify_coursegroup_membership {
                   7256:     my ($cdom,$cnum,$membership) = @_;
                   7257:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7258:     return $result;
                   7259: }
                   7260: 
1.682     raeburn  7261: sub get_active_groups {
                   7262:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7263:     my $now = time;
                   7264:     my %groups = ();
                   7265:     foreach my $key (keys(%env)) {
1.811     albertel 7266:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7267:             my ($start,$end) = split(/\./,$env{$key});
                   7268:             if (($end!=0) && ($end<$now)) { next; }
                   7269:             if (($start!=0) && ($start>$now)) { next; }
                   7270:             if ($1 eq $cdom && $2 eq $cnum) {
                   7271:                 $groups{$3} = $env{$key} ;
                   7272:             }
                   7273:         }
                   7274:     }
                   7275:     return %groups;
                   7276: }
                   7277: 
1.683     raeburn  7278: sub get_group_membership {
                   7279:     my ($cdom,$cnum,$group) = @_;
                   7280:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7281: }
                   7282: 
                   7283: sub get_users_groups {
                   7284:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7285:     my @usersgroups;
1.683     raeburn  7286:     my $cachetime=1800;
                   7287: 
                   7288:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7289:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7290:     if (defined($cached)) {
1.734     albertel 7291:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7292:     } else {  
                   7293:         $grouplist = '';
1.816     raeburn  7294:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7295:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7296:         my $access_end = $env{'course.'.$courseid.
                   7297:                               '.default_enrollment_end_date'};
                   7298:         my $now = time;
                   7299:         foreach my $key (keys(%roleshash)) {
                   7300:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7301:                 my $group = $1;
                   7302:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7303:                     my $start = $2;
                   7304:                     my $end = $1;
                   7305:                     if ($start == -1) { next; } # deleted from group
                   7306:                     if (($start!=0) && ($start>$now)) { next; }
                   7307:                     if (($end!=0) && ($end<$now)) {
                   7308:                         if ($access_end && $access_end < $now) {
                   7309:                             if ($access_end - $end < 86400) {
                   7310:                                 push(@usersgroups,$group);
1.733     raeburn  7311:                             }
                   7312:                         }
1.817     raeburn  7313:                         next;
1.733     raeburn  7314:                     }
1.817     raeburn  7315:                     push(@usersgroups,$group);
1.683     raeburn  7316:                 }
                   7317:             }
                   7318:         }
1.817     raeburn  7319:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7320:         $grouplist = join(':',@usersgroups);
                   7321:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7322:     }
1.733     raeburn  7323:     return @usersgroups;
1.683     raeburn  7324: }
                   7325: 
                   7326: sub devalidate_getgroups_cache {
                   7327:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7328:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7329: 
1.683     raeburn  7330:     my $hashid="$udom:$uname:$courseid";
                   7331:     &devalidate_cache_new('getgroups',$hashid);
                   7332: }
                   7333: 
1.12      www      7334: # ------------------------------------------------------------------ Plain Text
                   7335: 
                   7336: sub plaintext {
1.988     raeburn  7337:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7338:     if ($short =~ m{^cr/}) {
1.758     albertel 7339: 	return (split('/',$short))[-1];
                   7340:     }
1.742     raeburn  7341:     if (!defined($cid)) {
                   7342:         $cid = $env{'request.course.id'};
                   7343:     }
                   7344:     my %rolenames = (
1.1008    raeburn  7345:                       Course    => 'std',
                   7346:                       Community => 'alt1',
1.742     raeburn  7347:                     );
1.1037    raeburn  7348:     if ($cid ne '') {
                   7349:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7350:             unless ($forcedefault) {
                   7351:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7352:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7353:                 return &Apache::lonlocal::mt($roletext);
                   7354:             }
                   7355:         }
                   7356:     }
                   7357:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7358:         (defined($rolenames{$type})) && 
                   7359:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7360:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7361:     } elsif ($cid ne '') {
                   7362:         my $crstype = $env{'course.'.$cid.'.type'};
                   7363:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7364:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7365:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7366:         }
1.742     raeburn  7367:     }
1.1037    raeburn  7368:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7369: }
                   7370: 
                   7371: # ----------------------------------------------------------------- Assign Role
                   7372: 
                   7373: sub assignrole {
1.957     raeburn  7374:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7375:         $context)=@_;
1.21      www      7376:     my $mrole;
                   7377:     if ($role =~ /^cr\//) {
1.393     www      7378:         my $cwosec=$url;
1.811     albertel 7379:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7380: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7381:            my $refused = 1;
                   7382:            if ($context eq 'requestcourses') {
                   7383:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7384:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7385:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7386:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7387:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7388:                            if ($crsenv{'internal.courseowner'} eq
                   7389:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7390:                                $refused = '';
                   7391:                            }
                   7392:                        }
                   7393:                    }
                   7394:                }
                   7395:            }
                   7396:            if ($refused) {
                   7397:                &logthis('Refused custom assignrole: '.
                   7398:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7399:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7400:                return 'refused';
                   7401:            }
1.104     www      7402:         }
1.21      www      7403:         $mrole='cr';
1.678     raeburn  7404:     } elsif ($role =~ /^gr\//) {
                   7405:         my $cwogrp=$url;
1.811     albertel 7406:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7407:         unless (&allowed('mdg',$cwogrp)) {
                   7408:             &logthis('Refused group assignrole: '.
                   7409:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7410:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7411:             return 'refused';
                   7412:         }
                   7413:         $mrole='gr';
1.21      www      7414:     } else {
1.82      www      7415:         my $cwosec=$url;
1.811     albertel 7416:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7417:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7418:             my $refused;
                   7419:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7420:                 if (!(&allowed('c'.$role,$url))) {
                   7421:                     $refused = 1;
                   7422:                 }
                   7423:             } else {
                   7424:                 $refused = 1;
                   7425:             }
1.947     raeburn  7426:             if ($refused) {
1.1045    raeburn  7427:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7428:                 if (!$selfenroll && $context eq 'course') {
                   7429:                     my %crsenv;
                   7430:                     if ($role eq 'cc' || $role eq 'co') {
                   7431:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7432:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7433:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7434:                                 if ($crsenv{'internal.courseowner'} eq 
                   7435:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7436:                                     $refused = '';
                   7437:                                 }
                   7438:                             }
                   7439:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7440:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7441:                                 if ($crsenv{'internal.courseowner'} eq 
                   7442:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7443:                                     $refused = '';
                   7444:                                 }
                   7445:                             }
                   7446:                         }
                   7447:                     }
                   7448:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7449:                     $refused = '';
1.1017    raeburn  7450:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7451:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7452:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7453:                         my $wrongcc;
                   7454:                         if ($cnum =~ /^$match_community$/) {
                   7455:                             $wrongcc = 1 if ($role eq 'cc');
                   7456:                         } else {
                   7457:                             $wrongcc = 1 if ($role eq 'co');
                   7458:                         }
                   7459:                         unless ($wrongcc) {
                   7460:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7461:                             if ($crsenv{'internal.courseowner'} eq 
                   7462:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7463:                                 $refused = '';
                   7464:                             }
1.1017    raeburn  7465:                         }
                   7466:                     }
                   7467:                 }
                   7468:                 if ($refused) {
1.947     raeburn  7469:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7470:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7471: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7472:                     return 'refused';
                   7473:                 }
1.932     raeburn  7474:             }
1.1131    raeburn  7475:         } elsif ($role eq 'au') {
                   7476:             if ($url ne '/'.$udom.'/') {
                   7477:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7478:                          ' to assign author role for '.$uname.':'.$udom.
                   7479:                          ' in domain: '.$url.' refused (wrong domain).');
                   7480:                 return 'refused';
                   7481:             }
1.104     www      7482:         }
1.21      www      7483:         $mrole=$role;
                   7484:     }
1.620     albertel 7485:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7486:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7487:     if ($end) { $command.='_'.$end; }
1.21      www      7488:     if ($start) {
                   7489: 	if ($end) { 
1.81      www      7490:            $command.='_'.$start; 
1.21      www      7491:         } else {
1.81      www      7492:            $command.='_0_'.$start;
1.21      www      7493:         }
                   7494:     }
1.739     raeburn  7495:     my $origstart = $start;
                   7496:     my $origend = $end;
1.957     raeburn  7497:     my $delflag;
1.357     www      7498: # actually delete
                   7499:     if ($deleteflag) {
1.373     www      7500: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7501: # modify command to delete the role
1.620     albertel 7502:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7503:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7504: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7505: # set start and finish to negative values for userrolelog
                   7506:            $start=-1;
                   7507:            $end=-1;
1.957     raeburn  7508:            $delflag = 1;
1.357     www      7509:         }
                   7510:     }
                   7511: # send command
1.349     www      7512:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7513: # log new user role if status is ok
1.349     www      7514:     if ($answer eq 'ok') {
1.663     raeburn  7515: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7516: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7517:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7518:         unless ($role =~ /^gr/) {
                   7519:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7520:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7521:         }
1.1053    raeburn  7522:         if ($role eq 'cc') {
                   7523:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7524:         }
1.349     www      7525:     }
                   7526:     return $answer;
1.169     harris41 7527: }
                   7528: 
1.1053    raeburn  7529: sub autoupdate_coowners {
                   7530:     my ($url,$end,$start,$uname,$udom) = @_;
                   7531:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7532:     if (($cdom ne '') && ($cnum ne '')) {
                   7533:         my $now = time;
                   7534:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7535:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7536:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7537:             my $instcode = $coursehash{'internal.coursecode'};
                   7538:             if ($instcode ne '') {
1.1056    raeburn  7539:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7540:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7541:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7542:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7543:                         if ($result eq 'valid') {
                   7544:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7545:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7546:                                     push(@newcoowners,$coowner);
                   7547:                                 }
                   7548:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7549:                                     push(@newcoowners,$uname.':'.$udom);
                   7550:                                 }
                   7551:                                 @newcoowners = sort(@newcoowners);
                   7552:                             } else {
                   7553:                                 push(@newcoowners,$uname.':'.$udom);
                   7554:                             }
                   7555:                         } else {
                   7556:                             if ($coursehash{'internal.co-owners'}) {
                   7557:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7558:                                     unless ($coowner eq $uname.':'.$udom) {
                   7559:                                         push(@newcoowners,$coowner);
                   7560:                                     }
                   7561:                                 }
                   7562:                                 unless (@newcoowners > 0) {
                   7563:                                     $delcoowners = 1;
                   7564:                                     $coowners = '';
                   7565:                                 }
                   7566:                             }
                   7567:                         }
                   7568:                         if (@newcoowners || $delcoowners) {
                   7569:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7570:                                             $delcoowners,@newcoowners);
                   7571:                         }
                   7572:                     }
                   7573:                 }
                   7574:             }
                   7575:         }
                   7576:     }
                   7577: }
                   7578: 
                   7579: sub store_coowners {
                   7580:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7581:     my $cid = $cdom.'_'.$cnum;
                   7582:     my ($coowners,$delresult,$putresult);
                   7583:     if (@newcoowners) {
                   7584:         $coowners = join(',',@newcoowners);
                   7585:         my %coownershash = (
                   7586:                             'internal.co-owners' => $coowners,
                   7587:                            );
                   7588:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7589:         if ($putresult eq 'ok') {
                   7590:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7591:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7592:             }
                   7593:         }
                   7594:     }
                   7595:     if ($delcoowners) {
                   7596:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7597:         if ($delresult eq 'ok') {
                   7598:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7599:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7600:             }
                   7601:         }
                   7602:     }
                   7603:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7604:         my %crsinfo =
                   7605:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7606:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7607:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7608:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7609:         }
                   7610:     }
                   7611: }
                   7612: 
1.169     harris41 7613: # -------------------------------------------------- Modify user authentication
1.197     www      7614: # Overrides without validation
                   7615: 
1.169     harris41 7616: sub modifyuserauth {
                   7617:     my ($udom,$uname,$umode,$upass)=@_;
                   7618:     my $uhome=&homeserver($uname,$udom);
1.197     www      7619:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7620:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7621:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7622:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7623:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7624: 		     &escape($upass),$uhome);
1.620     albertel 7625:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7626:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7627:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7628:     &log($udom,,$uname,$uhome,
1.620     albertel 7629:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7630:                                      $env{'user.name'}.', '.$umode.
1.197     www      7631:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7632:     unless ($reply eq 'ok') {
1.197     www      7633:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7634: 	return 'error: '.$reply;
                   7635:     }   
1.170     harris41 7636:     return 'ok';
1.80      www      7637: }
                   7638: 
1.81      www      7639: # --------------------------------------------------------------- Modify a user
1.80      www      7640: 
1.81      www      7641: sub modifyuser {
1.206     matthew  7642:     my ($udom,    $uname, $uid,
                   7643:         $umode,   $upass, $first,
                   7644:         $middle,  $last,  $gene,
1.1058    raeburn  7645:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7646:     $udom= &LONCAPA::clean_domain($udom);
                   7647:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7648:     my $showcandelete = 'none';
                   7649:     if (ref($candelete) eq 'ARRAY') {
                   7650:         if (@{$candelete} > 0) {
                   7651:             $showcandelete = join(', ',@{$candelete});
                   7652:         }
                   7653:     }
1.81      www      7654:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7655:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7656: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7657:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7658:                                      ' desiredhome not specified'). 
1.620     albertel 7659:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7660:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7661:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7662:     my $newuser;
                   7663:     if ($uhome eq 'no_host') {
                   7664:         $newuser = 1;
                   7665:     }
1.80      www      7666: # ----------------------------------------------------------------- Create User
1.406     albertel 7667:     if (($uhome eq 'no_host') && 
                   7668: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7669:         my $unhome='';
1.844     albertel 7670:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7671:             $unhome = $desiredhome;
1.620     albertel 7672: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7673: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7674:         } else { # load balancing routine for determining $unhome
1.81      www      7675:             my $loadm=10000000;
1.841     albertel 7676: 	    my %servers = &get_servers($udom,'library');
                   7677: 	    foreach my $tryserver (keys(%servers)) {
                   7678: 		my $answer=reply('load',$tryserver);
                   7679: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7680: 		    $loadm=$answer;
                   7681: 		    $unhome=$tryserver;
                   7682: 		}
1.80      www      7683: 	    }
                   7684:         }
                   7685:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7686: 	    return 'error: unable to find a home server for '.$uname.
                   7687:                    ' in domain '.$udom;
1.80      www      7688:         }
                   7689:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7690:                          &escape($upass),$unhome);
                   7691: 	unless ($reply eq 'ok') {
                   7692:             return 'error: '.$reply;
                   7693:         }   
1.230     stredwic 7694:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7695:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7696: 	    return 'error: unable verify users home machine.';
1.80      www      7697:         }
1.209     matthew  7698:     }   # End of creation of new user
1.80      www      7699: # ---------------------------------------------------------------------- Add ID
                   7700:     if ($uid) {
                   7701:        $uid=~tr/A-Z/a-z/;
                   7702:        my %uidhash=&idrget($udom,$uname);
1.196     www      7703:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7704:          && (!$forceid)) {
1.80      www      7705: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7706: 	      return 'error: user id "'.$uid.'" does not match '.
                   7707:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7708:           }
                   7709:        } else {
                   7710: 	  &idput($udom,($uname => $uid));
                   7711:        }
                   7712:     }
                   7713: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7714:     my @tmp=&get('environment',
1.899     raeburn  7715: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7716:                     'permanentemail','inststatus'],
1.134     albertel 7717: 		   $udom,$uname);
1.1075    raeburn  7718:     my (%names,%oldnames);
1.313     matthew  7719:     if ($tmp[0] =~ m/^error:.*/) { 
                   7720:         %names=(); 
                   7721:     } else {
                   7722:         %names = @tmp;
1.1075    raeburn  7723:         %oldnames = %names;
1.313     matthew  7724:     }
1.388     www      7725: #
1.1058    raeburn  7726: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7727: # of users did not contain them), do not overwrite existing values
                   7728: # unless field is in $candelete array ref.  
                   7729: #
                   7730: 
                   7731:     my @fields = ('firstname','middlename','lastname','generation',
                   7732:                   'permanentemail','id');
                   7733:     my %newvalues;
                   7734:     if (ref($candelete) eq 'ARRAY') {
                   7735:         foreach my $field (@fields) {
                   7736:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7737:                 if ($field eq 'firstname') {
                   7738:                     $names{$field} = $first;
                   7739:                 } elsif ($field eq 'middlename') {
                   7740:                     $names{$field} = $middle;
                   7741:                 } elsif ($field eq 'lastname') {
                   7742:                     $names{$field} = $last;
                   7743:                 } elsif ($field eq 'generation') { 
                   7744:                     $names{$field} = $gene;
                   7745:                 } elsif ($field eq 'permanentemail') {
                   7746:                     $names{$field} = $email;
                   7747:                 } elsif ($field eq 'id') {
                   7748:                     $names{$field}  = $uid;
                   7749:                 }
                   7750:             }
                   7751:         }
                   7752:     }
1.388     www      7753:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7754:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7755:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7756:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7757:     if ($email) {
                   7758:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7759:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7760:     }
1.899     raeburn  7761:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7762:     if (defined($inststatus)) {
                   7763:         $names{'inststatus'} = '';
                   7764:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7765:         if (ref($usertypes) eq 'HASH') {
                   7766:             my @okstatuses; 
                   7767:             foreach my $item (split(/:/,$inststatus)) {
                   7768:                 if (defined($usertypes->{$item})) {
                   7769:                     push(@okstatuses,$item);  
                   7770:                 }
                   7771:             }
                   7772:             if (@okstatuses) {
                   7773:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7774:             }
                   7775:         }
                   7776:     }
1.1075    raeburn  7777:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7778:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7779:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7780:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7781:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7782:     } else {
                   7783:         $logmsg .= ' during self creation';
                   7784:     }
1.1075    raeburn  7785:     my $changed;
                   7786:     if ($newuser) {
                   7787:         $changed = 1;
                   7788:     } else {
                   7789:         foreach my $field (@fields) {
                   7790:             if ($names{$field} ne $oldnames{$field}) {
                   7791:                 $changed = 1;
                   7792:                 last;
                   7793:             }
                   7794:         }
                   7795:     }
                   7796:     unless ($changed) {
                   7797:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7798:         &logthis($logmsg);
                   7799:         return 'ok';
                   7800:     }
                   7801:     my $reply = &put('environment', \%names, $udom,$uname);
                   7802:     if ($reply ne 'ok') { 
                   7803:         return 'error: '.$reply;
                   7804:     }
1.1087    raeburn  7805:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7806:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7807:     }
1.1075    raeburn  7808:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7809:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7810:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7811:     &logthis($logmsg);
1.134     albertel 7812:     return 'ok';
1.80      www      7813: }
                   7814: 
1.81      www      7815: # -------------------------------------------------------------- Modify student
1.80      www      7816: 
1.81      www      7817: sub modifystudent {
                   7818:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7819:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7820:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7821:     if (!$cid) {
1.620     albertel 7822: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7823: 	    return 'not_in_class';
                   7824: 	}
1.80      www      7825:     }
                   7826: # --------------------------------------------------------------- Make the user
1.81      www      7827:     my $reply=&modifyuser
1.209     matthew  7828: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7829:          $desiredhome,$email,$inststatus);
1.80      www      7830:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7831:     # This will cause &modify_student_enrollment to get the uid from the
                   7832:     # students environment
                   7833:     $uid = undef if (!$forceid);
1.455     albertel 7834:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7835: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7836:     return $reply;
                   7837: }
                   7838: 
                   7839: sub modify_student_enrollment {
1.957     raeburn  7840:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7841:     my ($cdom,$cnum,$chome);
                   7842:     if (!$cid) {
1.620     albertel 7843: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7844: 	    return 'not_in_class';
                   7845: 	}
1.620     albertel 7846: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7847: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7848:     } else {
                   7849: 	($cdom,$cnum)=split(/_/,$cid);
                   7850:     }
1.620     albertel 7851:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7852:     if (!$chome) {
1.457     raeburn  7853: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7854:     }
1.455     albertel 7855:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7856:     # Make sure the user exists
1.81      www      7857:     my $uhome=&homeserver($uname,$udom);
                   7858:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7859: 	return 'error: no such user';
                   7860:     }
1.297     matthew  7861:     # Get student data if we were not given enough information
                   7862:     if (!defined($first)  || $first  eq '' || 
                   7863:         !defined($last)   || $last   eq '' || 
                   7864:         !defined($uid)    || $uid    eq '' || 
                   7865:         !defined($middle) || $middle eq '' || 
                   7866:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7867:         # They did not supply us with enough data to enroll the student, so
                   7868:         # we need to pick up more information.
1.297     matthew  7869:         my %tmp = &get('environment',
1.294     matthew  7870:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7871:                        ,$udom,$uname);
                   7872: 
1.800     albertel 7873:         #foreach my $key (keys(%tmp)) {
                   7874:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7875:         #}
1.294     matthew  7876:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7877:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7878:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7879:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7880:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7881:     }
1.556     albertel 7882:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7883:     my $user = "$uname:$udom";
                   7884:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7885:     my $reply=cput('classlist',
1.1148    raeburn  7886: 		   {$user => 
1.515     raeburn  7887: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7888: 		   $cdom,$cnum);
1.1148    raeburn  7889:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7890:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7891:     } else { 
1.81      www      7892: 	return 'error: '.$reply;
                   7893:     }
1.297     matthew  7894:     # Add student role to user
1.83      www      7895:     my $uurl='/'.$cid;
1.81      www      7896:     $uurl=~s/\_/\//g;
                   7897:     if ($usec) {
                   7898: 	$uurl.='/'.$usec;
                   7899:     }
1.1148    raeburn  7900:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7901:                              $selfenroll,$context);
                   7902:     if ($result ne 'ok') {
                   7903:         if ($old_entry{$user} ne '') {
                   7904:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7905:         } else {
                   7906:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7907:         }
                   7908:     }
                   7909:     return $result; 
1.21      www      7910: }
                   7911: 
1.556     albertel 7912: sub format_name {
                   7913:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7914:     my $name;
                   7915:     if ($first ne 'lastname') {
                   7916: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7917:     } else {
                   7918: 	if ($lastname=~/\S/) {
                   7919: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7920: 	    $name=~s/\s+,/,/;
                   7921: 	} else {
                   7922: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7923: 	}
                   7924:     }
                   7925:     $name=~s/^\s+//;
                   7926:     $name=~s/\s+$//;
                   7927:     $name=~s/\s+/ /g;
                   7928:     return $name;
                   7929: }
                   7930: 
1.84      www      7931: # ------------------------------------------------- Write to course preferences
                   7932: 
                   7933: sub writecoursepref {
                   7934:     my ($courseid,%prefs)=@_;
                   7935:     $courseid=~s/^\///;
                   7936:     $courseid=~s/\_/\//g;
                   7937:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7938:     my $chome=homeserver($cnum,$cdomain);
                   7939:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7940: 	return 'error: no such course';
                   7941:     }
                   7942:     my $cstring='';
1.800     albertel 7943:     foreach my $pref (keys(%prefs)) {
                   7944: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7945:     }
1.84      www      7946:     $cstring=~s/\&$//;
                   7947:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7948: }
                   7949: 
                   7950: # ---------------------------------------------------------- Make/modify course
                   7951: 
                   7952: sub createcourse {
1.741     raeburn  7953:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7954:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7955:     $url=&declutter($url);
                   7956:     my $cid='';
1.1028    raeburn  7957:     if ($context eq 'requestcourses') {
                   7958:         my $can_create = 0;
                   7959:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7960:         if ($udom eq $ownerdom) {
                   7961:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7962:                                   $context)) {
                   7963:                 $can_create = 1;
                   7964:             }
                   7965:         } else {
                   7966:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7967:                                            $category);
                   7968:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7969:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7970:                 if (@curr > 0) {
                   7971:                     my @options = qw(approval validate autolimit);
                   7972:                     my $optregex = join('|',@options);
                   7973:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7974:                         $can_create = 1;
                   7975:                     }
                   7976:                 }
                   7977:             }
                   7978:         }
                   7979:         if ($can_create) {
                   7980:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7981:                 unless (&allowed('ccc',$udom)) {
                   7982:                     return 'refused'; 
                   7983:                 }
1.1017    raeburn  7984:             }
                   7985:         } else {
                   7986:             return 'refused';
                   7987:         }
1.1028    raeburn  7988:     } elsif (!&allowed('ccc',$udom)) {
                   7989:         return 'refused';
1.84      www      7990:     }
1.1011    raeburn  7991: # --------------------------------------------------------------- Get Unique ID
                   7992:     my $uname;
                   7993:     if ($cnum =~ /^$match_courseid$/) {
                   7994:         my $chome=&homeserver($cnum,$udom,'true');
                   7995:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7996:             $uname = $cnum;
                   7997:         } else {
1.1038    raeburn  7998:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7999:         }
                   8000:     } else {
1.1038    raeburn  8001:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8002:     }
                   8003:     return $uname if ($uname =~ /^error/);
                   8004: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8005:     if (!defined($course_server)) {
                   8006:         if (defined(&domain($udom,'primary'))) {
                   8007:             $course_server = &domain($udom,'primary');
                   8008:         } else {
                   8009:             $course_server = $env{'user.home'}; 
                   8010:         }
                   8011:     }
                   8012:     my %host_servers =
                   8013:         &Apache::lonnet::get_servers($udom,'library');
                   8014:     unless ($host_servers{$course_server}) {
                   8015:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8016:     }
1.84      www      8017: # ------------------------------------------------------------- Make the course
                   8018:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8019:                       $course_server);
1.84      www      8020:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8021:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8022:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8023: 	return 'error: no such course';
                   8024:     }
1.271     www      8025: # ----------------------------------------------------------------- Course made
1.516     raeburn  8026: # log existence
1.1029    raeburn  8027:     my $now = time;
1.918     raeburn  8028:     my $newcourse = {
                   8029:                     $udom.'_'.$uname => {
1.921     raeburn  8030:                                      description => $description,
                   8031:                                      inst_code   => $inst_code,
                   8032:                                      owner       => $course_owner,
                   8033:                                      type        => $crstype,
1.1029    raeburn  8034:                                      creator     => $env{'user.name'}.':'.
                   8035:                                                     $env{'user.domain'},
                   8036:                                      created     => $now,
                   8037:                                      context     => $context,
1.918     raeburn  8038:                                                 },
                   8039:                     };
1.921     raeburn  8040:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8041: # set toplevel url
1.271     www      8042:     my $topurl=$url;
                   8043:     unless ($nonstandard) {
                   8044: # ------------------------------------------ For standard courses, make top url
                   8045:         my $mapurl=&clutter($url);
1.278     www      8046:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8047:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8048: <map>
                   8049: <resource id="1" type="start"></resource>
                   8050: <resource id="2" src="$mapurl"></resource>
                   8051: <resource id="3" type="finish"></resource>
                   8052: <link index="1" from="1" to="2"></link>
                   8053: <link index="2" from="2" to="3"></link>
                   8054: </map>
                   8055: ENDINITMAP
                   8056:         $topurl=&declutter(
1.638     albertel 8057:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8058:                           );
                   8059:     }
                   8060: # ----------------------------------------------------------- Write preferences
1.84      www      8061:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8062:                      ('description'              => $description,
                   8063:                       'url'                      => $topurl,
                   8064:                       'internal.creator'         => $env{'user.name'}.':'.
                   8065:                                                     $env{'user.domain'},
                   8066:                       'internal.created'         => $now,
                   8067:                       'internal.creationcontext' => $context)
                   8068:                     );
1.84      www      8069:     return '/'.$udom.'/'.$uname;
                   8070: }
                   8071: 
1.1011    raeburn  8072: # ------------------------------------------------------------------- Create ID
                   8073: sub generate_coursenum {
1.1038    raeburn  8074:     my ($udom,$crstype) = @_;
1.1011    raeburn  8075:     my $domdesc = &domain($udom);
                   8076:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8077:     my $first;
                   8078:     if ($crstype eq 'Community') {
                   8079:         $first = '0';
                   8080:     } else {
                   8081:         $first = int(1+rand(9)); 
                   8082:     } 
                   8083:     my $uname=$first.
1.1011    raeburn  8084:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8085:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8086:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8087: # ----------------------------------------------- Make sure that does not exist
                   8088:     my $uhome=&homeserver($uname,$udom,'true');
                   8089:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8090:         if ($crstype eq 'Community') {
                   8091:             $first = '0';
                   8092:         } else {
                   8093:             $first = int(1+rand(9));
                   8094:         }
                   8095:         $uname=$first.
1.1011    raeburn  8096:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8097:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8098:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8099:         $uhome=&homeserver($uname,$udom,'true');
                   8100:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8101:             return 'error: unable to generate unique course-ID';
                   8102:         }
                   8103:     }
                   8104:     return $uname;
                   8105: }
                   8106: 
1.813     albertel 8107: sub is_course {
1.1167    droeschl 8108:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8109:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8110: 
                   8111:     return unless $cdom and $cnum;
                   8112: 
                   8113:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8114:         '.');
                   8115: 
                   8116:     return unless exists($courses{$cdom.'_'.$cnum});
                   8117:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8118: }
                   8119: 
1.1015    raeburn  8120: sub store_userdata {
                   8121:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8122:     my $result;
1.1016    raeburn  8123:     if ($datakey ne '') {
1.1013    raeburn  8124:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8125:             if ($udom eq '' || $uname eq '') {
                   8126:                 $udom = $env{'user.domain'};
                   8127:                 $uname = $env{'user.name'};
                   8128:             }
                   8129:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8130:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8131:                 $result = 'error: no_host';
                   8132:             } else {
                   8133:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8134:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8135: 
                   8136:                 my $namevalue='';
                   8137:                 foreach my $key (keys(%{$storehash})) {
                   8138:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8139:                 }
                   8140:                 $namevalue=~s/\&$//;
1.1105    raeburn  8141:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8142:                                   $namevalue,$uhome);
1.1013    raeburn  8143:             }
                   8144:         } else {
                   8145:             $result = 'error: data to store was not a hash reference'; 
                   8146:         }
                   8147:     } else {
                   8148:         $result= 'error: invalid requestkey'; 
                   8149:     }
                   8150:     return $result;
                   8151: }
                   8152: 
1.21      www      8153: # ---------------------------------------------------------- Assign Custom Role
                   8154: 
                   8155: sub assigncustomrole {
1.957     raeburn  8156:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8157:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8158:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8159: }
                   8160: 
                   8161: # ----------------------------------------------------------------- Revoke Role
                   8162: 
                   8163: sub revokerole {
1.957     raeburn  8164:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8165:     my $now=time;
1.965     raeburn  8166:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8167: }
                   8168: 
                   8169: # ---------------------------------------------------------- Revoke Custom Role
                   8170: 
                   8171: sub revokecustomrole {
1.957     raeburn  8172:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8173:     my $now=time;
1.357     www      8174:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8175:            $deleteflag,$selfenroll,$context);
1.17      www      8176: }
                   8177: 
1.533     banghart 8178: # ------------------------------------------------------------ Disk usage
1.535     albertel 8179: sub diskusage {
1.955     raeburn  8180:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8181:     $directorypath =~ s/\/$//;
                   8182:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8183:                        .&escape($getpropath).':'.&escape($uname).':'
                   8184:                        .&escape($udom),homeserver($uname,$udom));
                   8185:     if ($listing eq 'unknown_cmd') {
                   8186:         if ($getpropath) {
                   8187:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8188:         }
                   8189:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8190:     }
1.514     albertel 8191:     return $listing;
1.512     banghart 8192: }
                   8193: 
1.566     banghart 8194: sub is_locked {
1.1096    raeburn  8195:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8196:     my @check;
                   8197:     my $is_locked;
1.1093    raeburn  8198:     push (@check,$file_name);
1.613     albertel 8199:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8200: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8201:     my ($tmp)=keys(%locked);
                   8202:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8203:     
1.566     banghart 8204:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8205:         $is_locked = 'false';
                   8206:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8207:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8208:                $is_locked = 'true';
1.1096    raeburn  8209:                if (ref($which) eq 'ARRAY') {
                   8210:                    push(@{$which},$entry);
                   8211:                } else {
                   8212:                    last;
                   8213:                }
1.745     raeburn  8214:            }
                   8215:        }
1.566     banghart 8216:     } else {
                   8217:         $is_locked = 'false';
                   8218:     }
1.1093    raeburn  8219:     return $is_locked;
1.566     banghart 8220: }
                   8221: 
1.759     albertel 8222: sub declutter_portfile {
                   8223:     my ($file) = @_;
1.833     albertel 8224:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8225:     return $file;
                   8226: }
                   8227: 
1.559     banghart 8228: # ------------------------------------------------------------- Mark as Read Only
                   8229: 
                   8230: sub mark_as_readonly {
                   8231:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8232:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8233:     my ($tmp)=keys(%current_permissions);
                   8234:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8235:     foreach my $file (@{$files}) {
1.759     albertel 8236: 	$file = &declutter_portfile($file);
1.561     banghart 8237:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8238:     }
1.613     albertel 8239:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8240:     return;
                   8241: }
                   8242: 
1.572     banghart 8243: # ------------------------------------------------------------Save Selected Files
                   8244: 
                   8245: sub save_selected_files {
                   8246:     my ($user, $path, @files) = @_;
                   8247:     my $filename = $user."savedfiles";
1.573     banghart 8248:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8249:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8250:     foreach my $file (@files) {
1.620     albertel 8251:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8252:     }
                   8253:     foreach my $file (@other_files) {
1.574     banghart 8254:         print (OUT $file."\n");
1.572     banghart 8255:     }
1.574     banghart 8256:     close (OUT);
1.572     banghart 8257:     return 'ok';
                   8258: }
                   8259: 
1.574     banghart 8260: sub clear_selected_files {
                   8261:     my ($user) = @_;
                   8262:     my $filename = $user."savedfiles";
1.1117    foxr     8263:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8264:     print (OUT undef);
                   8265:     close (OUT);
                   8266:     return ("ok");    
                   8267: }
                   8268: 
1.572     banghart 8269: sub files_in_path {
                   8270:     my ($user, $path) = @_;
                   8271:     my $filename = $user."savedfiles";
                   8272:     my %return_files;
1.1117    foxr     8273:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8274:     while (my $line_in = <IN>) {
1.574     banghart 8275:         chomp ($line_in);
                   8276:         my @paths_and_file = split (m!/!, $line_in);
                   8277:         my $file_part = pop (@paths_and_file);
                   8278:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8279:         $path_part.='/';
                   8280:         my $path_and_file = $path_part.$file_part;
                   8281:         if ($path_part eq $path) {
                   8282:             $return_files{$file_part}= 'selected';
                   8283:         }
                   8284:     }
1.574     banghart 8285:     close (IN);
                   8286:     return (\%return_files);
1.572     banghart 8287: }
                   8288: 
                   8289: # called in portfolio select mode, to show files selected NOT in current directory
                   8290: sub files_not_in_path {
                   8291:     my ($user, $path) = @_;
                   8292:     my $filename = $user."savedfiles";
                   8293:     my @return_files;
                   8294:     my $path_part;
1.1117    foxr     8295:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8296:     while (my $line = <IN>) {
1.572     banghart 8297:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8298:         my @paths_and_file = split(m|/|, $line);
                   8299:         my $file_part = pop(@paths_and_file);
                   8300:         chomp($file_part);
                   8301:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8302:         $path_part .= '/';
                   8303:         my $path_and_file = $path_part.$file_part;
                   8304:         if ($path_part ne $path) {
1.800     albertel 8305:             push(@return_files, ($path_and_file));
1.572     banghart 8306:         }
                   8307:     }
1.800     albertel 8308:     close(OUT);
1.574     banghart 8309:     return (@return_files);
1.572     banghart 8310: }
                   8311: 
1.745     raeburn  8312: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8313: 
1.745     raeburn  8314: sub get_portfile_permissions {
                   8315:     my ($domain,$user) = @_;
1.613     albertel 8316:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8317:     my ($tmp)=keys(%current_permissions);
                   8318:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8319:     return \%current_permissions;
                   8320: }
                   8321: 
                   8322: #---------------------------------------------Get portfolio file access controls
                   8323: 
1.749     raeburn  8324: sub get_access_controls {
1.745     raeburn  8325:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8326:     my %access;
                   8327:     my $real_file = $file;
                   8328:     $file =~ s/\.meta$//;
1.745     raeburn  8329:     if (defined($file)) {
1.749     raeburn  8330:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8331:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8332:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8333:             }
                   8334:         }
1.745     raeburn  8335:     } else {
1.749     raeburn  8336:         foreach my $key (keys(%{$current_permissions})) {
                   8337:             if ($key =~ /\0accesscontrol$/) {
                   8338:                 if (defined($group)) {
                   8339:                     if ($key !~ m-^\Q$group\E/-) {
                   8340:                         next;
                   8341:                     }
                   8342:                 }
                   8343:                 my ($fullpath) = split(/\0/,$key);
                   8344:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8345:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8346:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8347:                     }
                   8348:                 }
                   8349:             }
                   8350:         }
                   8351:     }
                   8352:     return %access;
                   8353: }
                   8354: 
                   8355: sub modify_access_controls {
                   8356:     my ($file_name,$changes,$domain,$user)=@_;
                   8357:     my ($outcome,$deloutcome);
                   8358:     my %store_permissions;
                   8359:     my %new_values;
                   8360:     my %new_control;
                   8361:     my %translation;
                   8362:     my @deletions = ();
                   8363:     my $now = time;
                   8364:     if (exists($$changes{'activate'})) {
                   8365:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8366:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8367:             my $numnew = scalar(@newitems);
                   8368:             for (my $i=0; $i<$numnew; $i++) {
                   8369:                 my $newkey = $newitems[$i];
                   8370:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8371:                 if ($newkey =~ /^\d+:/) { 
                   8372:                     $newkey =~ s/^(\d+)/$newid/;
                   8373:                     $translation{$1} = $newid;
                   8374:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8375:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8376:                     $translation{$1} = $newid;
                   8377:                 }
1.749     raeburn  8378:                 $new_values{$file_name."\0".$newkey} = 
                   8379:                                           $$changes{'activate'}{$newitems[$i]};
                   8380:                 $new_control{$newkey} = $now;
                   8381:             }
                   8382:         }
                   8383:     }
                   8384:     my %todelete;
                   8385:     my %changed_items;
                   8386:     foreach my $action ('delete','update') {
                   8387:         if (exists($$changes{$action})) {
                   8388:             if (ref($$changes{$action}) eq 'HASH') {
                   8389:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8390:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8391:                     if ($action eq 'delete') { 
                   8392:                         $todelete{$itemnum} = 1;
                   8393:                     } else {
                   8394:                         $changed_items{$itemnum} = $key;
                   8395:                     }
                   8396:                 }
1.745     raeburn  8397:             }
                   8398:         }
1.749     raeburn  8399:     }
                   8400:     # get lock on access controls for file.
                   8401:     my $lockhash = {
                   8402:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8403:                                                        ':'.$env{'user.domain'},
                   8404:                    }; 
                   8405:     my $tries = 0;
                   8406:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8407:    
                   8408:     while (($gotlock ne 'ok') && $tries <3) {
                   8409:         $tries ++;
                   8410:         sleep 1;
                   8411:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8412:     }
                   8413:     if ($gotlock eq 'ok') {
                   8414:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8415:         my ($tmp)=keys(%curr_permissions);
                   8416:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8417:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8418:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8419:             if (ref($curr_controls) eq 'HASH') {
                   8420:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8421:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8422:                     if (defined($todelete{$itemnum})) {
                   8423:                         push(@deletions,$file_name."\0".$control_item);
                   8424:                     } else {
                   8425:                         if (defined($changed_items{$itemnum})) {
                   8426:                             $new_control{$changed_items{$itemnum}} = $now;
                   8427:                             push(@deletions,$file_name."\0".$control_item);
                   8428:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8429:                         } else {
                   8430:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8431:                         }
                   8432:                     }
1.745     raeburn  8433:                 }
                   8434:             }
                   8435:         }
1.970     raeburn  8436:         my ($group);
                   8437:         if (&is_course($domain,$user)) {
                   8438:             ($group,my $file) = split(/\//,$file_name,2);
                   8439:         }
1.749     raeburn  8440:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8441:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8442:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8443:         #  remove lock
                   8444:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8445:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8446:         my $sqlresult =
1.970     raeburn  8447:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8448:                                     $group);
1.749     raeburn  8449:     } else {
                   8450:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8451:     }
1.749     raeburn  8452:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8453: }
                   8454: 
1.827     raeburn  8455: sub make_public_indefinitely {
                   8456:     my ($requrl) = @_;
                   8457:     my $now = time;
                   8458:     my $action = 'activate';
                   8459:     my $aclnum = 0;
                   8460:     if (&is_portfolio_url($requrl)) {
                   8461:         my (undef,$udom,$unum,$file_name,$group) =
                   8462:             &parse_portfolio_url($requrl);
                   8463:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8464:         my %access_controls = &get_access_controls($current_perms,
                   8465:                                                    $group,$file_name);
                   8466:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8467:             my ($num,$scope,$end,$start) = 
                   8468:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8469:             if ($scope eq 'public') {
                   8470:                 if ($start <= $now && $end == 0) {
                   8471:                     $action = 'none';
                   8472:                 } else {
                   8473:                     $action = 'update';
                   8474:                     $aclnum = $num;
                   8475:                 }
                   8476:                 last;
                   8477:             }
                   8478:         }
                   8479:         if ($action eq 'none') {
                   8480:              return 'ok';
                   8481:         } else {
                   8482:             my %changes;
                   8483:             my $newend = 0;
                   8484:             my $newstart = $now;
                   8485:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8486:             $changes{$action}{$newkey} = {
                   8487:                 type => 'public',
                   8488:                 time => {
                   8489:                     start => $newstart,
                   8490:                     end   => $newend,
                   8491:                 },
                   8492:             };
                   8493:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8494:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8495:             return $outcome;
                   8496:         }
                   8497:     } else {
                   8498:         return 'invalid';
                   8499:     }
                   8500: }
                   8501: 
1.745     raeburn  8502: #------------------------------------------------------Get Marked as Read Only
                   8503: 
                   8504: sub get_marked_as_readonly {
                   8505:     my ($domain,$user,$what,$group) = @_;
                   8506:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8507:     my @readonly_files;
1.629     banghart 8508:     my $cmp1=$what;
                   8509:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8510:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8511:         if (defined($group)) {
                   8512:             if ($file_name !~ m-^\Q$group\E/-) {
                   8513:                 next;
                   8514:             }
                   8515:         }
1.561     banghart 8516:         if (ref($value) eq "ARRAY"){
                   8517:             foreach my $stored_what (@{$value}) {
1.629     banghart 8518:                 my $cmp2=$stored_what;
1.759     albertel 8519:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8520:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8521:                 }
1.629     banghart 8522:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8523:                     push(@readonly_files, $file_name);
1.745     raeburn  8524:                     last;
1.563     banghart 8525:                 } elsif (!defined($what)) {
                   8526:                     push(@readonly_files, $file_name);
1.745     raeburn  8527:                     last;
1.561     banghart 8528:                 }
                   8529:             }
1.745     raeburn  8530:         }
1.561     banghart 8531:     }
                   8532:     return @readonly_files;
                   8533: }
1.577     banghart 8534: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8535: 
1.577     banghart 8536: sub get_marked_as_readonly_hash {
1.745     raeburn  8537:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8538:     my %readonly_files;
1.745     raeburn  8539:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8540:         if (defined($group)) {
                   8541:             if ($file_name !~ m-^\Q$group\E/-) {
                   8542:                 next;
                   8543:             }
                   8544:         }
1.577     banghart 8545:         if (ref($value) eq "ARRAY"){
                   8546:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8547:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8548:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8549:                         if ($lock_descriptor eq 'graded') {
                   8550:                             $readonly_files{$file_name} = 'graded';
                   8551:                         } elsif ($lock_descriptor eq 'handback') {
                   8552:                             $readonly_files{$file_name} = 'handback';
                   8553:                         } else {
                   8554:                             if (!exists($readonly_files{$file_name})) {
                   8555:                                 $readonly_files{$file_name} = 'locked';
                   8556:                             }
                   8557:                         }
1.745     raeburn  8558:                     }
1.750     banghart 8559:                 } 
1.577     banghart 8560:             }
                   8561:         } 
                   8562:     }
                   8563:     return %readonly_files;
                   8564: }
1.559     banghart 8565: # ------------------------------------------------------------ Unmark as Read Only
                   8566: 
                   8567: sub unmark_as_readonly {
1.629     banghart 8568:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8569:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8570:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8571:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8572:     my $symb_crs = $what;
                   8573:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8574:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8575:     my ($tmp)=keys(%current_permissions);
                   8576:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8577:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8578:     foreach my $file (@readonly_files) {
1.759     albertel 8579: 	my $clean_file = &declutter_portfile($file);
                   8580: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8581: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8582:         my @new_locks;
                   8583:         my @del_keys;
                   8584:         if (ref($current_locks) eq "ARRAY"){
                   8585:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8586:                 my $compare=$locker;
1.749     raeburn  8587:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8588:                     $compare=join('',@{$locker});
1.746     raeburn  8589:                     if ($compare ne $symb_crs) {
                   8590:                         push(@new_locks, $locker);
                   8591:                     }
1.563     banghart 8592:                 }
                   8593:             }
1.650     albertel 8594:             if (scalar(@new_locks) > 0) {
1.563     banghart 8595:                 $current_permissions{$file} = \@new_locks;
                   8596:             } else {
                   8597:                 push(@del_keys, $file);
1.613     albertel 8598:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8599:                 delete($current_permissions{$file});
1.563     banghart 8600:             }
                   8601:         }
1.561     banghart 8602:     }
1.613     albertel 8603:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8604:     return;
                   8605: }
1.512     banghart 8606: 
1.17      www      8607: # ------------------------------------------------------------ Directory lister
                   8608: 
                   8609: sub dirlist {
1.955     raeburn  8610:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8611:     $uri=~s/^\///;
                   8612:     $uri=~s/\/$//;
1.253     stredwic 8613:     my ($udom, $uname);
1.955     raeburn  8614:     if ($getuserdir) {
1.253     stredwic 8615:         $udom = $userdomain;
                   8616:         $uname = $username;
1.955     raeburn  8617:     } else {
                   8618:         (undef,$udom,$uname)=split(/\//,$uri);
                   8619:         if(defined($userdomain)) {
                   8620:             $udom = $userdomain;
                   8621:         }
                   8622:         if(defined($username)) {
                   8623:             $uname = $username;
                   8624:         }
1.253     stredwic 8625:     }
1.955     raeburn  8626:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8627: 
1.955     raeburn  8628:     $dirRoot = $perlvar{'lonDocRoot'};
                   8629:     if (defined($getpropath)) {
                   8630:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8631:         $dirRoot =~ s/\/$//;
1.955     raeburn  8632:     } elsif (defined($getuserdir)) {
                   8633:         my $subdir=$uname.'__';
                   8634:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8635:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8636:                    ."/$udom/$subdir/$uname";
                   8637:     } elsif (defined($alternateRoot)) {
                   8638:         $dirRoot = $alternateRoot;
1.751     banghart 8639:     }
1.253     stredwic 8640: 
                   8641:     if($udom) {
                   8642:         if($uname) {
1.1135    raeburn  8643:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8644:             if ($uhome eq 'no_host') {
                   8645:                 return ([],'no_host');
                   8646:             }
1.955     raeburn  8647:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8648:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8649:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8650:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8651:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8652:             } else {
                   8653:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8654:             }
1.605     matthew  8655:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8656:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8657:                 @listing_results = split(/:/,$listing);
                   8658:             } else {
                   8659:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8660:             }
1.1135    raeburn  8661:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8662:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8663:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8664:                 return ([],$listing);
                   8665:             } else {
                   8666:                 return (\@listing_results);
1.1135    raeburn  8667:             }
1.955     raeburn  8668:         } elsif(!$alternateRoot) {
1.1136    raeburn  8669:             my (%allusers,%listerror);
1.841     albertel 8670: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8671:  	    foreach my $tryserver (keys(%servers)) {
                   8672:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8673:                                   &escape($udom),$tryserver);
                   8674:                 if ($listing eq 'unknown_cmd') {
                   8675: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8676: 				      $udom, $tryserver);
                   8677:                 } else {
                   8678:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8679:                 }
1.841     albertel 8680: 		if ($listing eq 'unknown_cmd') {
                   8681: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8682: 				      $udom, $tryserver);
                   8683: 		    @listing_results = split(/:/,$listing);
                   8684: 		} else {
                   8685: 		    @listing_results =
                   8686: 			map { &unescape($_); } split(/:/,$listing);
                   8687: 		}
1.1136    raeburn  8688:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8689:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8690:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8691:                     $listerror{$tryserver} = $listing;
                   8692:                 } else {
1.841     albertel 8693: 		    foreach my $line (@listing_results) {
                   8694: 			my ($entry) = split(/&/,$line,2);
                   8695: 			$allusers{$entry} = 1;
                   8696: 		    }
                   8697: 		}
1.253     stredwic 8698:             }
1.1136    raeburn  8699:             my @alluserslist=();
1.800     albertel 8700:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8701:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8702:             }
1.1136    raeburn  8703:             return (\@alluserslist);
1.253     stredwic 8704:         } else {
1.1136    raeburn  8705:             return ([],'missing username');
1.253     stredwic 8706:         }
1.955     raeburn  8707:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8708:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8709:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8710:         return (\@all_domains);
1.955     raeburn  8711:     } else {
1.1136    raeburn  8712:         return ([],'missing domain');
1.275     stredwic 8713:     }
                   8714: }
                   8715: 
                   8716: # --------------------------------------------- GetFileTimestamp
                   8717: # This function utilizes dirlist and returns the date stamp for
                   8718: # when it was last modified.  It will also return an error of -1
                   8719: # if an error occurs
                   8720: 
                   8721: sub GetFileTimestamp {
1.955     raeburn  8722:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8723:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8724:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8725:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8726:                                     undef,$getuserdir);
                   8727:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8728:         return -1;
                   8729:     }
                   8730:     if (ref($fileref) eq 'ARRAY') {
                   8731:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8732:         # @stats contains first the filename, then the stat output
                   8733:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8734:     } else {
                   8735:         return -1;
1.253     stredwic 8736:     }
1.26      www      8737: }
                   8738: 
1.712     albertel 8739: sub stat_file {
                   8740:     my ($uri) = @_;
1.787     albertel 8741:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8742: 
1.955     raeburn  8743:     my ($udom,$uname,$file);
1.712     albertel 8744:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8745: 	($udom,$uname,$file) =
1.811     albertel 8746: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8747: 	$file = 'userfiles/'.$file;
                   8748:     }
                   8749:     if ($uri =~ m-^/res/-) {
                   8750: 	($udom,$uname) = 
1.807     albertel 8751: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8752: 	$file = $uri;
                   8753:     }
                   8754: 
                   8755:     if (!$udom || !$uname || !$file) {
                   8756: 	# unable to handle the uri
                   8757: 	return ();
                   8758:     }
1.956     raeburn  8759:     my $getpropath;
                   8760:     if ($file =~ /^userfiles\//) {
                   8761:         $getpropath = 1;
                   8762:     }
1.1136    raeburn  8763:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8764:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8765:         return ();
                   8766:     } else {
                   8767:         if (ref($listref) eq 'ARRAY') {
                   8768:             my @stats = split('&',$listref->[0]);
                   8769: 	    shift(@stats); #filename is first
                   8770: 	    return @stats;
                   8771:         }
1.712     albertel 8772:     }
                   8773:     return ();
                   8774: }
                   8775: 
1.26      www      8776: # -------------------------------------------------------- Value of a Condition
                   8777: 
1.713     albertel 8778: # gets the value of a specific preevaluated condition
                   8779: #    stored in the string  $env{user.state.<cid>}
                   8780: # or looks up a condition reference in the bighash and if if hasn't
                   8781: # already been evaluated recurses into docondval to get the value of
                   8782: # the condition, then memoizing it to 
                   8783: #   $env{user.state.<cid>.<condition>}
1.40      www      8784: sub directcondval {
                   8785:     my $number=shift;
1.620     albertel 8786:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8787: 	&Apache::lonuserstate::evalstate();
                   8788:     }
1.713     albertel 8789:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8790: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8791:     } elsif ($number =~ /^_/) {
                   8792: 	my $sub_condition;
                   8793: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8794: 		&GDBM_READER(),0640)) {
                   8795: 	    $sub_condition=$bighash{'conditions'.$number};
                   8796: 	    untie(%bighash);
                   8797: 	}
                   8798: 	my $value = &docondval($sub_condition);
1.949     raeburn  8799: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8800: 	return $value;
                   8801:     }
1.620     albertel 8802:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8803:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8804:     } else {
                   8805:        return 2;
                   8806:     }
                   8807: }
                   8808: 
1.713     albertel 8809: # get the collection of conditions for this resource
1.26      www      8810: sub condval {
                   8811:     my $condidx=shift;
1.54      www      8812:     my $allpathcond='';
1.713     albertel 8813:     foreach my $cond (split(/\|/,$condidx)) {
                   8814: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8815: 	    $allpathcond.=
                   8816: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8817: 	}
1.191     harris41 8818:     }
1.54      www      8819:     $allpathcond=~s/\|$//;
1.713     albertel 8820:     return &docondval($allpathcond);
                   8821: }
                   8822: 
                   8823: #evaluates an expression of conditions
                   8824: sub docondval {
                   8825:     my ($allpathcond) = @_;
                   8826:     my $result=0;
                   8827:     if ($env{'request.course.id'}
                   8828: 	&& defined($allpathcond)) {
                   8829: 	my $operand='|';
                   8830: 	my @stack;
                   8831: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8832: 	    if ($chunk eq '(') {
                   8833: 		push @stack,($operand,$result);
                   8834: 	    } elsif ($chunk eq ')') {
                   8835: 		my $before=pop @stack;
                   8836: 		if (pop @stack eq '&') {
                   8837: 		    $result=$result>$before?$before:$result;
                   8838: 		} else {
                   8839: 		    $result=$result>$before?$result:$before;
                   8840: 		}
                   8841: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8842: 		$operand=$chunk;
                   8843: 	    } else {
                   8844: 		my $new=directcondval($chunk);
                   8845: 		if ($operand eq '&') {
                   8846: 		    $result=$result>$new?$new:$result;
                   8847: 		} else {
                   8848: 		    $result=$result>$new?$result:$new;
                   8849: 		}
                   8850: 	    }
                   8851: 	}
1.26      www      8852:     }
                   8853:     return $result;
1.421     albertel 8854: }
                   8855: 
                   8856: # ---------------------------------------------------- Devalidate courseresdata
                   8857: 
                   8858: sub devalidatecourseresdata {
                   8859:     my ($coursenum,$coursedomain)=@_;
                   8860:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8861:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8862: }
                   8863: 
1.763     www      8864: 
1.200     www      8865: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8866: #
                   8867: #  Parameters:
                   8868: #      $coursenum    - Number of the course.
                   8869: #      $coursedomain - Domain at which the course was created.
                   8870: #  Returns:
                   8871: #     A hash of the course parameters along (I think) with timestamps
                   8872: #     and version info.
1.877     foxr     8873: 
1.624     albertel 8874: sub get_courseresdata {
                   8875:     my ($coursenum,$coursedomain)=@_;
1.200     www      8876:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8877:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8878:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8879:     my %dumpreply;
1.417     albertel 8880:     unless (defined($cached)) {
1.624     albertel 8881: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8882: 	$result=\%dumpreply;
1.251     albertel 8883: 	my ($tmp) = keys(%dumpreply);
                   8884: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8885: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8886: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8887: 	    return $tmp;
1.416     albertel 8888: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8889: 	    $result=undef;
1.599     albertel 8890: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8891: 	}
                   8892:     }
1.624     albertel 8893:     return $result;
                   8894: }
                   8895: 
1.633     albertel 8896: sub devalidateuserresdata {
                   8897:     my ($uname,$udom)=@_;
                   8898:     my $hashid="$udom:$uname";
                   8899:     &devalidate_cache_new('userres',$hashid);
                   8900: }
                   8901: 
1.624     albertel 8902: sub get_userresdata {
                   8903:     my ($uname,$udom)=@_;
                   8904:     #most student don\'t have any data set, check if there is some data
                   8905:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8906: 
                   8907:     my $hashid="$udom:$uname";
                   8908:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8909:     if (!defined($cached)) {
                   8910: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8911: 	$result=\%resourcedata;
                   8912: 	&do_cache_new('userres',$hashid,$result,600);
                   8913:     }
                   8914:     my ($tmp)=keys(%$result);
                   8915:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8916: 	return $result;
                   8917:     }
                   8918:     #error 2 occurs when the .db doesn't exist
                   8919:     if ($tmp!~/error: 2 /) {
1.672     albertel 8920: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8921: 		 " Trying to get resource data for ".
                   8922: 		 $uname." at ".$udom.": ".
                   8923: 		 $tmp."</font>");
                   8924:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8925: 	#&EXT_cache_set($udom,$uname);
                   8926: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8927: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8928:     }
                   8929:     return $tmp;
                   8930: }
1.879     foxr     8931: #----------------------------------------------- resdata - return resource data
                   8932: #  Purpose:
                   8933: #    Return resource data for either users or for a course.
                   8934: #  Parameters:
                   8935: #     $name      - Course/user name.
                   8936: #     $domain    - Name of the domain the user/course is registered on.
                   8937: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8938: #     @which     - Array of names of resources desired.
                   8939: #  Returns:
                   8940: #     The value of the first reasource in @which that is found in the
                   8941: #     resource hash.
                   8942: #  Exceptional Conditions:
                   8943: #     If the $type passed in is not valid (not the string 'course' or 
                   8944: #     'user', an undefined  reference is returned.
                   8945: #     If none of the resources are found, an undef is returned
1.624     albertel 8946: sub resdata {
                   8947:     my ($name,$domain,$type,@which)=@_;
                   8948:     my $result;
                   8949:     if ($type eq 'course') {
                   8950: 	$result=&get_courseresdata($name,$domain);
                   8951:     } elsif ($type eq 'user') {
                   8952: 	$result=&get_userresdata($name,$domain);
                   8953:     }
                   8954:     if (!ref($result)) { return $result; }    
1.251     albertel 8955:     foreach my $item (@which) {
1.927     albertel 8956: 	if (defined($result->{$item->[0]})) {
                   8957: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8958: 	}
1.250     albertel 8959:     }
1.291     albertel 8960:     return undef;
1.200     www      8961: }
                   8962: 
1.379     matthew  8963: #
                   8964: # EXT resource caching routines
                   8965: #
                   8966: 
                   8967: sub clear_EXT_cache_status {
1.383     albertel 8968:     &delenv('cache.EXT.');
1.379     matthew  8969: }
                   8970: 
                   8971: sub EXT_cache_status {
                   8972:     my ($target_domain,$target_user) = @_;
1.383     albertel 8973:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8974:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8975:         # We know already the user has no data
                   8976:         return 1;
                   8977:     } else {
                   8978:         return 0;
                   8979:     }
                   8980: }
                   8981: 
                   8982: sub EXT_cache_set {
                   8983:     my ($target_domain,$target_user) = @_;
1.383     albertel 8984:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8985:     #&appenv({$cachename => time});
1.379     matthew  8986: }
                   8987: 
1.28      www      8988: # --------------------------------------------------------- Value of a Variable
1.58      www      8989: sub EXT {
1.715     albertel 8990: 
1.395     albertel 8991:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8992:     unless ($varname) { return ''; }
1.218     albertel 8993:     #get real user name/domain, courseid and symb
                   8994:     my $courseid;
1.359     albertel 8995:     my $publicuser;
1.427     www      8996:     if ($symbparm) {
                   8997: 	$symbparm=&get_symb_from_alias($symbparm);
                   8998:     }
1.218     albertel 8999:     if (!($uname && $udom)) {
1.790     albertel 9000:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9001:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9002:     } else {
1.620     albertel 9003: 	$courseid=$env{'request.course.id'};
1.218     albertel 9004:     }
1.48      www      9005:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9006:     my $rest;
1.320     albertel 9007:     if (defined($therest[0])) {
1.48      www      9008:        $rest=join('.',@therest);
                   9009:     } else {
                   9010:        $rest='';
                   9011:     }
1.320     albertel 9012: 
1.57      www      9013:     my $qualifierrest=$qualifier;
                   9014:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9015:     my $spacequalifierrest=$space;
                   9016:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9017:     if ($realm eq 'user') {
1.48      www      9018: # --------------------------------------------------------------- user.resource
                   9019: 	if ($space eq 'resource') {
1.651     albertel 9020: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9021: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9022: 		 &&
1.744     albertel 9023: 		 ($symbparm eq &symbread()) ) {	
                   9024: 		# if we are in the middle of processing the resource the
                   9025: 		# get the value we are planning on committing
                   9026:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9027:                     return $Apache::lonhomework::results{$qualifierrest};
                   9028:                 } else {
                   9029:                     return $Apache::lonhomework::history{$qualifierrest};
                   9030:                 }
1.335     albertel 9031: 	    } else {
1.359     albertel 9032: 		my %restored;
1.620     albertel 9033: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9034: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9035: 		} else {
                   9036: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9037: 		}
1.335     albertel 9038: 		return $restored{$qualifierrest};
                   9039: 	    }
1.48      www      9040: # ----------------------------------------------------------------- user.access
                   9041:         } elsif ($space eq 'access') {
1.218     albertel 9042: 	    # FIXME - not supporting calls for a specific user
1.48      www      9043:             return &allowed($qualifier,$rest);
                   9044: # ------------------------------------------ user.preferences, user.environment
                   9045:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9046: 	    if (($uname eq $env{'user.name'}) &&
                   9047: 		($udom eq $env{'user.domain'})) {
                   9048: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9049: 	    } else {
1.359     albertel 9050: 		my %returnhash;
                   9051: 		if (!$publicuser) {
                   9052: 		    %returnhash=&userenvironment($udom,$uname,
                   9053: 						 $qualifierrest);
                   9054: 		}
1.218     albertel 9055: 		return $returnhash{$qualifierrest};
                   9056: 	    }
1.48      www      9057: # ----------------------------------------------------------------- user.course
                   9058:         } elsif ($space eq 'course') {
1.218     albertel 9059: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9060:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9061: # ------------------------------------------------------------------- user.role
                   9062:         } elsif ($space eq 'role') {
1.218     albertel 9063: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9064:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9065:             if ($qualifier eq 'value') {
                   9066: 		return $role;
                   9067:             } elsif ($qualifier eq 'extent') {
                   9068:                 return $where;
                   9069:             }
                   9070: # ----------------------------------------------------------------- user.domain
                   9071:         } elsif ($space eq 'domain') {
1.218     albertel 9072:             return $udom;
1.48      www      9073: # ------------------------------------------------------------------- user.name
                   9074:         } elsif ($space eq 'name') {
1.218     albertel 9075:             return $uname;
1.48      www      9076: # ---------------------------------------------------- Any other user namespace
1.29      www      9077:         } else {
1.359     albertel 9078: 	    my %reply;
                   9079: 	    if (!$publicuser) {
                   9080: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9081: 	    }
                   9082: 	    return $reply{$qualifierrest};
1.48      www      9083:         }
1.236     www      9084:     } elsif ($realm eq 'query') {
                   9085: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9086:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9087: 						[$spacequalifierrest]);
1.620     albertel 9088: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9089:    } elsif ($realm eq 'request') {
1.48      www      9090: # ------------------------------------------------------------- request.browser
                   9091:         if ($space eq 'browser') {
1.1145    bisitz   9092:             return $env{'browser.'.$qualifier};
1.57      www      9093: # ------------------------------------------------------------ request.filename
                   9094:         } else {
1.620     albertel 9095:             return $env{'request.'.$spacequalifierrest};
1.29      www      9096:         }
1.28      www      9097:     } elsif ($realm eq 'course') {
1.48      www      9098: # ---------------------------------------------------------- course.description
1.620     albertel 9099:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9100:     } elsif ($realm eq 'resource') {
1.165     www      9101: 
1.620     albertel 9102: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9103: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9104: 	}
1.693     albertel 9105: 
                   9106: 	if ($space eq 'title') {
                   9107: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9108: 	    return &gettitle($symbparm);
                   9109: 	}
                   9110: 	
                   9111: 	if ($space eq 'map') {
                   9112: 	    my ($map) = &decode_symb($symbparm);
                   9113: 	    return &symbread($map);
                   9114: 	}
1.905     albertel 9115: 	if ($space eq 'filename') {
                   9116: 	    if ($symbparm) {
                   9117: 		return &clutter((&decode_symb($symbparm))[2]);
                   9118: 	    }
                   9119: 	    return &hreflocation('',$env{'request.filename'});
                   9120: 	}
1.693     albertel 9121: 
                   9122: 	my ($section, $group, @groups);
1.593     albertel 9123: 	my ($courselevelm,$courselevel);
1.539     albertel 9124: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9125: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9126: 
1.218     albertel 9127: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9128: 
1.60      www      9129: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9130: 	    my $symbp=$symbparm;
1.735     albertel 9131: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9132: 
                   9133: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9134: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9135: 
1.620     albertel 9136: 	    if (($env{'user.name'} eq $uname) &&
                   9137: 		($env{'user.domain'} eq $udom)) {
                   9138: 		$section=$env{'request.course.sec'};
1.733     raeburn  9139:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9140:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9141: 	    } else {
1.539     albertel 9142: 		if (! defined($usection)) {
1.551     albertel 9143: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9144: 		} else {
                   9145: 		    $section = $usection;
                   9146: 		}
1.733     raeburn  9147:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9148: 	    }
                   9149: 
                   9150: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9151: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9152: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9153: 
1.593     albertel 9154: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9155: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9156: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9157: 
1.60      www      9158: # ----------------------------------------------------------- first, check user
1.624     albertel 9159: 
                   9160: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9161: 				       ([$courselevelr,'resource'],
                   9162: 					[$courselevelm,'map'     ],
                   9163: 					[$courselevel, 'course'  ]));
1.931     albertel 9164: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9165: 
1.594     albertel 9166: # ------------------------------------------------ second, check some of course
1.684     raeburn  9167:             my $coursereply;
1.691     raeburn  9168:             if (@groups > 0) {
                   9169:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9170:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9171:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9172:             }
1.96      www      9173: 
1.684     raeburn  9174: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9175: 				  $env{'course.'.$courseid.'.domain'},
                   9176: 				  'course',
                   9177: 				  ([$seclevelr,   'resource'],
                   9178: 				   [$seclevelm,   'map'     ],
                   9179: 				   [$seclevel,    'course'  ],
                   9180: 				   [$courselevelr,'resource']));
                   9181: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9182: 
1.60      www      9183: # ------------------------------------------------------ third, check map parms
1.218     albertel 9184: 	    my %parmhash=();
                   9185: 	    my $thisparm='';
                   9186: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9187: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9188: 		    &GDBM_READER(),0640)) {
1.218     albertel 9189: 		$thisparm=$parmhash{$symbparm};
                   9190: 		untie(%parmhash);
                   9191: 	    }
1.927     albertel 9192: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9193: 	}
1.594     albertel 9194: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9195: 
1.218     albertel 9196: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9197: 	my $filename;
                   9198: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9199: 	if ($symbparm) {
1.409     www      9200: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9201: 	} else {
1.620     albertel 9202: 	    $filename=$env{'request.filename'};
1.282     albertel 9203: 	}
                   9204: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9205: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9206: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9207: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9208: 
1.927     albertel 9209: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9210: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9211: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9212: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9213: 				     $env{'course.'.$courseid.'.domain'},
                   9214: 				     'course',
1.927     albertel 9215: 				     ([$courselevelm,'map'   ],
                   9216: 				      [$courselevel, 'course']));
                   9217: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9218: 	}
1.145     www      9219: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9220: 	unless ($space eq '0') {
1.336     albertel 9221: 	    my @parts=split(/_/,$space);
                   9222: 	    my $id=pop(@parts);
                   9223: 	    my $part=join('_',@parts);
                   9224: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9225: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9226: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9227: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9228: 	}
1.395     albertel 9229: 	if ($recurse) { return undef; }
                   9230: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9231: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9232: # ---------------------------------------------------- Any other user namespace
                   9233:     } elsif ($realm eq 'environment') {
                   9234: # ----------------------------------------------------------------- environment
1.620     albertel 9235: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9236: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9237: 	} else {
1.770     albertel 9238: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9239: 		return '';
                   9240: 	    }
1.219     albertel 9241: 	    my %returnhash=&userenvironment($udom,$uname,
                   9242: 					    $spacequalifierrest);
                   9243: 	    return $returnhash{$spacequalifierrest};
                   9244: 	}
1.28      www      9245:     } elsif ($realm eq 'system') {
1.48      www      9246: # ----------------------------------------------------------------- system.time
                   9247: 	if ($space eq 'time') {
                   9248: 	    return time;
                   9249:         }
1.696     albertel 9250:     } elsif ($realm eq 'server') {
                   9251: # ----------------------------------------------------------------- system.time
                   9252: 	if ($space eq 'name') {
                   9253: 	    return $ENV{'SERVER_NAME'};
                   9254:         }
1.28      www      9255:     }
1.48      www      9256:     return '';
1.61      www      9257: }
                   9258: 
1.927     albertel 9259: sub get_reply {
                   9260:     my ($reply_value) = @_;
1.940     raeburn  9261:     if (ref($reply_value) eq 'ARRAY') {
                   9262:         if (wantarray) {
                   9263: 	    return @$reply_value;
                   9264:         }
                   9265:         return $reply_value->[0];
                   9266:     } else {
                   9267:         return $reply_value;
1.927     albertel 9268:     }
                   9269: }
                   9270: 
1.691     raeburn  9271: sub check_group_parms {
                   9272:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9273:     my @groupitems = ();
                   9274:     my $resultitem;
1.927     albertel 9275:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9276:     foreach my $group (@{$groups}) {
                   9277:         foreach my $level (@levels) {
1.927     albertel 9278:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9279:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9280:         }
                   9281:     }
                   9282:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9283:                             $env{'course.'.$courseid.'.domain'},
                   9284:                                      'course',@groupitems);
                   9285:     return $coursereply;
                   9286: }
                   9287: 
                   9288: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9289:     my ($courseid,@groups) = @_;
                   9290:     @groups = sort(@groups);
1.691     raeburn  9291:     return @groups;
                   9292: }
                   9293: 
1.395     albertel 9294: sub packages_tab_default {
                   9295:     my ($uri,$varname)=@_;
                   9296:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9297: 
                   9298:     my (@extension,@specifics,$do_default);
                   9299:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9300: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9301: 	if ($pack_type eq 'default') {
                   9302: 	    $do_default=1;
                   9303: 	} elsif ($pack_type eq 'extension') {
                   9304: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9305: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9306: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9307: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9308: 	}
                   9309:     }
                   9310:     # first look for a package that matches the requested part id
                   9311:     foreach my $package (@specifics) {
                   9312: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9313: 	next if ($pack_part ne $part);
                   9314: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9315: 	    return $packagetab{"$pack_type&$name&default"};
                   9316: 	}
                   9317:     }
                   9318:     # look for any possible matching non extension_ package
                   9319:     foreach my $package (@specifics) {
                   9320: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9321: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9322: 	    return $packagetab{"$pack_type&$name&default"};
                   9323: 	}
1.585     albertel 9324: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9325: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9326: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9327: 	}
                   9328:     }
1.738     albertel 9329:     # look for any posible extension_ match
                   9330:     foreach my $package (@extension) {
                   9331: 	my ($package,$pack_type)=@{$package};
                   9332: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9333: 	    return $packagetab{"$pack_type&$name&default"};
                   9334: 	}
                   9335: 	if (defined($packagetab{$package."&$name&default"})) {
                   9336: 	    return $packagetab{$package."&$name&default"};
                   9337: 	}
                   9338:     }
                   9339:     # look for a global default setting
                   9340:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9341: 	return $packagetab{"default&$name&default"};
                   9342:     }
1.395     albertel 9343:     return undef;
                   9344: }
                   9345: 
1.334     albertel 9346: sub add_prefix_and_part {
                   9347:     my ($prefix,$part)=@_;
                   9348:     my $keyroot;
                   9349:     if (defined($prefix) && $prefix !~ /^__/) {
                   9350: 	# prefix that has a part already
                   9351: 	$keyroot=$prefix;
                   9352:     } elsif (defined($prefix)) {
                   9353: 	# prefix that is missing a part
                   9354: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9355:     } else {
                   9356: 	# no prefix at all
                   9357: 	if (defined($part)) { $keyroot='_'.$part; }
                   9358:     }
                   9359:     return $keyroot;
                   9360: }
                   9361: 
1.71      www      9362: # ---------------------------------------------------------------- Get metadata
                   9363: 
1.599     albertel 9364: my %metaentry;
1.1070    www      9365: my %importedpartids;
1.71      www      9366: sub metadata {
1.176     www      9367:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9368:     $uri=&declutter($uri);
1.288     albertel 9369:     # if it is a non metadata possible uri return quickly
1.529     albertel 9370:     if (($uri eq '') || 
                   9371: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9372: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9373:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9374: 	return undef;
                   9375:     }
1.1140    www      9376:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9377: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9378: 	return undef;
1.288     albertel 9379:     }
1.73      www      9380:     my $filename=$uri;
                   9381:     $uri=~s/\.meta$//;
1.172     www      9382: #
                   9383: # Is the metadata already cached?
1.177     www      9384: # Look at timestamp of caching
1.172     www      9385: # Everything is cached by the main uri, libraries are never directly cached
                   9386: #
1.428     albertel 9387:     if (!defined($liburi)) {
1.599     albertel 9388: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9389: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9390:     }
                   9391:     {
1.1069    www      9392: # Imported parts would go here
1.1070    www      9393:         my %importedids=();
                   9394:         my @origfileimportpartids=();
1.1069    www      9395:         my $importedparts=0;
1.172     www      9396: #
                   9397: # Is this a recursive call for a library?
                   9398: #
1.599     albertel 9399: #	if (! exists($metacache{$uri})) {
                   9400: #	    $metacache{$uri}={};
                   9401: #	}
1.924     albertel 9402: 	my $cachetime = 60*60;
1.171     www      9403:         if ($liburi) {
                   9404: 	    $liburi=&declutter($liburi);
                   9405:             $filename=$liburi;
1.401     bowersj2 9406:         } else {
1.599     albertel 9407: 	    &devalidate_cache_new('meta',$uri);
                   9408: 	    undef(%metaentry);
1.401     bowersj2 9409: 	}
1.140     www      9410:         my %metathesekeys=();
1.73      www      9411:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9412: 	my $metastring;
1.1140    www      9413: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9414: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9415: 	    $metastring = 
1.929     albertel 9416: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9417: 					  ('grade_target' => 'meta'));
                   9418: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9419: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9420:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9421: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9422: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9423: 	    $metastring=&getfile($file);
1.489     albertel 9424: 	}
1.208     albertel 9425:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9426:         my $token;
1.140     www      9427:         undef %metathesekeys;
1.71      www      9428:         while ($token=$parser->get_token) {
1.339     albertel 9429: 	    if ($token->[0] eq 'S') {
                   9430: 		if (defined($token->[2]->{'package'})) {
1.172     www      9431: #
                   9432: # This is a package - get package info
                   9433: #
1.339     albertel 9434: 		    my $package=$token->[2]->{'package'};
                   9435: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9436: 		    if (defined($token->[2]->{'id'})) { 
                   9437: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9438: 		    }
1.599     albertel 9439: 		    if ($metaentry{':packages'}) {
                   9440: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9441: 		    } else {
1.599     albertel 9442: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9443: 		    }
1.736     albertel 9444: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9445: 			my $part=$keyroot;
                   9446: 			$part=~s/^\_//;
1.736     albertel 9447: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9448: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9449: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9450: 			    # ignore package.tab specified default values
                   9451:                             # here &package_tab_default() will fetch those
                   9452: 			    if ($subp eq 'default') { next; }
1.736     albertel 9453: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9454: 			    my $unikey;
                   9455: 			    if ($pack =~ /_0$/) {
                   9456: 				$unikey='parameter_0_'.$name;
                   9457: 				$part=0;
                   9458: 			    } else {
                   9459: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9460: 			    }
1.339     albertel 9461: 			    if ($subp eq 'display') {
                   9462: 				$value.=' [Part: '.$part.']';
                   9463: 			    }
1.599     albertel 9464: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9465: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9466: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9467: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9468: 			    }
1.599     albertel 9469: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9470: 				$metaentry{':'.$unikey}=
                   9471: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9472: 			    }
1.339     albertel 9473: 			}
                   9474: 		    }
                   9475: 		} else {
1.172     www      9476: #
                   9477: # This is not a package - some other kind of start tag
1.339     albertel 9478: #
                   9479: 		    my $entry=$token->[1];
1.1068    www      9480: 		    my $unikey='';
1.175     www      9481: 
1.339     albertel 9482: 		    if ($entry eq 'import') {
1.175     www      9483: #
                   9484: # Importing a library here
1.339     albertel 9485: #
1.1067    www      9486:                         my $location=$parser->get_text('/import');
                   9487:                         my $dir=$filename;
                   9488:                         $dir=~s|[^/]*$||;
                   9489:                         $location=&filelocation($dir,$location);
1.1069    www      9490:                        
1.1068    www      9491:                         my $importmode=$token->[2]->{'importmode'};
                   9492:                         if ($importmode eq 'problem') {
1.1069    www      9493: # Import as problem/response
1.1068    www      9494:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9495:                         } elsif ($importmode eq 'part') {
                   9496: # Import as part(s)
1.1069    www      9497:                            $importedparts=1;
                   9498: # We need to get the original file and the imported file to get the part order correct
                   9499: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9500: # Load and inspect original file
1.1070    www      9501:                            if ($#origfileimportpartids<0) {
                   9502:                               undef(%importedpartids);
                   9503:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9504:                               my $origfile=&getfile($origfilelocation);
                   9505:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9506:                            }
                   9507: 
1.1069    www      9508: # Load and inspect imported file
                   9509:                            my $impfile=&getfile($location);
                   9510:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9511:                            if ($#impfilepartids>=0) {
                   9512: # This problem had parts
1.1070    www      9513:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9514:                            } else {
                   9515: # Importing by turning a single problem into a problem part
                   9516: # It gets the import-tags ID as part-ID
                   9517:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9518:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9519:                            }
1.1068    www      9520:                         } else {
                   9521: # Normal import
                   9522:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9523:                            if (defined($token->[2]->{'id'})) {
                   9524:                               $unikey.='_'.$token->[2]->{'id'};
                   9525:                            }
1.1067    www      9526:                         }
                   9527: 
1.339     albertel 9528: 			if ($depthcount<20) {
1.736     albertel 9529: 			    my $metadata = 
                   9530: 				&metadata($uri,'keys', $location,$unikey,
                   9531: 					  $depthcount+1);
                   9532: 			    foreach my $meta (split(',',$metadata)) {
                   9533: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9534: 				$metathesekeys{$meta}=1;
1.339     albertel 9535: 			    }
1.1068    www      9536: 			
                   9537:                         }
1.1067    www      9538: 		    } else {
                   9539: #
                   9540: # Not importing, some other kind of non-package, non-library start tag
                   9541: # 
                   9542:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9543:                         if (defined($token->[2]->{'id'})) {
                   9544:                             $unikey.='_'.$token->[2]->{'id'};
                   9545:                         }
1.339     albertel 9546: 			if (defined($token->[2]->{'name'})) { 
                   9547: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9548: 			}
                   9549: 			$metathesekeys{$unikey}=1;
1.736     albertel 9550: 			foreach my $param (@{$token->[3]}) {
                   9551: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9552: 				$token->[2]->{$param};
1.339     albertel 9553: 			}
                   9554: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9555: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9556: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9557: 		 # only ws inside the tag, and not in default, so use default
                   9558: 		 # as value
1.599     albertel 9559: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9560: 			} elsif ( $internaltext =~ /\S/ ) {
                   9561: 		  # something interesting inside the tag
                   9562: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9563: 			} else {
1.908     albertel 9564: 		  # no interesting values, don't set a default
1.339     albertel 9565: 			}
1.172     www      9566: # end of not-a-package not-a-library import
1.339     albertel 9567: 		    }
1.172     www      9568: # end of not-a-package start tag
1.339     albertel 9569: 		}
1.172     www      9570: # the next is the end of "start tag"
1.339     albertel 9571: 	    }
                   9572: 	}
1.483     albertel 9573: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9574: 	$extension = lc($extension);
                   9575: 	if ($extension eq 'htm') { $extension='html'; }
                   9576: 
1.737     albertel 9577: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9578: 	    #no specific packages #how's our extension
                   9579: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9580: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9581: 					 \%metathesekeys);
                   9582: 	}
1.883     albertel 9583: 
                   9584: 	if (!exists($metaentry{':packages'})
                   9585: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9586: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9587: 		#no specific packages well let's get default then
                   9588: 		if ($key!~/^default&/) { next; }
1.488     albertel 9589: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9590: 					     \%metathesekeys);
                   9591: 	    }
                   9592: 	}
1.338     www      9593: # are there custom rights to evaluate
1.599     albertel 9594: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9595: 
1.338     www      9596:     #
                   9597:     # Importing a rights file here
1.339     albertel 9598:     #
                   9599: 	    unless ($depthcount) {
1.599     albertel 9600: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9601: 		my $dir=$filename;
                   9602: 		$dir=~s|[^/]*$||;
                   9603: 		$location=&filelocation($dir,$location);
1.736     albertel 9604: 		my $rights_metadata =
                   9605: 		    &metadata($uri,'keys',$location,'_rights',
                   9606: 			      $depthcount+1);
                   9607: 		foreach my $rights (split(',',$rights_metadata)) {
                   9608: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9609: 		    $metathesekeys{$rights}=1;
1.339     albertel 9610: 		}
                   9611: 	    }
                   9612: 	}
1.737     albertel 9613: 	# uniqifiy package listing
                   9614: 	my %seen;
                   9615: 	my @uniq_packages =
                   9616: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9617: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9618: 
1.1070    www      9619:         if ($importedparts) {
                   9620: # We had imported parts and need to rebuild partorder
                   9621:            $metaentry{':partorder'}='';
                   9622:            $metathesekeys{'partorder'}=1;
                   9623:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9624:                if ($origfileimportpartids[$index] eq 'part') {
                   9625: # original part, part of the problem
                   9626:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9627:                } else {
                   9628: # we have imported parts at this position
                   9629:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9630:                }
                   9631:            }
                   9632:            $metaentry{':partorder'}=~s/^\,//;
                   9633:         }
                   9634: 
1.737     albertel 9635: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9636: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9637: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9638: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9639: # this is the end of "was not already recently cached
1.71      www      9640:     }
1.599     albertel 9641:     return $metaentry{':'.$what};
1.261     albertel 9642: }
                   9643: 
1.488     albertel 9644: sub metadata_create_package_def {
1.483     albertel 9645:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9646:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9647:     if ($subp eq 'default') { next; }
                   9648:     
1.599     albertel 9649:     if (defined($metaentry{':packages'})) {
                   9650: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9651:     } else {
1.599     albertel 9652: 	$metaentry{':packages'}=$package;
1.483     albertel 9653:     }
                   9654:     my $value=$packagetab{$key};
                   9655:     my $unikey;
                   9656:     $unikey='parameter_0_'.$name;
1.599     albertel 9657:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9658:     $$metathesekeys{$unikey}=1;
1.599     albertel 9659:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9660: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9661:     }
1.599     albertel 9662:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9663: 	$metaentry{':'.$unikey}=
                   9664: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9665:     }
                   9666: }
                   9667: 
1.261     albertel 9668: sub metadata_generate_part0 {
                   9669:     my ($metadata,$metacache,$uri) = @_;
                   9670:     my %allnames;
1.737     albertel 9671:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9672: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9673: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9674: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9675: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9676: 	    $allnames{$name}=$part;
                   9677: 	  }
                   9678: 	}
                   9679:     }
                   9680:     foreach my $name (keys(%allnames)) {
                   9681:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9682:       my $key=":parameter_0_$name";
1.261     albertel 9683:       $$metacache{"$key.part"}='0';
                   9684:       $$metacache{"$key.name"}=$name;
1.428     albertel 9685:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9686: 					   $allnames{$name}.'_'.$name.
                   9687: 					   '.type'};
1.428     albertel 9688:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9689: 			     '.display'};
1.644     www      9690:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9691:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9692:       $$metacache{"$key.display"}=$olddis;
                   9693:     }
1.71      www      9694: }
                   9695: 
1.764     albertel 9696: # ------------------------------------------------------ Devalidate title cache
                   9697: 
                   9698: sub devalidate_title_cache {
                   9699:     my ($url)=@_;
                   9700:     if (!$env{'request.course.id'}) { return; }
                   9701:     my $symb=&symbread($url);
                   9702:     if (!$symb) { return; }
                   9703:     my $key=$env{'request.course.id'}."\0".$symb;
                   9704:     &devalidate_cache_new('title',$key);
                   9705: }
                   9706: 
1.1014    droeschl 9707: # ------------------------------------------------- Get the title of a course
                   9708: 
                   9709: sub current_course_title {
                   9710:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9711: }
1.301     www      9712: # ------------------------------------------------- Get the title of a resource
                   9713: 
                   9714: sub gettitle {
                   9715:     my $urlsymb=shift;
                   9716:     my $symb=&symbread($urlsymb);
1.534     albertel 9717:     if ($symb) {
1.620     albertel 9718: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9719: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9720: 	if (defined($cached)) { 
                   9721: 	    return $result;
                   9722: 	}
1.534     albertel 9723: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9724: 	my $title='';
1.907     albertel 9725: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9726: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9727: 	} else {
                   9728: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9729: 		    &GDBM_READER(),0640)) {
                   9730: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9731: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9732: 		untie(%bighash);
                   9733: 	    }
1.534     albertel 9734: 	}
                   9735: 	$title=~s/\&colon\;/\:/gs;
                   9736: 	if ($title) {
1.1159    www      9737: # Remember both $symb and $title for dynamic metadata
                   9738:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9739:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9740: # Cache this title and then return it
1.599     albertel 9741: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9742: 	}
                   9743: 	$urlsymb=$url;
                   9744:     }
                   9745:     my $title=&metadata($urlsymb,'title');
                   9746:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9747:     return $title;
1.301     www      9748: }
1.613     albertel 9749: 
1.614     albertel 9750: sub get_slot {
                   9751:     my ($which,$cnum,$cdom)=@_;
                   9752:     if (!$cnum || !$cdom) {
1.790     albertel 9753: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9754: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9755: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9756:     }
1.703     albertel 9757:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9758:     my %slotinfo;
                   9759:     if (exists($remembered{$key})) {
                   9760: 	$slotinfo{$which} = $remembered{$key};
                   9761:     } else {
                   9762: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9763: 	&Apache::lonhomework::showhash(%slotinfo);
                   9764: 	my ($tmp)=keys(%slotinfo);
                   9765: 	if ($tmp=~/^error:/) { return (); }
                   9766: 	$remembered{$key} = $slotinfo{$which};
                   9767:     }
1.616     albertel 9768:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9769: 	return %{$slotinfo{$which}};
                   9770:     }
                   9771:     return $slotinfo{$which};
1.614     albertel 9772: }
1.1150    raeburn  9773: 
                   9774: sub get_reservable_slots {
                   9775:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9776:     my $now = time;
                   9777:     my $reservable_info;
                   9778:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9779:     if (exists($remembered{$key})) {
                   9780:         $reservable_info = $remembered{$key};
                   9781:     } else {
                   9782:         my %resv;
                   9783:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9784:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9785:         $reservable_info = \%resv;
                   9786:         $remembered{$key} = $reservable_info;
                   9787:     }
                   9788:     return $reservable_info;
                   9789: }
                   9790: 
                   9791: sub get_course_slots {
                   9792:     my ($cnum,$cdom) = @_;
                   9793:     my $hashid=$cnum.':'.$cdom;
                   9794:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9795:     if (defined($cached)) {
                   9796:         if (ref($result) eq 'HASH') {
                   9797:             return %{$result};
                   9798:         }
                   9799:     } else {
                   9800:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9801:         my ($tmp) = keys(%slots);
                   9802:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9803:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9804:             return %slots;
                   9805:         }
                   9806:     }
                   9807:     return;
                   9808: }
                   9809: 
                   9810: sub devalidate_slots_cache {
                   9811:     my ($cnum,$cdom)=@_;
                   9812:     my $hashid=$cnum.':'.$cdom;
                   9813:     &devalidate_cache_new('allslots',$hashid);
                   9814: }
                   9815: 
1.31      www      9816: # ------------------------------------------------- Update symbolic store links
                   9817: 
                   9818: sub symblist {
                   9819:     my ($mapname,%newhash)=@_;
1.438     www      9820:     $mapname=&deversion(&declutter($mapname));
1.31      www      9821:     my %hash;
1.620     albertel 9822:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9823:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9824:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9825: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9826: 		next if ($url eq 'last_known'
                   9827: 			 && $env{'form.no_update_last_known'});
                   9828: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9829: 						    $newhash{$url}->[1],
                   9830: 						    $newhash{$url}->[0]);
1.191     harris41 9831:             }
1.31      www      9832:             if (untie(%hash)) {
                   9833: 		return 'ok';
                   9834:             }
                   9835:         }
                   9836:     }
                   9837:     return 'error';
1.212     www      9838: }
                   9839: 
                   9840: # --------------------------------------------------------------- Verify a symb
                   9841: 
                   9842: sub symbverify {
1.510     www      9843:     my ($symb,$thisurl)=@_;
                   9844:     my $thisfn=$thisurl;
1.439     www      9845:     $thisfn=&declutter($thisfn);
1.215     www      9846: # direct jump to resource in page or to a sequence - will construct own symbs
                   9847:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9848: # check URL part
1.409     www      9849:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9850: 
1.431     www      9851:     unless ($url eq $thisfn) { return 0; }
1.213     www      9852: 
1.216     www      9853:     $symb=&symbclean($symb);
1.510     www      9854:     $thisurl=&deversion($thisurl);
1.439     www      9855:     $thisfn=&deversion($thisfn);
1.213     www      9856: 
                   9857:     my %bighash;
                   9858:     my $okay=0;
1.431     www      9859: 
1.620     albertel 9860:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9861:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9862:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9863:             $thisurl =~ s/\?.+$//;
                   9864:         }
1.510     www      9865:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9866:         unless ($ids) {
                   9867:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9868:             $ids=$bighash{$idkey};
1.216     www      9869:         }
                   9870:         if ($ids) {
                   9871: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9872: 	    foreach my $id (split(/\,/,$ids)) {
                   9873: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9874:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9875:                    $symb =~ s/\?.+$//;
                   9876:                }
1.216     www      9877:                if (
                   9878:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9879:    eq $symb) { 
1.620     albertel 9880: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9881: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9882:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9883: 		       $okay=1; 
                   9884: 		   }
                   9885: 	       }
1.216     www      9886: 	   }
                   9887:         }
1.213     www      9888: 	untie(%bighash);
                   9889:     }
                   9890:     return $okay;
1.31      www      9891: }
                   9892: 
1.210     www      9893: # --------------------------------------------------------------- Clean-up symb
                   9894: 
                   9895: sub symbclean {
                   9896:     my $symb=shift;
1.568     albertel 9897:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9898: # remove version from map
                   9899:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9900: 
1.210     www      9901: # remove version from URL
                   9902:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9903: 
1.507     www      9904: # remove wrapper
                   9905: 
1.510     www      9906:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9907:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9908:     return $symb;
1.409     www      9909: }
                   9910: 
                   9911: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9912: 
                   9913: sub encode_symb {
                   9914:     my ($map,$resid,$url)=@_;
                   9915:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9916: }
1.409     www      9917: 
                   9918: sub decode_symb {
1.568     albertel 9919:     my $symb=shift;
                   9920:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9921:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9922:     return (&fixversion($map),$resid,&fixversion($url));
                   9923: }
                   9924: 
                   9925: sub fixversion {
                   9926:     my $fn=shift;
1.609     banghart 9927:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9928:     my %bighash;
                   9929:     my $uri=&clutter($fn);
1.620     albertel 9930:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9931: # is this cached?
1.599     albertel 9932:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9933:     if (defined($cached)) { return $result; }
                   9934: # unfortunately not cached, or expired
1.620     albertel 9935:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9936: 	    &GDBM_READER(),0640)) {
                   9937:  	if ($bighash{'version_'.$uri}) {
                   9938:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9939:  	    unless (($version eq 'mostrecent') || 
                   9940: 		    ($version==&getversion($uri))) {
1.440     www      9941:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9942:  	    }
                   9943:  	}
                   9944:  	untie %bighash;
1.413     www      9945:     }
1.599     albertel 9946:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9947: }
                   9948: 
                   9949: sub deversion {
                   9950:     my $url=shift;
                   9951:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9952:     return $url;
1.210     www      9953: }
                   9954: 
1.31      www      9955: # ------------------------------------------------------ Return symb list entry
                   9956: 
                   9957: sub symbread {
1.249     www      9958:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9959:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9960:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9961: # no filename provided? try from environment
1.44      www      9962:     unless ($thisfn) {
1.620     albertel 9963:         if ($env{'request.symb'}) {
                   9964: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9965: 	}
1.620     albertel 9966: 	$thisfn=$env{'request.filename'};
1.44      www      9967:     }
1.569     albertel 9968:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9969: # is that filename actually a symb? Verify, clean, and return
                   9970:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9971: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9972: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9973: 	}
1.242     www      9974:     }
1.44      www      9975:     $thisfn=declutter($thisfn);
1.31      www      9976:     my %hash;
1.37      www      9977:     my %bighash;
                   9978:     my $syval='';
1.620     albertel 9979:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9980:         my $targetfn = $thisfn;
1.609     banghart 9981:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9982:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9983:         }
1.687     albertel 9984: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9985: 	    $targetfn=$1;
                   9986: 	}
1.620     albertel 9987:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9988:                       &GDBM_READER(),0640)) {
1.481     raeburn  9989: 	    $syval=$hash{$targetfn};
1.37      www      9990:             untie(%hash);
                   9991:         }
                   9992: # ---------------------------------------------------------- There was an entry
                   9993:         if ($syval) {
1.601     albertel 9994: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9995: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9996: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9997: 		    #return $env{$cache_str}='';
1.601     albertel 9998: 		#}    
                   9999: 		#$syval.=$1;
                   10000: 	    #}
1.37      www      10001:         } else {
                   10002: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10003:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10004:                             &GDBM_READER(),0640)) {
1.37      www      10005: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10006:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10007:               unless ($ids) { 
                   10008:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10009:               }
                   10010:               unless ($ids) {
                   10011: # alias?
                   10012: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10013:               }
1.37      www      10014:               if ($ids) {
                   10015: # ------------------------------------------------------------------- Has ID(s)
                   10016:                  my @possibilities=split(/\,/,$ids);
1.39      www      10017:                  if ($#possibilities==0) {
                   10018: # ----------------------------------------------- There is only one possibility
1.37      www      10019: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10020: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10021: 						    $resid,$thisfn);
1.249     www      10022:                  } elsif (!$donotrecurse) {
1.39      www      10023: # ------------------------------------------ There is more than one possibility
                   10024:                      my $realpossible=0;
1.800     albertel 10025:                      foreach my $id (@possibilities) {
                   10026: 			 my $file=$bighash{'src_'.$id};
1.39      www      10027:                          if (&allowed('bre',$file)) {
1.800     albertel 10028:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10029:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10030: 				$realpossible++;
1.626     albertel 10031:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10032: 						    $resid,$thisfn);
1.39      www      10033:                             }
                   10034: 			 }
1.191     harris41 10035:                      }
1.39      www      10036: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10037:                  } else {
                   10038:                      $syval='';
1.37      www      10039:                  }
                   10040: 	      }
                   10041:               untie(%bighash)
1.481     raeburn  10042:            }
1.31      www      10043:         }
1.62      www      10044:         if ($syval) {
1.620     albertel 10045: 	    return $env{$cache_str}=$syval;
1.62      www      10046:         }
1.31      www      10047:     }
1.949     raeburn  10048:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10049:     return $env{$cache_str}='';
1.31      www      10050: }
                   10051: 
                   10052: # ---------------------------------------------------------- Return random seed
                   10053: 
1.32      www      10054: sub numval {
                   10055:     my $txt=shift;
                   10056:     $txt=~tr/A-J/0-9/;
                   10057:     $txt=~tr/a-j/0-9/;
                   10058:     $txt=~tr/K-T/0-9/;
                   10059:     $txt=~tr/k-t/0-9/;
                   10060:     $txt=~tr/U-Z/0-5/;
                   10061:     $txt=~tr/u-z/0-5/;
                   10062:     $txt=~s/\D//g;
1.564     albertel 10063:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10064:     return int($txt);
1.368     albertel 10065: }
                   10066: 
1.484     albertel 10067: sub numval2 {
                   10068:     my $txt=shift;
                   10069:     $txt=~tr/A-J/0-9/;
                   10070:     $txt=~tr/a-j/0-9/;
                   10071:     $txt=~tr/K-T/0-9/;
                   10072:     $txt=~tr/k-t/0-9/;
                   10073:     $txt=~tr/U-Z/0-5/;
                   10074:     $txt=~tr/u-z/0-5/;
                   10075:     $txt=~s/\D//g;
                   10076:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10077:     my $total;
                   10078:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10079:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10080:     return int($total);
                   10081: }
                   10082: 
1.575     albertel 10083: sub numval3 {
                   10084:     use integer;
                   10085:     my $txt=shift;
                   10086:     $txt=~tr/A-J/0-9/;
                   10087:     $txt=~tr/a-j/0-9/;
                   10088:     $txt=~tr/K-T/0-9/;
                   10089:     $txt=~tr/k-t/0-9/;
                   10090:     $txt=~tr/U-Z/0-5/;
                   10091:     $txt=~tr/u-z/0-5/;
                   10092:     $txt=~s/\D//g;
                   10093:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10094:     my $total;
                   10095:     foreach my $val (@txts) { $total+=$val; }
                   10096:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10097:     return $total;
                   10098: }
                   10099: 
1.675     albertel 10100: sub digest {
                   10101:     my ($data)=@_;
                   10102:     my $digest=&Digest::MD5::md5($data);
                   10103:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10104:     my ($e,$f);
                   10105:     {
                   10106:         use integer;
                   10107:         $e=($a+$b);
                   10108:         $f=($c+$d);
                   10109:         if ($_64bit) {
                   10110:             $e=(($e<<32)>>32);
                   10111:             $f=(($f<<32)>>32);
                   10112:         }
                   10113:     }
                   10114:     if (wantarray) {
                   10115: 	return ($e,$f);
                   10116:     } else {
                   10117: 	my $g;
                   10118: 	{
                   10119: 	    use integer;
                   10120: 	    $g=($e+$f);
                   10121: 	    if ($_64bit) {
                   10122: 		$g=(($g<<32)>>32);
                   10123: 	    }
                   10124: 	}
                   10125: 	return $g;
                   10126:     }
                   10127: }
                   10128: 
1.368     albertel 10129: sub latest_rnd_algorithm_id {
1.675     albertel 10130:     return '64bit5';
1.366     albertel 10131: }
1.32      www      10132: 
1.503     albertel 10133: sub get_rand_alg {
                   10134:     my ($courseid)=@_;
1.790     albertel 10135:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10136:     if ($courseid) {
1.620     albertel 10137: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10138:     }
                   10139:     return &latest_rnd_algorithm_id();
                   10140: }
                   10141: 
1.562     albertel 10142: sub validCODE {
                   10143:     my ($CODE)=@_;
                   10144:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10145:     return 0;
                   10146: }
                   10147: 
1.491     albertel 10148: sub getCODE {
1.620     albertel 10149:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10150:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10151: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10152: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10153: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10154:     }
                   10155:     return undef;
                   10156: }
1.1133    foxr     10157: #
                   10158: #  Determines the random seed for a specific context:
                   10159: #
                   10160: # parameters:
                   10161: #   symb      - in course context the symb for the seed.
                   10162: #   course_id - The course id of the form domain_coursenum.
                   10163: #   domain    - Domain for the user.
                   10164: #   course    - Course for the user.
                   10165: #   cenv      - environment of the course.
                   10166: #
                   10167: # NOTE:
                   10168: #   All parameters are picked out of the environment if missing
                   10169: #   or not defined.
                   10170: #   If a symb cannot be determined the current time is used instead.
                   10171: #
                   10172: #  For a given well defined symb, courside, domain, username,
                   10173: #  and course environment, the seed is reproducible.
                   10174: #
1.31      www      10175: sub rndseed {
1.1133    foxr     10176:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10177:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10178:     if (!defined($symb)) {
1.366     albertel 10179: 	unless ($symb=$wsymb) { return time; }
                   10180:     }
1.1146    foxr     10181:     if (!defined $courseid) { 
                   10182: 	$courseid=$wcourseid; 
                   10183:     }
                   10184:     if (!defined $domain) { $domain=$wdomain; }
                   10185:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10186: 
                   10187:     my $which;
                   10188:     if (defined($cenv->{'rndseed'})) {
                   10189: 	$which = $cenv->{'rndseed'};
                   10190:     } else {
                   10191: 	$which =&get_rand_alg($courseid);
                   10192:     }
1.491     albertel 10193:     if (defined(&getCODE())) {
1.1133    foxr     10194: 
1.675     albertel 10195: 	if ($which eq '64bit5') {
                   10196: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10197: 	} elsif ($which eq '64bit4') {
1.575     albertel 10198: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10199: 	} else {
                   10200: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10201: 	}
1.675     albertel 10202:     } elsif ($which eq '64bit5') {
                   10203: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10204:     } elsif ($which eq '64bit4') {
                   10205: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10206:     } elsif ($which eq '64bit3') {
                   10207: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10208:     } elsif ($which eq '64bit2') {
                   10209: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10210:     } elsif ($which eq '64bit') {
                   10211: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10212:     }
                   10213:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10214: }
                   10215: 
                   10216: sub rndseed_32bit {
                   10217:     my ($symb,$courseid,$domain,$username)=@_;
                   10218:     {
                   10219: 	use integer;
                   10220: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10221: 	my $symbseed=numval($symb) << 22;
                   10222: 	my $namechck=unpack("%32C*",$username) << 17;
                   10223: 	my $nameseed=numval($username) << 12;
                   10224: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10225: 	my $courseseed=unpack("%32C*",$courseid);
                   10226: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10227: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10228: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10229: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10230: 	return $num;
                   10231:     }
                   10232: }
                   10233: 
                   10234: sub rndseed_64bit {
                   10235:     my ($symb,$courseid,$domain,$username)=@_;
                   10236:     {
                   10237: 	use integer;
                   10238: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10239: 	my $symbseed=numval($symb) << 10;
                   10240: 	my $namechck=unpack("%32S*",$username);
                   10241: 	
                   10242: 	my $nameseed=numval($username) << 21;
                   10243: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10244: 	my $courseseed=unpack("%32S*",$courseid);
                   10245: 	
                   10246: 	my $num1=$symbchck+$symbseed+$namechck;
                   10247: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10248: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10249: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10250: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10251: 	return "$num1,$num2";
1.155     albertel 10252:     }
1.366     albertel 10253: }
                   10254: 
1.443     albertel 10255: sub rndseed_64bit2 {
                   10256:     my ($symb,$courseid,$domain,$username)=@_;
                   10257:     {
                   10258: 	use integer;
                   10259: 	# strings need to be an even # of cahracters long, it it is odd the
                   10260:         # last characters gets thrown away
                   10261: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10262: 	my $symbseed=numval($symb) << 10;
                   10263: 	my $namechck=unpack("%32S*",$username.' ');
                   10264: 	
                   10265: 	my $nameseed=numval($username) << 21;
1.501     albertel 10266: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10267: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10268: 	
                   10269: 	my $num1=$symbchck+$symbseed+$namechck;
                   10270: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10271: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10272: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10273: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10274: 	return "$num1,$num2";
                   10275:     }
                   10276: }
                   10277: 
                   10278: sub rndseed_64bit3 {
                   10279:     my ($symb,$courseid,$domain,$username)=@_;
                   10280:     {
                   10281: 	use integer;
                   10282: 	# strings need to be an even # of cahracters long, it it is odd the
                   10283:         # last characters gets thrown away
                   10284: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10285: 	my $symbseed=numval2($symb) << 10;
                   10286: 	my $namechck=unpack("%32S*",$username.' ');
                   10287: 	
                   10288: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10289: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10290: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10291: 	
                   10292: 	my $num1=$symbchck+$symbseed+$namechck;
                   10293: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10294: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10295: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10296: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10297: 	
1.503     albertel 10298: 	return "$num1:$num2";
1.443     albertel 10299:     }
                   10300: }
                   10301: 
1.575     albertel 10302: sub rndseed_64bit4 {
                   10303:     my ($symb,$courseid,$domain,$username)=@_;
                   10304:     {
                   10305: 	use integer;
                   10306: 	# strings need to be an even # of cahracters long, it it is odd the
                   10307:         # last characters gets thrown away
                   10308: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10309: 	my $symbseed=numval3($symb) << 10;
                   10310: 	my $namechck=unpack("%32S*",$username.' ');
                   10311: 	
                   10312: 	my $nameseed=numval3($username) << 21;
                   10313: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10314: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10315: 	
                   10316: 	my $num1=$symbchck+$symbseed+$namechck;
                   10317: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10318: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10319: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10320: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10321: 	
1.575     albertel 10322: 	return "$num1:$num2";
                   10323:     }
                   10324: }
                   10325: 
1.675     albertel 10326: sub rndseed_64bit5 {
                   10327:     my ($symb,$courseid,$domain,$username)=@_;
                   10328:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10329:     return "$num1:$num2";
                   10330: }
                   10331: 
1.366     albertel 10332: sub rndseed_CODE_64bit {
                   10333:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10334:     {
1.366     albertel 10335: 	use integer;
1.443     albertel 10336: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10337: 	my $symbseed=numval2($symb);
1.491     albertel 10338: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10339: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10340: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10341: 	my $num1=$symbseed+$CODEchck;
                   10342: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10343: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10344: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10345: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10346: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10347: 	return "$num1:$num2";
1.366     albertel 10348:     }
                   10349: }
                   10350: 
1.575     albertel 10351: sub rndseed_CODE_64bit4 {
                   10352:     my ($symb,$courseid,$domain,$username)=@_;
                   10353:     {
                   10354: 	use integer;
                   10355: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10356: 	my $symbseed=numval3($symb);
                   10357: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10358: 	my $CODEseed=numval3(&getCODE());
                   10359: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10360: 	my $num1=$symbseed+$CODEchck;
                   10361: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10362: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10363: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10364: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10365: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10366: 	return "$num1:$num2";
                   10367:     }
                   10368: }
                   10369: 
1.675     albertel 10370: sub rndseed_CODE_64bit5 {
                   10371:     my ($symb,$courseid,$domain,$username)=@_;
                   10372:     my $code = &getCODE();
                   10373:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10374:     return "$num1:$num2";
                   10375: }
                   10376: 
1.366     albertel 10377: sub setup_random_from_rndseed {
                   10378:     my ($rndseed)=@_;
1.503     albertel 10379:     if ($rndseed =~/([,:])/) {
                   10380: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10381: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10382:     } else {
                   10383: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10384:     }
1.36      albertel 10385: }
                   10386: 
1.474     albertel 10387: sub latest_receipt_algorithm_id {
1.835     albertel 10388:     return 'receipt3';
1.474     albertel 10389: }
                   10390: 
1.480     www      10391: sub recunique {
                   10392:     my $fucourseid=shift;
                   10393:     my $unique;
1.835     albertel 10394:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10395: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10396: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10397:     } else {
                   10398: 	$unique=$perlvar{'lonReceipt'};
                   10399:     }
                   10400:     return unpack("%32C*",$unique);
                   10401: }
                   10402: 
                   10403: sub recprefix {
                   10404:     my $fucourseid=shift;
                   10405:     my $prefix;
1.835     albertel 10406:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10407: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10408: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10409:     } else {
                   10410: 	$prefix=$perlvar{'lonHostID'};
                   10411:     }
                   10412:     return unpack("%32C*",$prefix);
                   10413: }
                   10414: 
1.76      www      10415: sub ireceipt {
1.474     albertel 10416:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10417: 
                   10418:     my $return =&recprefix($fucourseid).'-';
                   10419: 
                   10420:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10421: 	$env{'request.state'} eq 'construct') {
                   10422: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10423: 	return $return;
                   10424:     }
                   10425: 
1.76      www      10426:     my $cuname=unpack("%32C*",$funame);
                   10427:     my $cudom=unpack("%32C*",$fudom);
                   10428:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10429:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10430:     my $cunique=&recunique($fucourseid);
1.474     albertel 10431:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10432:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10433: 
1.790     albertel 10434: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10435: 			       
                   10436: 	$return.= ($cunique%$cuname+
                   10437: 		   $cunique%$cudom+
                   10438: 		   $cusymb%$cuname+
                   10439: 		   $cusymb%$cudom+
                   10440: 		   $cucourseid%$cuname+
                   10441: 		   $cucourseid%$cudom+
                   10442: 		   $cpart%$cuname+
                   10443: 		   $cpart%$cudom);
                   10444:     } else {
                   10445: 	$return.= ($cunique%$cuname+
                   10446: 		   $cunique%$cudom+
                   10447: 		   $cusymb%$cuname+
                   10448: 		   $cusymb%$cudom+
                   10449: 		   $cucourseid%$cuname+
                   10450: 		   $cucourseid%$cudom);
                   10451:     }
                   10452:     return $return;
1.76      www      10453: }
                   10454: 
                   10455: sub receipt {
1.474     albertel 10456:     my ($part)=@_;
1.790     albertel 10457:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10458:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10459: }
1.260     ng       10460: 
1.790     albertel 10461: sub whichuser {
                   10462:     my ($passedsymb)=@_;
                   10463:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10464:     if (defined($env{'form.grade_symb'})) {
                   10465: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10466: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10467: 	if (!$allowed &&
                   10468: 	    exists($env{'request.course.sec'}) &&
                   10469: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10470: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10471: 			      '/'.$env{'request.course.sec'});
                   10472: 	}
                   10473: 	if ($allowed) {
                   10474: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10475: 	    $courseid=$tmp_courseid;
                   10476: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10477: 	    ($name)=&get_env_multiple('form.grade_username');
                   10478: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10479: 	}
                   10480:     }
                   10481:     if (!$passedsymb) {
                   10482: 	$symb=&symbread();
                   10483:     } else {
                   10484: 	$symb=$passedsymb;
                   10485:     }
                   10486:     $courseid=$env{'request.course.id'};
                   10487:     $domain=$env{'user.domain'};
                   10488:     $name=$env{'user.name'};
                   10489:     if ($name eq 'public' && $domain eq 'public') {
                   10490: 	if (!defined($env{'form.username'})) {
                   10491: 	    $env{'form.username'}.=time.rand(10000000);
                   10492: 	}
                   10493: 	$name.=$env{'form.username'};
                   10494:     }
                   10495:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10496: 
                   10497: }
                   10498: 
1.36      albertel 10499: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10500: # returns either the contents of the file or 
                   10501: # -1 if the file doesn't exist
1.481     raeburn  10502: #
                   10503: # if the target is a file that was uploaded via DOCS, 
                   10504: # a check will be made to see if a current copy exists on the local server,
                   10505: # if it does this will be served, otherwise a copy will be retrieved from
                   10506: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10507: # the local server.   
1.472     albertel 10508: 
1.36      albertel 10509: sub getfile {
1.538     albertel 10510:     my ($file) = @_;
1.609     banghart 10511:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10512:     &repcopy($file);
                   10513:     return &readfile($file);
                   10514: }
                   10515: 
                   10516: sub repcopy_userfile {
                   10517:     my ($file)=@_;
1.1142    raeburn  10518:     my $londocroot = $perlvar{'lonDocRoot'};
                   10519:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10520:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10521:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10522: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10523:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10524:     if (-e "$file") {
1.828     www      10525: # we already have a local copy, check it out
1.538     albertel 10526: 	my @fileinfo = stat($file);
1.828     www      10527: 	my $rtncode;
                   10528: 	my $info;
1.538     albertel 10529: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10530: 	if ($lwpresp ne 'ok') {
1.828     www      10531: # there is no such file anymore, even though we had a local copy
1.482     albertel 10532: 	    if ($rtncode eq '404') {
1.538     albertel 10533: 		unlink($file);
1.482     albertel 10534: 	    }
                   10535: 	    return -1;
                   10536: 	}
                   10537: 	if ($info < $fileinfo[9]) {
1.828     www      10538: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10539: 	    return 'ok';
1.828     www      10540: 	} else {
                   10541: # the file is outdated, get rid of it
                   10542: 	    unlink($file);
1.482     albertel 10543: 	}
1.828     www      10544:     }
                   10545: # one way or the other, at this point, we don't have the file
                   10546: # construct the correct path for the file
                   10547:     my @parts = ($cdom,$cnum); 
                   10548:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10549: 	push @parts, split(/\//,$1);
                   10550:     }
                   10551:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10552:     foreach my $part (@parts) {
                   10553: 	$path .= '/'.$part;
                   10554: 	if (!-e $path) {
                   10555: 	    mkdir($path,0770);
1.482     albertel 10556: 	}
                   10557:     }
1.828     www      10558: # now the path exists for sure
                   10559: # get a user agent
                   10560:     my $ua=new LWP::UserAgent;
                   10561:     my $transferfile=$file.'.in.transfer';
                   10562: # FIXME: this should flock
                   10563:     if (-e $transferfile) { return 'ok'; }
                   10564:     my $request;
                   10565:     $uri=~s/^\///;
1.980     raeburn  10566:     my $homeserver = &homeserver($cnum,$cdom);
                   10567:     my $protocol = $protocol{$homeserver};
                   10568:     $protocol = 'http' if ($protocol ne 'https');
                   10569:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10570:     my $response=$ua->request($request,$transferfile);
                   10571: # did it work?
                   10572:     if ($response->is_error()) {
                   10573: 	unlink($transferfile);
                   10574: 	&logthis("Userfile repcopy failed for $uri");
                   10575: 	return -1;
                   10576:     }
                   10577: # worked, rename the transfer file
                   10578:     rename($transferfile,$file);
1.607     raeburn  10579:     return 'ok';
1.481     raeburn  10580: }
                   10581: 
1.517     albertel 10582: sub tokenwrapper {
                   10583:     my $uri=shift;
1.980     raeburn  10584:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10585:     $uri=~s|^/||;
1.620     albertel 10586:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10587:     my $token=$1;
1.552     albertel 10588:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10589:     if ($udom && $uname && $file) {
                   10590: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10591:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10592:         my $homeserver = &homeserver($uname,$udom);
                   10593:         my $protocol = $protocol{$homeserver};
                   10594:         $protocol = 'http' if ($protocol ne 'https');
                   10595:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10596:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10597:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10598:     } else {
                   10599:         return '/adm/notfound.html';
                   10600:     }
                   10601: }
                   10602: 
1.828     www      10603: # call with reqtype HEAD: get last modification time
                   10604: # call with reqtype GET: get the file contents
                   10605: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10606: #
1.481     raeburn  10607: sub getuploaded {
                   10608:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10609:     $uri=~s/^\///;
1.980     raeburn  10610:     my $homeserver = &homeserver($cnum,$cdom);
                   10611:     my $protocol = $protocol{$homeserver};
                   10612:     $protocol = 'http' if ($protocol ne 'https');
                   10613:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10614:     my $ua=new LWP::UserAgent;
                   10615:     my $request=new HTTP::Request($reqtype,$uri);
                   10616:     my $response=$ua->request($request);
                   10617:     $$rtncode = $response->code;
1.482     albertel 10618:     if (! $response->is_success()) {
                   10619: 	return 'failed';
                   10620:     }      
                   10621:     if ($reqtype eq 'HEAD') {
1.486     www      10622: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10623:     } elsif ($reqtype eq 'GET') {
                   10624: 	$$info = $response->content;
1.472     albertel 10625:     }
1.482     albertel 10626:     return 'ok';
1.36      albertel 10627: }
                   10628: 
1.481     raeburn  10629: sub readfile {
                   10630:     my $file = shift;
                   10631:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10632:     my $fh;
                   10633:     open($fh,"<$file");
                   10634:     my $a='';
1.800     albertel 10635:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10636:     return $a;
                   10637: }
                   10638: 
1.36      albertel 10639: sub filelocation {
1.590     banghart 10640:     my ($dir,$file) = @_;
                   10641:     my $location;
                   10642:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10643: 
                   10644:     if ($file =~ m-^/adm/-) {
                   10645: 	$file=~s-^/adm/wrapper/-/-;
                   10646: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10647:     }
1.882     albertel 10648: 
1.1139    www      10649:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10650:         $location = $file;
1.609     banghart 10651:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10652:         my ($udom,$uname,$filename)=
1.811     albertel 10653:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10654:         my $home=&homeserver($uname,$udom);
                   10655:         my $is_me=0;
                   10656:         my @ids=&current_machine_ids();
                   10657:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10658:         if ($is_me) {
1.1117    foxr     10659:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10660:         } else {
                   10661:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10662:   	      $udom.'/'.$uname.'/'.$filename;
                   10663:         }
1.882     albertel 10664:     } elsif ($file =~ m-^/adm/-) {
                   10665: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10666:     } else {
                   10667:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10668:         $file=~s:^/(res|priv)/:/:;
                   10669:         my $space=$1;
1.590     banghart 10670:         if ( !( $file =~ m:^/:) ) {
                   10671:             $location = $dir. '/'.$file;
                   10672:         } else {
1.1142    raeburn  10673:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10674:         }
1.59      albertel 10675:     }
1.590     banghart 10676:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10677:     while ($location=~m{/\.\./}) {
                   10678: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10679: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10680: 	} else {
                   10681: 	    $location=~ s{/\.\./}{/}g;
                   10682: 	}
                   10683:     } #remove dir/..
1.590     banghart 10684:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10685:     return $location;
1.46      www      10686: }
1.36      albertel 10687: 
1.46      www      10688: sub hreflocation {
                   10689:     my ($dir,$file)=@_;
1.980     raeburn  10690:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10691: 	$file=filelocation($dir,$file);
1.700     albertel 10692:     } elsif ($file=~m-^/adm/-) {
                   10693: 	$file=~s-^/adm/wrapper/-/-;
                   10694: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10695:     }
                   10696:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10697: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10698:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10699: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10700: 	        {/uploaded/$1/$2/}x;
1.46      www      10701:     }
1.913     albertel 10702:     if ($file=~ m{^/userfiles/}) {
                   10703: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10704:     }
1.462     albertel 10705:     return $file;
1.465     albertel 10706: }
                   10707: 
1.1139    www      10708: 
                   10709: 
                   10710: 
                   10711: 
1.465     albertel 10712: sub current_machine_domains {
1.853     albertel 10713:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10714: }
                   10715: 
                   10716: sub machine_domains {
                   10717:     my ($hostname) = @_;
1.465     albertel 10718:     my @domains;
1.838     albertel 10719:     my %hostname = &all_hostnames();
1.465     albertel 10720:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10721: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10722: 	if ($hostname eq $name) {
1.844     albertel 10723: 	    push(@domains,&host_domain($id));
1.465     albertel 10724: 	}
                   10725:     }
                   10726:     return @domains;
                   10727: }
                   10728: 
                   10729: sub current_machine_ids {
1.853     albertel 10730:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10731: }
                   10732: 
                   10733: sub machine_ids {
                   10734:     my ($hostname) = @_;
                   10735:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10736:     my @ids;
1.888     albertel 10737:     my %name_to_host = &all_names();
1.889     albertel 10738:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10739: 	return @{ $name_to_host{$hostname} };
                   10740:     }
                   10741:     return;
1.31      www      10742: }
                   10743: 
1.824     raeburn  10744: sub additional_machine_domains {
                   10745:     my @domains;
                   10746:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10747:     while( my $line = <$fh>) {
                   10748:         $line =~ s/\s//g;
                   10749:         push(@domains,$line);
                   10750:     }
                   10751:     return @domains;
                   10752: }
                   10753: 
                   10754: sub default_login_domain {
                   10755:     my $domain = $perlvar{'lonDefDomain'};
                   10756:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10757:     foreach my $posdom (&current_machine_domains(),
                   10758:                         &additional_machine_domains()) {
                   10759:         if (lc($posdom) eq lc($testdomain)) {
                   10760:             $domain=$posdom;
                   10761:             last;
                   10762:         }
                   10763:     }
                   10764:     return $domain;
                   10765: }
                   10766: 
1.31      www      10767: # ------------------------------------------------------------- Declutters URLs
                   10768: 
                   10769: sub declutter {
                   10770:     my $thisfn=shift;
1.569     albertel 10771:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10772:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10773:     $thisfn=~s/^\///;
1.697     albertel 10774:     $thisfn=~s|^adm/wrapper/||;
                   10775:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10776:     $thisfn=~s/^res\///;
1.1032    raeburn  10777:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10778:         $thisfn=~s/\?.+$//;
                   10779:     }
1.268     www      10780:     return $thisfn;
                   10781: }
                   10782: 
                   10783: # ------------------------------------------------------------- Clutter up URLs
                   10784: 
                   10785: sub clutter {
                   10786:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10787:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10788: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10789:        $thisfn='/res'.$thisfn; 
                   10790:     }
1.1031    raeburn  10791:     if ($thisfn !~m|^/adm|) {
                   10792: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10793: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10794: 	} else {
                   10795: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10796: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10797: 	    if ($embstyle eq 'ssi'
                   10798: 		|| ($embstyle eq 'hdn')
                   10799: 		|| ($embstyle eq 'rat')
                   10800: 		|| ($embstyle eq 'prv')
                   10801: 		|| ($embstyle eq 'ign')) {
                   10802: 		#do nothing with these
                   10803: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10804: 		|| ($embstyle eq 'emb')
                   10805: 		|| ($embstyle eq 'wrp')) {
                   10806: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10807: 	    } elsif ($embstyle eq 'unk'
                   10808: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10809: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10810: 	    } else {
1.718     www      10811: #		&logthis("Got a blank emb style");
1.695     albertel 10812: 	    }
1.694     albertel 10813: 	}
                   10814:     }
1.31      www      10815:     return $thisfn;
1.12      www      10816: }
                   10817: 
1.787     albertel 10818: sub clutter_with_no_wrapper {
                   10819:     my $uri = &clutter(shift);
                   10820:     if ($uri =~ m-^/adm/-) {
                   10821: 	$uri =~ s-^/adm/wrapper/-/-;
                   10822: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10823:     }
                   10824:     return $uri;
                   10825: }
                   10826: 
1.557     albertel 10827: sub freeze_escape {
                   10828:     my ($value)=@_;
                   10829:     if (ref($value)) {
                   10830: 	$value=&nfreeze($value);
                   10831: 	return '__FROZEN__'.&escape($value);
                   10832:     }
                   10833:     return &escape($value);
                   10834: }
                   10835: 
1.11      www      10836: 
1.557     albertel 10837: sub thaw_unescape {
                   10838:     my ($value)=@_;
                   10839:     if ($value =~ /^__FROZEN__/) {
                   10840: 	substr($value,0,10,undef);
                   10841: 	$value=&unescape($value);
                   10842: 	return &thaw($value);
                   10843:     }
                   10844:     return &unescape($value);
                   10845: }
                   10846: 
1.436     albertel 10847: sub correct_line_ends {
                   10848:     my ($result)=@_;
                   10849:     $$result =~s/\r\n/\n/mg;
                   10850:     $$result =~s/\r/\n/mg;
1.415     albertel 10851: }
1.1       albertel 10852: # ================================================================ Main Program
                   10853: 
1.184     www      10854: sub goodbye {
1.204     albertel 10855:    &logthis("Starting Shut down");
1.443     albertel 10856: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10857:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10858: #converted
1.599     albertel 10859: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10860:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10861: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10862: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10863: #1.1 only
1.870     albertel 10864: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10865: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10866: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10867: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10868:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10869:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10870:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10871:    &flushcourselogs();
                   10872:    &logthis("Shutting down");
                   10873: }
                   10874: 
1.852     albertel 10875: sub get_dns {
1.869     albertel 10876:     my ($url,$func,$ignore_cache) = @_;
                   10877:     if (!$ignore_cache) {
                   10878: 	my ($content,$cached)=
                   10879: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10880: 	if ($cached) {
                   10881: 	    &$func($content);
                   10882: 	    return;
                   10883: 	}
                   10884:     }
                   10885: 
                   10886:     my %alldns;
1.852     albertel 10887:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10888:     foreach my $dns (<$config>) {
                   10889: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10890:         my $line = $1;
                   10891:         my ($host,$protocol) = split(/:/,$line);
                   10892:         if ($protocol ne 'https') {
                   10893:             $protocol = 'http';
                   10894:         }
                   10895: 	$alldns{$host} = $protocol;
1.869     albertel 10896:     }
                   10897:     while (%alldns) {
                   10898: 	my ($dns) = keys(%alldns);
1.852     albertel 10899: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10900:         $ua->timeout(30);
1.979     raeburn  10901: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10902: 	my $response=$ua->request($request);
1.979     raeburn  10903:         delete($alldns{$dns});
1.852     albertel 10904: 	next if ($response->is_error());
                   10905: 	my @content = split("\n",$response->content);
1.869     albertel 10906: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10907: 	&$func(\@content);
1.869     albertel 10908: 	return;
1.852     albertel 10909:     }
                   10910:     close($config);
1.871     albertel 10911:     my $which = (split('/',$url))[3];
                   10912:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10913:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10914:     my @content = <$config>;
                   10915:     &$func(\@content);
                   10916:     return;
1.852     albertel 10917: }
1.327     albertel 10918: # ------------------------------------------------------------ Read domain file
                   10919: {
1.852     albertel 10920:     my $loaded;
1.846     albertel 10921:     my %domain;
                   10922: 
1.852     albertel 10923:     sub parse_domain_tab {
                   10924: 	my ($lines) = @_;
                   10925: 	foreach my $line (@$lines) {
                   10926: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10927: 
1.846     albertel 10928: 	    chomp($line);
1.852     albertel 10929: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10930: 	    my %this_domain;
                   10931: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10932: 			       'lang_def', 'city', 'longi', 'lati',
                   10933: 			       'primary') {
                   10934: 		$this_domain{$field} = shift(@elements);
                   10935: 	    }
                   10936: 	    $domain{$name} = \%this_domain;
1.852     albertel 10937: 	}
                   10938:     }
1.864     albertel 10939: 
                   10940:     sub reset_domain_info {
                   10941: 	undef($loaded);
                   10942: 	undef(%domain);
                   10943:     }
                   10944: 
1.852     albertel 10945:     sub load_domain_tab {
1.869     albertel 10946: 	my ($ignore_cache) = @_;
                   10947: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10948: 	my $fh;
                   10949: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10950: 	    my @lines = <$fh>;
                   10951: 	    &parse_domain_tab(\@lines);
1.448     albertel 10952: 	}
1.852     albertel 10953: 	close($fh);
                   10954: 	$loaded = 1;
1.327     albertel 10955:     }
1.846     albertel 10956: 
                   10957:     sub domain {
1.852     albertel 10958: 	&load_domain_tab() if (!$loaded);
                   10959: 
1.846     albertel 10960: 	my ($name,$what) = @_;
                   10961: 	return if ( !exists($domain{$name}) );
                   10962: 
                   10963: 	if (!$what) {
                   10964: 	    return $domain{$name}{'description'};
                   10965: 	}
                   10966: 	return $domain{$name}{$what};
                   10967:     }
1.974     raeburn  10968: 
                   10969:     sub domain_info {
                   10970:         &load_domain_tab() if (!$loaded);
                   10971:         return %domain;
                   10972:     }
                   10973: 
1.327     albertel 10974: }
                   10975: 
                   10976: 
1.1       albertel 10977: # ------------------------------------------------------------- Read hosts file
                   10978: {
1.838     albertel 10979:     my %hostname;
1.844     albertel 10980:     my %hostdom;
1.845     albertel 10981:     my %libserv;
1.852     albertel 10982:     my $loaded;
1.888     albertel 10983:     my %name_to_host;
1.1074    raeburn  10984:     my %internetdom;
1.1107    raeburn  10985:     my %LC_dns_serv;
1.852     albertel 10986: 
                   10987:     sub parse_hosts_tab {
                   10988: 	my ($file) = @_;
                   10989: 	foreach my $configline (@$file) {
                   10990: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10991:             chomp($configline);
                   10992: 	    if ($configline =~ /^\^/) {
                   10993:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10994:                     $LC_dns_serv{$1} = 1;
                   10995:                 }
                   10996:                 next;
                   10997:             }
1.1074    raeburn  10998: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10999: 	    $name=~s/\s//g;
                   11000: 	    if ($id && $domain && $role && $name) {
                   11001: 		$hostname{$id}=$name;
1.888     albertel 11002: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11003: 		$hostdom{$id}=$domain;
                   11004: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11005:                 if (defined($protocol)) {
                   11006:                     if ($protocol eq 'https') {
                   11007:                         $protocol{$id} = $protocol;
                   11008:                     } else {
                   11009:                         $protocol{$id} = 'http'; 
                   11010:                     }
1.968     raeburn  11011:                 } else {
1.969     raeburn  11012:                     $protocol{$id} = 'http';
1.968     raeburn  11013:                 }
1.1074    raeburn  11014:                 if (defined($intdom)) {
                   11015:                     $internetdom{$id} = $intdom;
                   11016:                 }
1.852     albertel 11017: 	    }
                   11018: 	}
                   11019:     }
1.864     albertel 11020:     
                   11021:     sub reset_hosts_info {
1.897     albertel 11022: 	&purge_remembered();
1.864     albertel 11023: 	&reset_domain_info();
                   11024: 	&reset_hosts_ip_info();
1.892     albertel 11025: 	undef(%name_to_host);
1.864     albertel 11026: 	undef(%hostname);
                   11027: 	undef(%hostdom);
                   11028: 	undef(%libserv);
                   11029: 	undef($loaded);
                   11030:     }
1.1       albertel 11031: 
1.852     albertel 11032:     sub load_hosts_tab {
1.869     albertel 11033: 	my ($ignore_cache) = @_;
                   11034: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11035: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11036: 	my @config = <$config>;
                   11037: 	&parse_hosts_tab(\@config);
                   11038: 	close($config);
                   11039: 	$loaded=1;
1.1       albertel 11040:     }
1.852     albertel 11041: 
1.838     albertel 11042:     sub hostname {
1.852     albertel 11043: 	&load_hosts_tab() if (!$loaded);
                   11044: 
1.838     albertel 11045: 	my ($lonid) = @_;
                   11046: 	return $hostname{$lonid};
                   11047:     }
1.845     albertel 11048: 
1.838     albertel 11049:     sub all_hostnames {
1.852     albertel 11050: 	&load_hosts_tab() if (!$loaded);
                   11051: 
1.838     albertel 11052: 	return %hostname;
                   11053:     }
1.845     albertel 11054: 
1.888     albertel 11055:     sub all_names {
                   11056: 	&load_hosts_tab() if (!$loaded);
                   11057: 
                   11058: 	return %name_to_host;
                   11059:     }
                   11060: 
1.974     raeburn  11061:     sub all_host_domain {
                   11062:         &load_hosts_tab() if (!$loaded);
                   11063:         return %hostdom;
                   11064:     }
                   11065: 
1.845     albertel 11066:     sub is_library {
1.852     albertel 11067: 	&load_hosts_tab() if (!$loaded);
                   11068: 
1.845     albertel 11069: 	return exists($libserv{$_[0]});
                   11070:     }
                   11071: 
                   11072:     sub all_library {
1.852     albertel 11073: 	&load_hosts_tab() if (!$loaded);
                   11074: 
1.845     albertel 11075: 	return %libserv;
                   11076:     }
                   11077: 
1.1062    droeschl 11078:     sub unique_library {
                   11079: 	#2x reverse removes all hostnames that appear more than once
                   11080:         my %unique = reverse &all_library();
                   11081:         return reverse %unique;
                   11082:     }
                   11083: 
1.841     albertel 11084:     sub get_servers {
1.852     albertel 11085: 	&load_hosts_tab() if (!$loaded);
                   11086: 
1.841     albertel 11087: 	my ($domain,$type) = @_;
                   11088: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11089: 	                                          : %hostname;
                   11090: 	my %result;
1.842     albertel 11091: 	if (ref($domain) eq 'ARRAY') {
                   11092: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11093: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11094: 		    $result{$host} = $hostname;
                   11095: 		}
                   11096: 	    }
                   11097: 	} else {
                   11098: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11099: 		if ($hostdom{$host} eq $domain) {
                   11100: 		    $result{$host} = $hostname;
                   11101: 		}
1.841     albertel 11102: 	    }
                   11103: 	}
                   11104: 	return %result;
                   11105:     }
1.845     albertel 11106: 
1.1062    droeschl 11107:     sub get_unique_servers {
                   11108:         my %unique = reverse &get_servers(@_);
                   11109: 	return reverse %unique;
                   11110:     }
                   11111: 
1.844     albertel 11112:     sub host_domain {
1.852     albertel 11113: 	&load_hosts_tab() if (!$loaded);
                   11114: 
1.844     albertel 11115: 	my ($lonid) = @_;
                   11116: 	return $hostdom{$lonid};
                   11117:     }
                   11118: 
1.841     albertel 11119:     sub all_domains {
1.852     albertel 11120: 	&load_hosts_tab() if (!$loaded);
                   11121: 
1.841     albertel 11122: 	my %seen;
                   11123: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11124: 	return @uniq;
                   11125:     }
1.1074    raeburn  11126: 
                   11127:     sub internet_dom {
                   11128:         &load_hosts_tab() if (!$loaded);
                   11129: 
                   11130:         my ($lonid) = @_;
                   11131:         return $internetdom{$lonid};
                   11132:     }
1.1107    raeburn  11133: 
                   11134:     sub is_LC_dns {
                   11135:         &load_hosts_tab() if (!$loaded);
                   11136: 
                   11137:         my ($hostname) = @_;
                   11138:         return exists($LC_dns_serv{$hostname});
                   11139:     }
                   11140: 
1.1       albertel 11141: }
                   11142: 
1.847     albertel 11143: { 
                   11144:     my %iphost;
1.856     albertel 11145:     my %name_to_ip;
                   11146:     my %lonid_to_ip;
1.869     albertel 11147: 
1.847     albertel 11148:     sub get_hosts_from_ip {
                   11149: 	my ($ip) = @_;
                   11150: 	my %iphosts = &get_iphost();
                   11151: 	if (ref($iphosts{$ip})) {
                   11152: 	    return @{$iphosts{$ip}};
                   11153: 	}
                   11154: 	return;
1.839     albertel 11155:     }
1.864     albertel 11156:     
                   11157:     sub reset_hosts_ip_info {
                   11158: 	undef(%iphost);
                   11159: 	undef(%name_to_ip);
                   11160: 	undef(%lonid_to_ip);
                   11161:     }
1.856     albertel 11162: 
                   11163:     sub get_host_ip {
                   11164: 	my ($lonid) = @_;
                   11165: 	if (exists($lonid_to_ip{$lonid})) {
                   11166: 	    return $lonid_to_ip{$lonid};
                   11167: 	}
                   11168: 	my $name=&hostname($lonid);
                   11169:    	my $ip = gethostbyname($name);
                   11170: 	return if (!$ip || length($ip) ne 4);
                   11171: 	$ip=inet_ntoa($ip);
                   11172: 	$name_to_ip{$name}   = $ip;
                   11173: 	$lonid_to_ip{$lonid} = $ip;
                   11174: 	return $ip;
                   11175:     }
1.847     albertel 11176:     
                   11177:     sub get_iphost {
1.869     albertel 11178: 	my ($ignore_cache) = @_;
1.894     albertel 11179: 
1.869     albertel 11180: 	if (!$ignore_cache) {
                   11181: 	    if (%iphost) {
                   11182: 		return %iphost;
                   11183: 	    }
                   11184: 	    my ($ip_info,$cached)=
                   11185: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11186: 	    if ($cached) {
                   11187: 		%iphost      = %{$ip_info->[0]};
                   11188: 		%name_to_ip  = %{$ip_info->[1]};
                   11189: 		%lonid_to_ip = %{$ip_info->[2]};
                   11190: 		return %iphost;
                   11191: 	    }
                   11192: 	}
1.894     albertel 11193: 
                   11194: 	# get yesterday's info for fallback
                   11195: 	my %old_name_to_ip;
                   11196: 	my ($ip_info,$cached)=
                   11197: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11198: 	if ($cached) {
                   11199: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11200: 	}
                   11201: 
1.888     albertel 11202: 	my %name_to_host = &all_names();
                   11203: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11204: 	    my $ip;
                   11205: 	    if (!exists($name_to_ip{$name})) {
                   11206: 		$ip = gethostbyname($name);
                   11207: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11208: 		    if (defined($old_name_to_ip{$name})) {
                   11209: 			$ip = $old_name_to_ip{$name};
                   11210: 			&logthis("Can't find $name defaulting to old $ip");
                   11211: 		    } else {
                   11212: 			&logthis("Name $name no IP found");
                   11213: 			next;
                   11214: 		    }
                   11215: 		} else {
                   11216: 		    $ip=inet_ntoa($ip);
1.847     albertel 11217: 		}
                   11218: 		$name_to_ip{$name} = $ip;
                   11219: 	    } else {
                   11220: 		$ip = $name_to_ip{$name};
1.653     albertel 11221: 	    }
1.888     albertel 11222: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11223: 		$lonid_to_ip{$id} = $ip;
                   11224: 	    }
                   11225: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11226: 	}
1.869     albertel 11227: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11228: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11229: 				      48*60*60);
1.869     albertel 11230: 
1.847     albertel 11231: 	return %iphost;
1.598     albertel 11232:     }
                   11233: 
1.992     raeburn  11234:     #
                   11235:     #  Given a DNS returns the loncapa host name for that DNS 
                   11236:     # 
                   11237:     sub host_from_dns {
                   11238:         my ($dns) = @_;
                   11239:         my @hosts;
                   11240:         my $ip;
                   11241: 
1.993     raeburn  11242:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11243:             $ip = $name_to_ip{$dns};
                   11244:         }
                   11245:         if (!$ip) {
                   11246:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11247:             if (length($ip) == 4) { 
                   11248: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11249:             }
                   11250:         }
                   11251:         if ($ip) {
                   11252: 	    @hosts = get_hosts_from_ip($ip);
                   11253: 	    return $hosts[0];
                   11254:         }
                   11255:         return undef;
1.986     foxr     11256:     }
1.992     raeburn  11257: 
1.1074    raeburn  11258:     sub get_internet_names {
                   11259:         my ($lonid) = @_;
                   11260:         return if ($lonid eq '');
                   11261:         my ($idnref,$cached)=
                   11262:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11263:         if ($cached) {
                   11264:             return $idnref;
                   11265:         }
                   11266:         my $ip = &get_host_ip($lonid);
                   11267:         my @hosts = &get_hosts_from_ip($ip);
                   11268:         my %iphost = &get_iphost();
                   11269:         my (@idns,%seen);
                   11270:         foreach my $id (@hosts) {
                   11271:             my $dom = &host_domain($id);
                   11272:             my $prim_id = &domain($dom,'primary');
                   11273:             my $prim_ip = &get_host_ip($prim_id);
                   11274:             next if ($seen{$prim_ip});
                   11275:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11276:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11277:                     my $intdom = &internet_dom($id);
                   11278:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11279:                         push(@idns,$intdom);
                   11280:                     }
                   11281:                 }
                   11282:             }
                   11283:             $seen{$prim_ip} = 1;
                   11284:         }
                   11285:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11286:     }
                   11287: 
1.986     foxr     11288: }
                   11289: 
1.1079    raeburn  11290: sub all_loncaparevs {
                   11291:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
                   11292: }
                   11293: 
1.862     albertel 11294: BEGIN {
                   11295: 
                   11296: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11297:     unless ($readit) {
                   11298: {
                   11299:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11300:     %perlvar = (%perlvar,%{$configvars});
                   11301: }
                   11302: 
                   11303: 
1.1       albertel 11304: # ------------------------------------------------------ Read spare server file
                   11305: {
1.448     albertel 11306:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11307: 
                   11308:     while (my $configline=<$config>) {
                   11309:        chomp($configline);
1.284     matthew  11310:        if ($configline) {
1.784     albertel 11311: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11312: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11313: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11314:        }
                   11315:     }
1.448     albertel 11316:     close($config);
1.1       albertel 11317: }
1.11      www      11318: # ------------------------------------------------------------ Read permissions
                   11319: {
1.448     albertel 11320:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11321: 
                   11322:     while (my $configline=<$config>) {
1.448     albertel 11323: 	chomp($configline);
                   11324: 	if ($configline) {
                   11325: 	    my ($role,$perm)=split(/ /,$configline);
                   11326: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11327: 	}
1.11      www      11328:     }
1.448     albertel 11329:     close($config);
1.11      www      11330: }
                   11331: 
                   11332: # -------------------------------------------- Read plain texts for permissions
                   11333: {
1.448     albertel 11334:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11335: 
                   11336:     while (my $configline=<$config>) {
1.448     albertel 11337: 	chomp($configline);
                   11338: 	if ($configline) {
1.742     raeburn  11339: 	    my ($short,@plain)=split(/:/,$configline);
                   11340:             %{$prp{$short}} = ();
                   11341: 	    if (@plain > 0) {
                   11342:                 $prp{$short}{'std'} = $plain[0];
                   11343:                 for (my $i=1; $i<@plain; $i++) {
                   11344:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11345:                 }
                   11346:             }
1.448     albertel 11347: 	}
1.135     www      11348:     }
1.448     albertel 11349:     close($config);
1.135     www      11350: }
                   11351: 
                   11352: # ---------------------------------------------------------- Read package table
                   11353: {
1.448     albertel 11354:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11355: 
                   11356:     while (my $configline=<$config>) {
1.483     albertel 11357: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11358: 	chomp($configline);
                   11359: 	my ($short,$plain)=split(/:/,$configline);
                   11360: 	my ($pack,$name)=split(/\&/,$short);
                   11361: 	if ($plain ne '') {
                   11362: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11363: 	    $packagetab{$short}=$plain; 
                   11364: 	}
1.11      www      11365:     }
1.448     albertel 11366:     close($config);
1.329     matthew  11367: }
                   11368: 
1.1073    raeburn  11369: # ---------------------------------------------------------- Read loncaparev table
                   11370: {
                   11371:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11372:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11373:             while (my $configline=<$config>) {
                   11374:                 chomp($configline);
                   11375:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11376:                 $loncaparevs{$hostid}=$loncaparev;
                   11377:             }
                   11378:             close($config);
                   11379:         }
                   11380:     }
                   11381: }
                   11382: 
1.1074    raeburn  11383: # ---------------------------------------------------------- Read serverhostID table
                   11384: {
                   11385:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11386:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11387:             while (my $configline=<$config>) {
                   11388:                 chomp($configline);
                   11389:                 my ($name,$id)=split(/:/,$configline);
                   11390:                 $serverhomeIDs{$name}=$id;
                   11391:             }
                   11392:             close($config);
                   11393:         }
                   11394:     }
                   11395: }
                   11396: 
1.1079    raeburn  11397: {
                   11398:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11399:     if (-e $file) {
                   11400:         my $parser = HTML::LCParser->new($file);
                   11401:         while (my $token = $parser->get_token()) {
                   11402:             if ($token->[0] eq 'S') {
                   11403:                 my $item = $token->[1];
                   11404:                 my $name = $token->[2]{'name'};
                   11405:                 my $value = $token->[2]{'value'};
                   11406:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11407:                     my $release = $parser->get_text();
                   11408:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11409:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11410:                 }
                   11411:             }
                   11412:         }
                   11413:     }
1.1073    raeburn  11414: }
                   11415: 
1.1138    raeburn  11416: # ---------------------------------------------------------- Read managers table
                   11417: {
                   11418:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11419:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11420:             while (my $configline=<$config>) {
                   11421:                 chomp($configline);
                   11422:                 next if ($configline =~ /^\#/);
                   11423:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11424:                     $managerstab{$configline} = 1;
                   11425:                 }
                   11426:             }
                   11427:             close($config);
                   11428:         }
                   11429:     }
                   11430: }
                   11431: 
1.329     matthew  11432: # ------------- set up temporary directory
                   11433: {
1.1117    foxr     11434:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11435: 
1.11      www      11436: }
                   11437: 
1.794     albertel 11438: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11439: 				'compress_threshold'=> 20_000,
                   11440:  			        });
1.185     www      11441: 
1.281     www      11442: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11443: $dumpcount=0;
1.958     www      11444: $locknum=0;
1.22      www      11445: 
1.163     harris41 11446: &logtouch();
1.672     albertel 11447: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11448: $readit=1;
1.564     albertel 11449:     {
                   11450: 	use integer;
                   11451: 	my $test=(2**32)+1;
1.568     albertel 11452: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11453: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11454:     }
1.195     www      11455: }
1.1       albertel 11456: }
1.179     www      11457: 
1.1       albertel 11458: 1;
1.191     harris41 11459: __END__
                   11460: 
1.243     albertel 11461: =pod
                   11462: 
1.191     harris41 11463: =head1 NAME
                   11464: 
1.243     albertel 11465: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11466: 
                   11467: =head1 SYNOPSIS
                   11468: 
1.243     albertel 11469: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11470: 
                   11471:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11472: 
1.243     albertel 11473: Common parameters:
                   11474: 
                   11475: =over 4
                   11476: 
                   11477: =item *
                   11478: 
                   11479: $uname : an internal username (if $cname expecting a course Id specifically)
                   11480: 
                   11481: =item *
                   11482: 
                   11483: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11484: 
                   11485: =item *
                   11486: 
                   11487: $symb : a resource instance identifier
                   11488: 
                   11489: =item *
                   11490: 
                   11491: $namespace : the name of a .db file that contains the data needed or
                   11492: being set.
                   11493: 
                   11494: =back
                   11495: 
1.394     bowersj2 11496: =head1 OVERVIEW
1.191     harris41 11497: 
1.394     bowersj2 11498: lonnet provides subroutines which interact with the
                   11499: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11500: about classes, users, and resources.
1.243     albertel 11501: 
                   11502: For many of these objects you can also use this to store data about
                   11503: them or modify them in various ways.
1.191     harris41 11504: 
1.394     bowersj2 11505: =head2 Symbs
1.191     harris41 11506: 
1.394     bowersj2 11507: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11508: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11509: map, the resource number of the resource in the map, and the URL of
                   11510: the resource itself. The latter is somewhat redundant, but might help
                   11511: if maps change.
                   11512: 
                   11513: An example is
                   11514: 
                   11515:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11516: 
                   11517: The respective map entry is
                   11518: 
                   11519:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11520:   title="Problem 2">
                   11521:  </resource>
                   11522: 
                   11523: Symbs are used by the random number generator, as well as to store and
                   11524: restore data specific to a certain instance of for example a problem.
                   11525: 
                   11526: =head2 Storing And Retrieving Data
                   11527: 
                   11528: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11529: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11530: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11531: is is the non-critical message twin of cstore. These functions are for
                   11532: handlers to store a perl hash to a user's permanent data space in an
                   11533: easy manner, and to retrieve it again on another call. It is expected
                   11534: that a handler would use this once at the beginning to retrieve data,
                   11535: and then again once at the end to send only the new data back.
                   11536: 
                   11537: The data is stored in the user's data directory on the user's
                   11538: homeserver under the ID of the course.
                   11539: 
                   11540: The hash that is returned by restore will have all of the previous
                   11541: value for all of the elements of the hash.
                   11542: 
                   11543: Example:
                   11544: 
                   11545:  #creating a hash
                   11546:  my %hash;
                   11547:  $hash{'foo'}='bar';
                   11548: 
                   11549:  #storing it
                   11550:  &Apache::lonnet::cstore(\%hash);
                   11551: 
                   11552:  #changing a value
                   11553:  $hash{'foo'}='notbar';
                   11554: 
                   11555:  #adding a new value
                   11556:  $hash{'bar'}='foo';
                   11557:  &Apache::lonnet::cstore(\%hash);
                   11558: 
                   11559:  #retrieving the hash
                   11560:  my %history=&Apache::lonnet::restore();
                   11561: 
                   11562:  #print the hash
                   11563:  foreach my $key (sort(keys(%history))) {
                   11564:    print("\%history{$key} = $history{$key}");
                   11565:  }
                   11566: 
                   11567: Will print out:
1.191     harris41 11568: 
1.394     bowersj2 11569:  %history{1:foo} = bar
                   11570:  %history{1:keys} = foo:timestamp
                   11571:  %history{1:timestamp} = 990455579
                   11572:  %history{2:bar} = foo
                   11573:  %history{2:foo} = notbar
                   11574:  %history{2:keys} = foo:bar:timestamp
                   11575:  %history{2:timestamp} = 990455580
                   11576:  %history{bar} = foo
                   11577:  %history{foo} = notbar
                   11578:  %history{timestamp} = 990455580
                   11579:  %history{version} = 2
                   11580: 
                   11581: Note that the special hash entries C<keys>, C<version> and
                   11582: C<timestamp> were added to the hash. C<version> will be equal to the
                   11583: total number of versions of the data that have been stored. The
                   11584: C<timestamp> attribute will be the UNIX time the hash was
                   11585: stored. C<keys> is available in every historical section to list which
                   11586: keys were added or changed at a specific historical revision of a
                   11587: hash.
                   11588: 
                   11589: B<Warning>: do not store the hash that restore returns directly. This
                   11590: will cause a mess since it will restore the historical keys as if the
                   11591: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11592: 
1.394     bowersj2 11593: Calling convention:
1.191     harris41 11594: 
1.394     bowersj2 11595:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11596:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11597: 
1.394     bowersj2 11598: For more detailed information, see lonnet specific documentation.
1.191     harris41 11599: 
1.394     bowersj2 11600: =head1 RETURN MESSAGES
1.191     harris41 11601: 
1.394     bowersj2 11602: =over 4
1.191     harris41 11603: 
1.394     bowersj2 11604: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11605: 
1.394     bowersj2 11606: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11607: when the connection is brought back up
1.191     harris41 11608: 
1.394     bowersj2 11609: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11610: for later delivery
1.191     harris41 11611: 
1.967     bisitz   11612: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11613: 
1.394     bowersj2 11614: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11615: that was requested
1.191     harris41 11616: 
1.243     albertel 11617: =back
1.191     harris41 11618: 
1.243     albertel 11619: =head1 PUBLIC SUBROUTINES
1.191     harris41 11620: 
1.243     albertel 11621: =head2 Session Environment Functions
1.191     harris41 11622: 
1.243     albertel 11623: =over 4
1.191     harris41 11624: 
1.394     bowersj2 11625: =item * 
                   11626: X<appenv()>
1.949     raeburn  11627: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11628: the user envirnoment file, and will be restored for each access this
1.620     albertel 11629: user makes during this session, also modifies the %env for the current
1.949     raeburn  11630: process. Optional rolesarrayref - if defined contains a reference to an array
                   11631: of roles which are exempt from the restriction on modifying user.role entries 
                   11632: in the user's environment.db and in %env.    
1.191     harris41 11633: 
                   11634: =item *
1.394     bowersj2 11635: X<delenv()>
1.987     raeburn  11636: B<delenv($delthis,$regexp)>: removes all items from the session
                   11637: environment file that begin with $delthis. If the 
                   11638: optional second arg - $regexp - is true, $delthis is treated as a 
                   11639: regular expression, otherwise \Q$delthis\E is used. 
                   11640: The values are also deleted from the current processes %env.
1.191     harris41 11641: 
1.795     albertel 11642: =item * get_env_multiple($name) 
                   11643: 
                   11644: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11645: values may be defined and end up as an array ref.
                   11646: 
                   11647: returns an array of values
                   11648: 
1.243     albertel 11649: =back
                   11650: 
                   11651: =head2 User Information
1.191     harris41 11652: 
1.243     albertel 11653: =over 4
1.191     harris41 11654: 
                   11655: =item *
1.394     bowersj2 11656: X<queryauthenticate()>
                   11657: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11658: authentication scheme
                   11659: 
                   11660: =item *
1.394     bowersj2 11661: X<authenticate()>
1.1073    raeburn  11662: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11663: authenticate user from domain's lib servers (first use the current
                   11664: one). C<$upass> should be the users password.
1.1073    raeburn  11665: $checkdefauth is optional (value is 1 if a check should be made to
                   11666:    authenticate user using default authentication method, and allow
                   11667:    account creation if username does not have account in the domain).
                   11668: $clientcancheckhost is optional (value is 1 if checking whether the
                   11669:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11670: 
                   11671: =item *
1.394     bowersj2 11672: X<homeserver()>
                   11673: B<homeserver($uname,$udom)>: find the server which has
                   11674: the user's directory and files (there must be only one), this caches
                   11675: the answer, and also caches if there is a borken connection.
1.191     harris41 11676: 
                   11677: =item *
1.394     bowersj2 11678: X<idget()>
                   11679: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11680: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11681: username, and only 1 username per ID in a specific domain) (returns
                   11682: hash: id=>name,id=>name)
1.191     harris41 11683: 
                   11684: =item *
1.394     bowersj2 11685: X<idrget()>
                   11686: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11687: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11688: 
                   11689: =item *
1.394     bowersj2 11690: X<idput()>
                   11691: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11692: 
                   11693: =item *
1.394     bowersj2 11694: X<rolesinit()>
1.1169  ! droeschl 11695: B<rolesinit($udom,$username)>: get user privileges.
        !          11696: returns user role, first access and timer interval hashes
1.243     albertel 11697: 
                   11698: =item *
1.551     albertel 11699: X<getsection()>
                   11700: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11701: course $cname, return section name/number or '' for "not in course"
                   11702: and '-1' for "no section"
                   11703: 
                   11704: =item *
1.394     bowersj2 11705: X<userenvironment()>
                   11706: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11707: passed in @what from the requested user's environment, returns a hash
                   11708: 
1.858     raeburn  11709: =item * 
                   11710: X<userlog_query()>
1.859     albertel 11711: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11712: activity.log file. %filters defines filters applied when parsing the
                   11713: log file. These can be start or end timestamps, or the type of action
                   11714: - log to look for Login or Logout events, check for Checkin or
                   11715: Checkout, role for role selection. The response is in the form
                   11716: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11717: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11718: 
1.243     albertel 11719: =back
                   11720: 
                   11721: =head2 User Roles
                   11722: 
                   11723: =over 4
                   11724: 
                   11725: =item *
                   11726: 
1.810     raeburn  11727: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11728:  F: full access
                   11729:  U,I,K: authentication modes (cxx only)
                   11730:  '': forbidden
                   11731:  1: user needs to choose course
                   11732:  2: browse allowed
1.766     albertel 11733:  A: passphrase authentication needed
1.243     albertel 11734: 
                   11735: =item *
                   11736: 
                   11737: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11738: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11739: and course level
                   11740: 
                   11741: =item *
                   11742: 
1.988     raeburn  11743: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11744: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11745: $type is Course (default) or Community.
1.988     raeburn  11746: If $forcedefault evaluates to true, text returned will be default 
                   11747: text for $type. Otherwise, if this is a course, the text returned 
                   11748: will be a custom name for the role (if defined in the course's 
                   11749: environment).  If no custom name is defined the default is returned.
                   11750:    
1.832     raeburn  11751: =item *
                   11752: 
1.935     raeburn  11753: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11754: All arguments are optional. Returns a hash of a roles, either for
                   11755: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11756: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11757: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11758: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11759: For each key, value is set to colon-separated start and end times for
                   11760: the role.  If no username and domain are specified, will default to
1.934     raeburn  11761: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11762: of role statuses (active, future or previous), roles 
                   11763: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11764: to restrict the list of roles reported. If no array ref is 
                   11765: provided for types, will default to return only active roles.
1.834     albertel 11766: 
1.243     albertel 11767: =back
                   11768: 
                   11769: =head2 User Modification
                   11770: 
                   11771: =over 4
                   11772: 
                   11773: =item *
                   11774: 
1.957     raeburn  11775: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11776: user for the level given by URL.  Optional start and end dates (leave empty
                   11777: string or zero for "no date")
1.191     harris41 11778: 
                   11779: =item *
                   11780: 
1.243     albertel 11781: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11782: change a users, password, possible return values are: ok,
                   11783: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11784: refused
1.191     harris41 11785: 
                   11786: =item *
                   11787: 
1.243     albertel 11788: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11789: 
                   11790: =item *
                   11791: 
1.1058    raeburn  11792: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11793:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11794: 
                   11795: will update user information (firstname,middlename,lastname,generation,
                   11796: permanentemail), and if forceid is true, student/employee ID also.
                   11797: A user's institutional affiliation(s) can also be updated.
                   11798: User information fields will not be overwritten with empty entries 
                   11799: unless the field is included in the $candelete array reference.
                   11800: This array is included when a single user is modified via "Manage Users",
                   11801: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11802: 
                   11803: =item *
                   11804: 
1.286     matthew  11805: modifystudent
                   11806: 
1.957     raeburn  11807: modify a student's enrollment and identification information.
1.286     matthew  11808: The course id is resolved based on the current users environment.  
                   11809: This means the envoking user must be a course coordinator or otherwise
                   11810: associated with a course.
                   11811: 
1.297     matthew  11812: This call is essentially a wrapper for lonnet::modifyuser and
                   11813: lonnet::modify_student_enrollment
1.286     matthew  11814: 
                   11815: Inputs: 
                   11816: 
                   11817: =over 4
                   11818: 
1.957     raeburn  11819: =item B<$udom> Student's loncapa domain
1.286     matthew  11820: 
1.957     raeburn  11821: =item B<$uname> Student's loncapa login name
1.286     matthew  11822: 
1.964     bisitz   11823: =item B<$uid> Student/Employee ID
1.286     matthew  11824: 
1.957     raeburn  11825: =item B<$umode> Student's authentication mode
1.286     matthew  11826: 
1.957     raeburn  11827: =item B<$upass> Student's password
1.286     matthew  11828: 
1.957     raeburn  11829: =item B<$first> Student's first name
1.286     matthew  11830: 
1.957     raeburn  11831: =item B<$middle> Student's middle name
1.286     matthew  11832: 
1.957     raeburn  11833: =item B<$last> Student's last name
1.286     matthew  11834: 
1.957     raeburn  11835: =item B<$gene> Student's generation
1.286     matthew  11836: 
1.957     raeburn  11837: =item B<$usec> Student's section in course
1.286     matthew  11838: 
                   11839: =item B<$end> Unix time of the roles expiration
                   11840: 
                   11841: =item B<$start> Unix time of the roles start date
                   11842: 
                   11843: =item B<$forceid> If defined, allow $uid to be changed
                   11844: 
                   11845: =item B<$desiredhome> server to use as home server for student
                   11846: 
1.957     raeburn  11847: =item B<$email> Student's permanent e-mail address
                   11848: 
                   11849: =item B<$type> Type of enrollment (auto or manual)
                   11850: 
1.963     raeburn  11851: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11852: 
                   11853: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11854: 
1.963     raeburn  11855: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11856: 
1.963     raeburn  11857: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11858: 
1.963     raeburn  11859: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11860: 
1.286     matthew  11861: =back
1.297     matthew  11862: 
                   11863: =item *
                   11864: 
                   11865: modify_student_enrollment
                   11866: 
                   11867: Change a students enrollment status in a class.  The environment variable
                   11868: 'role.request.course' must be defined for this function to proceed.
                   11869: 
                   11870: Inputs:
                   11871: 
                   11872: =over 4
                   11873: 
                   11874: =item $udom, students domain
                   11875: 
                   11876: =item $uname, students name
                   11877: 
                   11878: =item $uid, students user id
                   11879: 
                   11880: =item $first, students first name
                   11881: 
                   11882: =item $middle
                   11883: 
                   11884: =item $last
                   11885: 
                   11886: =item $gene
                   11887: 
                   11888: =item $usec
                   11889: 
                   11890: =item $end
                   11891: 
                   11892: =item $start
                   11893: 
1.957     raeburn  11894: =item $type
                   11895: 
                   11896: =item $locktype
                   11897: 
                   11898: =item $cid
                   11899: 
                   11900: =item $selfenroll
                   11901: 
                   11902: =item $context
                   11903: 
1.297     matthew  11904: =back
                   11905: 
1.191     harris41 11906: 
                   11907: =item *
                   11908: 
1.243     albertel 11909: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11910: custom role; give a custom role to a user for the level given by URL.  Specify
                   11911: name and domain of role author, and role name
1.191     harris41 11912: 
                   11913: =item *
                   11914: 
1.243     albertel 11915: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11916: 
                   11917: =item *
                   11918: 
1.243     albertel 11919: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11920: 
                   11921: =back
                   11922: 
                   11923: =head2 Course Infomation
                   11924: 
                   11925: =over 4
1.191     harris41 11926: 
                   11927: =item *
                   11928: 
1.1118    foxr     11929: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11930: specified course id, including all environment settings for the
                   11931: course, the description of the course will be in the hash under the
                   11932: key 'description'
1.191     harris41 11933: 
1.1118    foxr     11934: $options is an optional parameter that if supplied is a hash reference that controls
                   11935: what how this function works.  It has the following key/values:
                   11936: 
                   11937: =over 4
                   11938: 
                   11939: =item freshen_cache
                   11940: 
                   11941: If defined, and the environment cache for the course is valid, it is 
                   11942: returned in the returned hash.
                   11943: 
                   11944: =item one_time
                   11945: 
                   11946: If defined, the last cache time is set to _now_
                   11947: 
                   11948: =item user
                   11949: 
                   11950: If defined, the supplied username is used instead of the current user.
                   11951: 
                   11952: 
                   11953: =back
                   11954: 
1.191     harris41 11955: =item *
                   11956: 
1.624     albertel 11957: resdata($name,$domain,$type,@which) : request for current parameter
                   11958: setting for a specific $type, where $type is either 'course' or 'user',
                   11959: @what should be a list of parameters to ask about. This routine caches
                   11960: answers for 5 minutes.
1.243     albertel 11961: 
1.877     foxr     11962: =item *
                   11963: 
                   11964: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11965: data base, returning a hash that is keyed by the resource name and has
                   11966: values that are the resource value.  I believe that the timestamps and
                   11967: versions are also returned.
                   11968: 
                   11969: 
1.243     albertel 11970: =back
                   11971: 
                   11972: =head2 Course Modification
                   11973: 
                   11974: =over 4
1.191     harris41 11975: 
                   11976: =item *
                   11977: 
1.243     albertel 11978: writecoursepref($courseid,%prefs) : write preferences (environment
                   11979: database) for a course
1.191     harris41 11980: 
                   11981: =item *
                   11982: 
1.1011    raeburn  11983: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11984: 
                   11985: =item *
                   11986: 
1.1038    raeburn  11987: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11988: 
1.1167    droeschl 11989: =item *
                   11990: 
                   11991: is_course($courseid), is_course($cdom, $cnum)
                   11992: 
                   11993: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   11994: two component version $cdom, $cnum. It checks if the specified course exists.
                   11995: 
                   11996: Returns:
                   11997:     undef if the course doesn't exist, otherwise
                   11998:     in scalar context the combined courseid.
                   11999:     in list context the two components of the course identifier, domain and 
                   12000:     courseid.    
                   12001: 
1.243     albertel 12002: =back
                   12003: 
                   12004: =head2 Resource Subroutines
                   12005: 
                   12006: =over 4
1.191     harris41 12007: 
                   12008: =item *
                   12009: 
1.243     albertel 12010: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12011: 
                   12012: =item *
                   12013: 
1.243     albertel 12014: repcopy($filename) : subscribes to the requested file, and attempts to
                   12015: replicate from the owning library server, Might return
1.607     raeburn  12016: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12017: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12018: resource. Expects the local filesystem pathname
                   12019: (/home/httpd/html/res/....)
                   12020: 
                   12021: =back
                   12022: 
                   12023: =head2 Resource Information
                   12024: 
                   12025: =over 4
1.191     harris41 12026: 
                   12027: =item *
                   12028: 
1.243     albertel 12029: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12030: a vairety of different possible values, $varname should be a request
                   12031: string, and the other parameters can be used to specify who and what
                   12032: one is asking about.
                   12033: 
                   12034: Possible values for $varname are environment.lastname (or other item
                   12035: from the envirnment hash), user.name (or someother aspect about the
                   12036: user), resource.0.maxtries (or some other part and parameter of a
                   12037: resource)
1.204     albertel 12038: 
                   12039: =item *
                   12040: 
1.243     albertel 12041: directcondval($number) : get current value of a condition; reads from a state
                   12042: string
1.204     albertel 12043: 
                   12044: =item *
                   12045: 
1.243     albertel 12046: condval($condidx) : value of condition index based on state
1.204     albertel 12047: 
                   12048: =item *
                   12049: 
1.243     albertel 12050: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12051: resource's metadata, $what should be either a specific key, or either
                   12052: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12053: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12054: 
                   12055: this function automatically caches all requests
1.191     harris41 12056: 
                   12057: =item *
                   12058: 
1.243     albertel 12059: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12060: network of library servers; returns file handle of where SQL and regex results
                   12061: will be stored for query
1.191     harris41 12062: 
                   12063: =item *
                   12064: 
1.243     albertel 12065: symbread($filename) : return symbolic list entry (filename argument optional);
                   12066: returns the data handle
1.191     harris41 12067: 
                   12068: =item *
                   12069: 
1.243     albertel 12070: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 12071: a possible symb for the URL in $thisfn, and if is an encryypted
                   12072: resource that the user accessed using /enc/ returns a 1 on success, 0
                   12073: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 12074: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 12075: 
1.191     harris41 12076: 
                   12077: =item *
                   12078: 
1.243     albertel 12079: symbclean($symb) : removes versions numbers from a symb, returns the
                   12080: cleaned symb
1.191     harris41 12081: 
                   12082: =item *
                   12083: 
1.243     albertel 12084: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12085: course map, user must be in a course for it to work.
1.191     harris41 12086: 
                   12087: =item *
                   12088: 
1.243     albertel 12089: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12090: 
                   12091: =item *
                   12092: 
1.243     albertel 12093: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12094: a random seed, all arguments are optional, if they aren't sent it uses the
                   12095: environment to derive them. Note: if symb isn't sent and it can't get one
                   12096: from &symbread it will use the current time as its return value
1.191     harris41 12097: 
                   12098: =item *
                   12099: 
1.243     albertel 12100: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12101: unfakeable, receipt
1.191     harris41 12102: 
                   12103: =item *
                   12104: 
1.620     albertel 12105: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12106: 
                   12107: =item *
                   12108: 
1.243     albertel 12109: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12110: 
                   12111: =item *
                   12112: 
1.243     albertel 12113: 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 12114: 
                   12115: =item *
                   12116: 
1.243     albertel 12117: 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 12118: 
                   12119: =item *
                   12120: 
1.243     albertel 12121: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12122: 
                   12123: =item *
                   12124: 
1.243     albertel 12125: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12126: forcing spreadsheet to reevaluate the resource scores next time.
                   12127: 
                   12128: =back
                   12129: 
                   12130: =head2 Storing/Retreiving Data
                   12131: 
                   12132: =over 4
1.191     harris41 12133: 
                   12134: =item *
                   12135: 
1.243     albertel 12136: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12137: for this url; hashref needs to be given and should be a \%hashname; the
                   12138: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12139: be derived from the env
1.191     harris41 12140: 
                   12141: =item *
                   12142: 
1.243     albertel 12143: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12144: uses critical subroutine
1.191     harris41 12145: 
                   12146: =item *
                   12147: 
1.243     albertel 12148: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12149: all args are optional
1.191     harris41 12150: 
                   12151: =item *
                   12152: 
1.717     albertel 12153: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12154: dumps the complete (or key matching regexp) namespace into a hash
                   12155: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12156: normally &store()ed into
                   12157: 
                   12158: $range should be either an integer '100' (give me the first 100
                   12159:                                            matching records)
                   12160:               or be  two integers sperated by a - with no spaces
                   12161:                  '30-50' (give me the 30th through the 50th matching
                   12162:                           records)
                   12163: 
                   12164: 
                   12165: =item *
                   12166: 
                   12167: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12168: replaces a &store() version of data with a replacement set of data
                   12169: for a particular resource in a namespace passed in the $storehash hash 
                   12170: reference
                   12171: 
                   12172: =item *
                   12173: 
1.243     albertel 12174: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12175: works very similar to store/cstore, but all data is stored in a
                   12176: temporary location and can be reset using tmpreset, $storehash should
                   12177: be a hash reference, returns nothing on success
1.191     harris41 12178: 
                   12179: =item *
                   12180: 
1.243     albertel 12181: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12182: similar to restore, but all data is stored in a temporary location and
                   12183: can be reset using tmpreset. Returns a hash of values on success,
                   12184: error string otherwise.
1.191     harris41 12185: 
                   12186: =item *
                   12187: 
1.243     albertel 12188: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12189: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12190: 
                   12191: =item *
                   12192: 
1.243     albertel 12193: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12194: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12195: 
                   12196: =item *
                   12197: 
1.243     albertel 12198: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12199: namesp ($udom and $uname are optional)
1.191     harris41 12200: 
                   12201: =item *
                   12202: 
1.702     albertel 12203: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12204: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12205: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12206: 
1.702     albertel 12207: $range should be either an integer '100' (give me the first 100
                   12208:                                            matching records)
                   12209:               or be  two integers sperated by a - with no spaces
                   12210:                  '30-50' (give me the 30th through the 50th matching
                   12211:                           records)
1.449     matthew  12212: =item *
                   12213: 
                   12214: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12215: $store can be a scalar, an array reference, or if the amount to be 
                   12216: incremented is > 1, a hash reference.
                   12217: 
                   12218: ($udom and $uname are optional)
1.191     harris41 12219: 
                   12220: =item *
                   12221: 
1.243     albertel 12222: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12223: ($udom and $uname are optional)
1.191     harris41 12224: 
                   12225: =item *
                   12226: 
1.243     albertel 12227: cput($namespace,$storehash,$udom,$uname) : critical put
                   12228: ($udom and $uname are optional)
1.191     harris41 12229: 
                   12230: =item *
                   12231: 
1.748     albertel 12232: newput($namespace,$storehash,$udom,$uname) :
                   12233: 
                   12234: Attempts to store the items in the $storehash, but only if they don't
                   12235: currently exist, if this succeeds you can be certain that you have 
                   12236: successfully created a new key value pair in the $namespace db.
                   12237: 
                   12238: 
                   12239: Args:
                   12240:  $namespace: name of database to store values to
                   12241:  $storehash: hashref to store to the db
                   12242:  $udom: (optional) domain of user containing the db
                   12243:  $uname: (optional) name of user caontaining the db
                   12244: 
                   12245: Returns:
                   12246:  'ok' -> succeeded in storing all keys of $storehash
                   12247:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12248:                         least <key> already existed in the db (other
                   12249:                         requested keys may also already exist)
1.967     bisitz   12250:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12251:  'con_lost' -> unable to contact request server
                   12252:  'refused' -> action was not allowed by remote machine
                   12253: 
                   12254: 
                   12255: =item *
                   12256: 
1.243     albertel 12257: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12258: reference filled in from namesp (encrypts the return communication)
                   12259: ($udom and $uname are optional)
1.191     harris41 12260: 
                   12261: =item *
                   12262: 
1.243     albertel 12263: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12264: critical subroutine
                   12265: 
1.806     raeburn  12266: =item *
                   12267: 
1.860     raeburn  12268: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12269: array reference filled in from namespace found in domain level on either
                   12270: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12271: 
                   12272: =item *
                   12273: 
1.860     raeburn  12274: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12275: domain level either on specified domain server ($uhome) or primary domain 
                   12276: server ($udom and $uhome are optional)
1.806     raeburn  12277: 
1.943     raeburn  12278: =item * 
                   12279: 
                   12280: get_domain_defaults($target_domain) : returns hash with defaults for
                   12281: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12282: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12283: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12284: Values are retrieved from cache (if current), or from domain's configuration.db
                   12285: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12286: or lonTabs/domain.tab. 
                   12287: 
                   12288: %domdefaults = &get_auth_defaults($target_domain);
                   12289: 
1.243     albertel 12290: =back
                   12291: 
                   12292: =head2 Network Status Functions
                   12293: 
                   12294: =over 4
1.191     harris41 12295: 
                   12296: =item *
                   12297: 
1.1137    raeburn  12298: dirlist() : return directory list based on URI (first arg).
                   12299: 
                   12300: Inputs: 1 required, 5 optional.
                   12301: 
                   12302: =over
                   12303: 
                   12304: =item 
                   12305: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12306: 
                   12307: =item
                   12308: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12309: 
                   12310: =item
                   12311: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12312: 
                   12313: =item
                   12314: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12315: 
                   12316: =item
                   12317: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12318: 
                   12319: =item 
                   12320: $alternateRoot - path to prepend in place of path from $uri.
                   12321: 
                   12322: =back
                   12323: 
                   12324: Returns: Array of up to two items.
                   12325: 
                   12326: =over
                   12327: 
                   12328: a reference to an array of files/subdirectories
                   12329: 
                   12330: =over
                   12331: 
                   12332: Each element in the array of files/subdirectories is a & separated list of
                   12333: item name and the result of running stat on the item.  If dirlist was requested
                   12334: for a file instead of a directory, the item name will be ''. For a directory 
                   12335: listing, if the item is a metadata file, the element will end &N&M 
                   12336: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12337: default copyright set (1).  
                   12338: 
                   12339: =back
                   12340: 
                   12341: a scalar containing error condition (if encountered).
                   12342: 
                   12343: =over
                   12344: 
                   12345: =item 
                   12346: no_host (no homeserver identified for $username:$domain).
                   12347: 
                   12348: =item 
                   12349: no_such_host (server contacted for listing not identified as valid host).
                   12350: 
                   12351: =item 
                   12352: con_lost (connection to remote server failed).
                   12353: 
                   12354: =item 
                   12355: refused (invalid $username:$domain received on lond side).
                   12356: 
                   12357: =item 
                   12358: no_such_dir (directory at specified path on lond side does not exist). 
                   12359: 
                   12360: =item 
                   12361: empty (directory at specified path on lond side is empty).
                   12362: 
                   12363: =over
                   12364: 
                   12365: This is currently not encountered because the &ls3, &ls2, 
                   12366: &ls (_handler) routines on the lond side do not filter out
                   12367: . and .. from a directory listing. 
                   12368: 
                   12369: =back
                   12370: 
                   12371: =back
                   12372: 
                   12373: =back
1.191     harris41 12374: 
                   12375: =item *
                   12376: 
1.243     albertel 12377: spareserver() : find server with least workload from spare.tab
                   12378: 
1.986     foxr     12379: 
                   12380: =item *
                   12381: 
                   12382: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12383: if there is no corresponding loncapa host.
                   12384: 
1.243     albertel 12385: =back
                   12386: 
1.986     foxr     12387: 
1.243     albertel 12388: =head2 Apache Request
                   12389: 
                   12390: =over 4
1.191     harris41 12391: 
                   12392: =item *
                   12393: 
1.243     albertel 12394: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12395: localhost, posts hash
                   12396: 
                   12397: =back
                   12398: 
                   12399: =head2 Data to String to Data
                   12400: 
                   12401: =over 4
1.191     harris41 12402: 
                   12403: =item *
                   12404: 
1.243     albertel 12405: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12406: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12407: 
                   12408: =item *
                   12409: 
1.243     albertel 12410: hashref2str($hashref) : convert a hashref into a string complete with
                   12411: escaping and '=' and '&' separators, supports elements that are
                   12412: arrayrefs and hashrefs
1.191     harris41 12413: 
                   12414: =item *
                   12415: 
1.243     albertel 12416: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12417: with escaping and '&' separators, supports elements that are arrayrefs
                   12418: and hashrefs
1.191     harris41 12419: 
                   12420: =item *
                   12421: 
1.243     albertel 12422: str2hash($string) : convert string to hash using unescaping and
                   12423: splitting on '=' and '&', supports elements that are arrayrefs and
                   12424: hashrefs
1.191     harris41 12425: 
                   12426: =item *
                   12427: 
1.243     albertel 12428: str2array($string) : convert string to hash using unescaping and
                   12429: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12430: 
                   12431: =back
                   12432: 
                   12433: =head2 Logging Routines
                   12434: 
                   12435: 
                   12436: These routines allow one to make log messages in the lonnet.log and
                   12437: lonnet.perm logfiles.
1.191     harris41 12438: 
1.1119    foxr     12439: =over 4
                   12440: 
1.191     harris41 12441: =item *
                   12442: 
1.243     albertel 12443: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12444: 
                   12445: =item *
                   12446: 
1.243     albertel 12447: logthis() : append message to the normal lonnet.log file, it gets
                   12448: preiodically rolled over and deleted.
1.191     harris41 12449: 
                   12450: =item *
                   12451: 
1.243     albertel 12452: logperm() : append a permanent message to lonnet.perm.log, this log
                   12453: file never gets deleted by any automated portion of the system, only
                   12454: messages of critical importance should go in here.
                   12455: 
1.1119    foxr     12456: 
1.243     albertel 12457: =back
                   12458: 
                   12459: =head2 General File Helper Routines
                   12460: 
                   12461: =over 4
1.191     harris41 12462: 
                   12463: =item *
                   12464: 
1.481     raeburn  12465: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12466: (a) files in /uploaded
                   12467:   (i) If a local copy of the file exists - 
                   12468:       compares modification date of local copy with last-modified date for 
                   12469:       definitive version stored on home server for course. If local copy is 
                   12470:       stale, requests a new version from the home server and stores it. 
                   12471:       If the original has been removed from the home server, then local copy 
                   12472:       is unlinked.
                   12473:   (ii) If local copy does not exist -
                   12474:       requests the file from the home server and stores it. 
                   12475:   
                   12476:   If $caller is 'uploadrep':  
                   12477:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12478:     for request for files originally uploaded via DOCS. 
                   12479:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12480:   
                   12481:   Otherwise:
                   12482:      This indicates a call from the content generation phase of the request.
                   12483:      -  returns the entire contents of the file or -1.
                   12484:      
                   12485: (b) files in /res
                   12486:    - returns the entire contents of a file or -1; 
                   12487:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12488: 
1.712     albertel 12489: 
                   12490: =item *
                   12491: 
                   12492: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12493:                   reference
                   12494: 
                   12495: returns either a stat() list of data about the file or an empty list
                   12496: if the file doesn't exist or couldn't find out about it (connection
                   12497: problems or user unknown)
                   12498: 
1.191     harris41 12499: =item *
                   12500: 
1.243     albertel 12501: filelocation($dir,$file) : returns file system location of a file
                   12502: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12503: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12504: and a file of ../bob will become /a/bob)
1.191     harris41 12505: 
                   12506: =item *
                   12507: 
                   12508: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12509: filelocation except for hrefs
                   12510: 
                   12511: =item *
                   12512: 
                   12513: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12514: 
1.243     albertel 12515: =back
                   12516: 
1.608     albertel 12517: =head2 Usererfile file routines (/uploaded*)
                   12518: 
                   12519: =over 4
                   12520: 
                   12521: =item *
                   12522: 
                   12523: userfileupload(): main rotine for putting a file in a user or course's
                   12524:                   filespace, arguments are,
                   12525: 
1.620     albertel 12526:  formname - required - this is the name of the element in $env where the
1.608     albertel 12527:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12528:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12529:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12530:  context - if coursedoc, store the file in the course of the active role
                   12531:              of the current user; 
                   12532:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12533:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12534:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12535:          if undefined, it will be placed in "unknown"
                   12536: 
                   12537:  (This routine calls clean_filename() to remove any dangerous
                   12538:  characters from the filename, and then calls finuserfileupload() to
                   12539:  complete the transaction)
                   12540: 
                   12541:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12542:  and /adm/notfound.html if unsuccessful
                   12543: 
                   12544: =item *
                   12545: 
                   12546: clean_filename(): routine for cleaing a filename up for storage in
                   12547:                  userfile space, argument is:
                   12548: 
                   12549:  filename - proposed filename
                   12550: 
                   12551: returns: the new clean filename
                   12552: 
                   12553: =item *
                   12554: 
1.1090    raeburn  12555: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12556: userspace, probably shouldn't be called directly
                   12557: 
                   12558:   docuname: username or courseid of destination for the file
                   12559:   docudom: domain of user/course of destination for the file
                   12560:   formname: same as for userfileupload()
1.1090    raeburn  12561:   fname: filename (including subdirectories) for the file
                   12562:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12563:   allfiles: reference to hash used to store objects found by parser
                   12564:   codebase: reference to hash used for codebases of java objects found by parser
                   12565:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12566:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12567:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12568:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12569:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12570:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12571:   mimetype: reference to scalar to accommodate mime type determined
                   12572:             from File::MMagic if $parser = parse.
1.608     albertel 12573: 
                   12574:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12575:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12576:  was 'overwrite').
                   12577:  
1.608     albertel 12578: 
                   12579: =item *
                   12580: 
                   12581: renameuserfile(): renames an existing userfile to a new name
                   12582: 
                   12583:   Args:
                   12584:    docuname: username or courseid of destination for the file
                   12585:    docudom: domain of user/course of destination for the file
                   12586:    old: current file name (including any subdirs under userfiles)
                   12587:    new: desired file name (including any subdirs under userfiles)
                   12588: 
                   12589: =item *
                   12590: 
                   12591: mkdiruserfile(): creates a directory is a userfiles dir
                   12592: 
                   12593:   Args:
                   12594:    docuname: username or courseid of destination for the file
                   12595:    docudom: domain of user/course of destination for the file
                   12596:    dir: dir to create (including any subdirs under userfiles)
                   12597: 
                   12598: =item *
                   12599: 
                   12600: removeuserfile(): removes a file that exists in userfiles
                   12601: 
                   12602:   Args:
                   12603:    docuname: username or courseid of destination for the file
                   12604:    docudom: domain of user/course of destination for the file
                   12605:    fname: filname to delete (including any subdirs under userfiles)
                   12606: 
                   12607: =item *
                   12608: 
                   12609: removeuploadedurl(): convience function for removeuserfile()
                   12610: 
                   12611:   Args:
                   12612:    url:  a full /uploaded/... url to delete
                   12613: 
1.747     albertel 12614: =item * 
                   12615: 
                   12616: get_portfile_permissions():
                   12617:   Args:
                   12618:     domain: domain of user or course contain the portfolio files
                   12619:     user: name of user or num of course contain the portfolio files
                   12620:   Returns:
                   12621:     hashref of a dump of the proper file_permissions.db
                   12622:    
                   12623: 
                   12624: =item * 
                   12625: 
                   12626: get_access_controls():
                   12627: 
                   12628: Args:
                   12629:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12630:   group: (optional) the group you want the files associated with
                   12631:   file: (optional) the file you want access info on
                   12632: 
                   12633: Returns:
1.749     raeburn  12634:     a hash (keys are file names) of hashes containing
                   12635:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12636:         values are XML containing access control settings (see below) 
1.747     albertel 12637: 
                   12638: Internal notes:
                   12639: 
1.749     raeburn  12640:  access controls are stored in file_permissions.db as key=value pairs.
                   12641:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12642:         where scope -> public,guest,course,group,domains or users.
                   12643:               end -> UNIX time for end of access (0 -> no end date)
                   12644:               start -> UNIX time for start of access
                   12645: 
                   12646:     value -> XML description of access control
                   12647:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12648:             <start></start>
                   12649:             <end></end>
                   12650: 
                   12651:             <password></password>  for scope type = guest
                   12652: 
                   12653:             <domain></domain>     for scope type = course or group
                   12654:             <number></number>
                   12655:             <roles id="">
                   12656:              <role></role>
                   12657:              <access></access>
                   12658:              <section></section>
                   12659:              <group></group>
                   12660:             </roles>
                   12661: 
                   12662:             <dom></dom>         for scope type = domains
                   12663: 
                   12664:             <users>             for scope type = users
                   12665:              <user>
                   12666:               <uname></uname>
                   12667:               <udom></udom>
                   12668:              </user>
                   12669:             </users>
                   12670:            </scope> 
                   12671:               
                   12672:  Access data is also aggregated for each file in an additional key=value pair:
                   12673:  key -> path to file/file_name\0accesscontrol 
                   12674:  value -> reference to hash
                   12675:           hash contains key = value pairs
                   12676:           where key = uniqueID:scope_end_start
                   12677:                 value = UNIX time record was last updated
                   12678: 
                   12679:           Used to improve speed of look-ups of access controls for each file.  
                   12680:  
                   12681:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12682: 
                   12683: modify_access_controls():
                   12684: 
                   12685: Modifies access controls for a portfolio file
                   12686: Args
                   12687: 1. file name
                   12688: 2. reference to hash of required changes,
                   12689: 3. domain
                   12690: 4. username
                   12691:   where domain,username are the domain of the portfolio owner 
                   12692:   (either a user or a course) 
                   12693: 
                   12694: Returns:
                   12695: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12696: 2. result of deletions ('ok' or 'error', with error message).
                   12697: 3. reference to hash of any new or updated access controls.
                   12698: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12699:    key = integer (inbound ID)
                   12700:    value = uniqueID  
1.747     albertel 12701: 
1.608     albertel 12702: =back
                   12703: 
1.243     albertel 12704: =head2 HTTP Helper Routines
                   12705: 
                   12706: =over 4
                   12707: 
1.191     harris41 12708: =item *
                   12709: 
                   12710: escape() : unpack non-word characters into CGI-compatible hex codes
                   12711: 
                   12712: =item *
                   12713: 
                   12714: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12715: 
1.243     albertel 12716: =back
                   12717: 
                   12718: =head1 PRIVATE SUBROUTINES
                   12719: 
                   12720: =head2 Underlying communication routines (Shouldn't call)
                   12721: 
                   12722: =over 4
                   12723: 
                   12724: =item *
                   12725: 
                   12726: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12727: 
                   12728: =item *
                   12729: 
                   12730: reply() : uses subreply to send a message to remote machine, logs all failures
                   12731: 
                   12732: =item *
                   12733: 
                   12734: critical() : passes a critical message to another server; if cannot
                   12735: get through then place message in connection buffer directory and
                   12736: returns con_delayed, if incapable of saving message, returns
                   12737: con_failed
                   12738: 
                   12739: =item *
                   12740: 
                   12741: reconlonc() : tries to reconnect lonc client processes.
                   12742: 
                   12743: =back
                   12744: 
                   12745: =head2 Resource Access Logging
                   12746: 
                   12747: =over 4
                   12748: 
                   12749: =item *
                   12750: 
                   12751: flushcourselogs() : flush (save) buffer logs and access logs
                   12752: 
                   12753: =item *
                   12754: 
                   12755: courselog($what) : save message for course in hash
                   12756: 
                   12757: =item *
                   12758: 
                   12759: courseacclog($what) : save message for course using &courselog().  Perform
                   12760: special processing for specific resource types (problems, exams, quizzes, etc).
                   12761: 
1.191     harris41 12762: =item *
                   12763: 
                   12764: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12765: as a PerlChildExitHandler
1.243     albertel 12766: 
                   12767: =back
                   12768: 
                   12769: =head2 Other
                   12770: 
                   12771: =over 4
                   12772: 
                   12773: =item *
                   12774: 
                   12775: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12776: 
                   12777: =back
                   12778: 
                   12779: =cut
1.877     foxr     12780: 

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