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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1264  ! raeburn     4: # $Id: lonnet.pm,v 1.1263 2014/06/25 00:55:26 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.539     albertel   95: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.550     foxr      108: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.993     raeburn   232: sub get_server_loncaparev {
1.1073    raeburn   233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   234:     if (defined($lonhost)) {
                    235:         if (!defined(&hostname($lonhost))) {
                    236:             undef($lonhost);
                    237:         }
                    238:     }
                    239:     if (!defined($lonhost)) {
                    240:         if (defined(&domain($dom,'primary'))) {
                    241:             $lonhost=&domain($dom,'primary');
                    242:             if ($lonhost eq 'no_host') {
                    243:                 undef($lonhost);
                    244:             }
                    245:         }
                    246:     }
                    247:     if (defined($lonhost)) {
1.1073    raeburn   248:         my $cachetime = 12*3600;
                    249:         if (!$ignore_cache) {
                    250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    251:             if (defined($cached)) {
                    252:                 return $loncaparev;
                    253:             }
                    254:         }
                    255:         my ($answer,$loncaparev);
                    256:         my @ids=&current_machine_ids();
                    257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    258:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   260:                 $loncaparev = $1;
                    261:             }
                    262:         } else {
                    263:             $answer = &reply('serverloncaparev',$lonhost);
                    264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    265:                 if ($caller eq 'loncron') {
                    266:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   267:                     $ua->timeout(4);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
                    270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1241    raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364:     return $response;
                    365: }
                    366: 
1.1       albertel  367: # -------------------------------------------------- Non-critical communication
                    368: sub subreply {
                    369:     my ($cmd,$server)=@_;
1.838     albertel  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      371:     #
                    372:     #  With loncnew process trimming, there's a timing hole between lonc server
                    373:     #  process exit and the master server picking up the listen on the AF_UNIX
                    374:     #  socket.  In that time interval, a lock file will exist:
                    375: 
                    376:     my $lockfile=$peerfile.".lock";
                    377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    378: 	sleep(1);
                    379:     }
                    380:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      381:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      382:     #
1.550     foxr      383:     #   We'll give the connection a few tries before abandoning it.  If
                    384:     #   connection is not possible, we'll con_lost back to the client.
                    385:     #   
                    386:     my $client;
                    387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    389: 				      Type    => SOCK_STREAM,
                    390: 				      Timeout => 10);
1.869     albertel  391: 	if ($client) {
1.550     foxr      392: 	    last;		# Connected!
1.850     albertel  393: 	} else {
1.853     albertel  394: 	    &create_connection(&hostname($server),$server);
1.550     foxr      395: 	}
1.850     albertel  396:         sleep(1);		# Try again later if failed connection.
1.550     foxr      397:     }
                    398:     my $answer;
                    399:     if ($client) {
1.704     albertel  400: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      401: 	$answer=<$client>;
                    402: 	if (!$answer) { $answer="con_lost"; }
                    403: 	chomp($answer);
                    404:     } else {
                    405: 	$answer = 'con_lost';	# Failed connection.
                    406:     }
1.1       albertel  407:     return $answer;
                    408: }
                    409: 
                    410: sub reply {
                    411:     my ($cmd,$server)=@_;
1.838     albertel  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  413:     my $answer=subreply($cmd,$server);
1.65      www       414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  415:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       416:                 " $cmd to $server returned $answer</font>");
                    417:     }
1.1       albertel  418:     return $answer;
                    419: }
                    420: 
                    421: # ----------------------------------------------------------- Send USR1 to lonc
                    422: 
                    423: sub reconlonc {
1.891     albertel  424:     my ($lonid) = @_;
                    425:     my $hostname = &hostname($lonid);
                    426:     if ($lonid) {
                    427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    428: 	if ($hostname && -e $peerfile) {
                    429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    431: 					     Type    => SOCK_STREAM,
                    432: 					     Timeout => 10);
                    433: 	    if ($client) {
                    434: 		print $client ("reset_retries\n");
                    435: 		my $answer=<$client>;
                    436: 		#reset just this one.
                    437: 	    }
                    438: 	}
                    439: 	return;
                    440:     }
                    441: 
1.836     www       442:     &logthis("Trying to reconnect lonc");
1.1       albertel  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  444:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  445: 	my $loncpid=<$fh>;
                    446:         chomp($loncpid);
                    447:         if (kill 0 => $loncpid) {
                    448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    449:             kill USR1 => $loncpid;
                    450:             sleep 1;
1.836     www       451:          } else {
1.12      www       452: 	    &logthis(
1.672     albertel  453:                "<font color=\"blue\">WARNING:".
1.12      www       454:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  455:         }
                    456:     } else {
1.836     www       457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  458:     }
                    459: }
                    460: 
                    461: # ------------------------------------------------------ Critical communication
1.12      www       462: 
1.1       albertel  463: sub critical {
                    464:     my ($cmd,$server)=@_;
1.838     albertel  465:     unless (&hostname($server)) {
1.672     albertel  466:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       467:                " Critical message to unknown server ($server)</font>");
                    468:         return 'no_such_host';
                    469:     }
1.1       albertel  470:     my $answer=reply($cmd,$server);
                    471:     if ($answer eq 'con_lost') {
                    472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  473: 	my $answer=reply($cmd,$server);
1.1       albertel  474:         if ($answer eq 'con_lost') {
                    475:             my $now=time;
                    476:             my $middlename=$cmd;
1.5       www       477:             $middlename=substr($middlename,0,16);
1.1       albertel  478:             $middlename=~s/\W//g;
                    479:             my $dfilename=
1.305     www       480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    481:             $dumpcount++;
1.1       albertel  482:             {
1.448     albertel  483: 		my $dfh;
                    484: 		if (open($dfh,">$dfilename")) {
                    485: 		    print $dfh "$cmd\n"; 
                    486: 		    close($dfh);
                    487: 		}
1.1       albertel  488:             }
                    489:             sleep 2;
                    490:             my $wcmd='';
                    491:             {
1.448     albertel  492: 		my $dfh;
                    493: 		if (open($dfh,"<$dfilename")) {
                    494: 		    $wcmd=<$dfh>; 
                    495: 		    close($dfh);
                    496: 		}
1.1       albertel  497:             }
                    498:             chomp($wcmd);
1.7       www       499:             if ($wcmd eq $cmd) {
1.672     albertel  500: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       501:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  502:                 &logperm("D:$server:$cmd");
                    503: 	        return 'con_delayed';
                    504:             } else {
1.672     albertel  505:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       506:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  507:                 &logperm("F:$server:$cmd");
                    508:                 return 'con_failed';
                    509:             }
                    510:         }
                    511:     }
                    512:     return $answer;
1.405     albertel  513: }
                    514: 
1.755     albertel  515: # ------------------------------------------- check if return value is an error
                    516: 
                    517: sub error {
                    518:     my ($result) = @_;
1.756     albertel  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  520: 	if ($2 == 2) { return undef; }
                    521: 	return $1;
                    522:     }
                    523:     return undef;
                    524: }
                    525: 
1.783     albertel  526: sub convert_and_load_session_env {
                    527:     my ($lonidsdir,$handle)=@_;
                    528:     my @profile;
                    529:     {
1.917     albertel  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    531: 	if (!$opened) {
1.915     albertel  532: 	    return 0;
                    533: 	}
1.783     albertel  534: 	flock($idf,LOCK_SH);
                    535: 	@profile=<$idf>;
                    536: 	close($idf);
                    537:     }
                    538:     my %temp_env;
                    539:     foreach my $line (@profile) {
1.786     albertel  540: 	if ($line !~ m/=/) {
                    541: 	    return 0;
                    542: 	}
1.783     albertel  543: 	chomp($line);
                    544: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    546:     }
                    547:     unlink("$lonidsdir/$handle.id");
                    548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    549: 	    0640)) {
                    550: 	%disk_env = %temp_env;
                    551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    552: 	untie(%disk_env);
                    553:     }
1.786     albertel  554:     return 1;
1.783     albertel  555: }
                    556: 
1.374     www       557: # ------------------------------------------- Transfer profile into environment
1.780     albertel  558: my $env_loaded;
                    559: sub transfer_profile_to_env {
1.788     albertel  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    561:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       562: 
1.720     albertel  563:     if (!defined($lonidsdir)) {
                    564: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    565:     }
                    566:     if (!defined($handle)) {
                    567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    568:     }
                    569: 
1.786     albertel  570:     my $convert;
                    571:     {
1.917     albertel  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    573: 	if (!$opened) {
1.915     albertel  574: 	    return;
                    575: 	}
1.786     albertel  576: 	flock($idf,LOCK_SH);
                    577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    578: 		&GDBM_READER(),0640)) {
                    579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    580: 	    untie(%disk_env);
                    581: 	} else {
                    582: 	    $convert = 1;
                    583: 	}
                    584:     }
                    585:     if ($convert) {
                    586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    587: 	    &logthis("Failed to load session, or convert session.");
                    588: 	}
1.374     www       589:     }
1.783     albertel  590: 
1.786     albertel  591:     my %remove;
1.783     albertel  592:     while ( my $envname = each(%env) ) {
1.433     matthew   593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    594:             if ($time < time-300) {
1.783     albertel  595:                 $remove{$key}++;
1.433     matthew   596:             }
                    597:         }
                    598:     }
1.783     albertel  599: 
1.619     albertel  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  601:     $env_loaded=1;
1.783     albertel  602:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   603:         &delenv($expired_key);
1.374     www       604:     }
1.1       albertel  605: }
                    606: 
1.916     albertel  607: # ---------------------------------------------------- Check for valid session 
                    608: sub check_for_valid_session {
1.1245    raeburn   609:     my ($r,$name,$userhashref) = @_;
1.916     albertel  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   611:     if ($name eq '') {
                    612:         $name = 'lonID';
                    613:     }
                    614:     my $lonid=$cookies{$name};
1.916     albertel  615:     return undef if (!$lonid);
                    616: 
                    617:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   618:     my $lonidsdir;
                    619:     if ($name eq 'lonDAV') {
                    620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    621:     } else {
                    622:         $lonidsdir=$r->dir_config('lonIDsDir');
                    623:     }
1.916     albertel  624:     return undef if (!-e "$lonidsdir/$handle.id");
                    625: 
1.917     albertel  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    627:     return undef if (!$opened);
1.916     albertel  628: 
                    629:     flock($idf,LOCK_SH);
                    630:     my %disk_env;
                    631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    632: 	    &GDBM_READER(),0640)) {
                    633: 	return undef;	
                    634:     }
                    635: 
                    636:     if (!defined($disk_env{'user.name'})
                    637: 	|| !defined($disk_env{'user.domain'})) {
                    638: 	return undef;
                    639:     }
1.1245    raeburn   640: 
                    641:     if (ref($userhashref) eq 'HASH') {
                    642:         $userhashref->{'name'} = $disk_env{'user.name'};
                    643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   644:     }
1.1245    raeburn   645: 
1.916     albertel  646:     return $handle;
                    647: }
                    648: 
1.830     albertel  649: sub timed_flock {
                    650:     my ($file,$lock_type) = @_;
                    651:     my $failed=0;
                    652:     eval {
                    653: 	local $SIG{__DIE__}='DEFAULT';
                    654: 	local $SIG{ALRM}=sub {
                    655: 	    $failed=1;
                    656: 	    die("failed lock");
                    657: 	};
                    658: 	alarm(13);
                    659: 	flock($file,$lock_type);
                    660: 	alarm(0);
                    661:     };
                    662:     if ($failed) {
                    663: 	return undef;
                    664:     } else {
                    665: 	return 1;
                    666:     }
                    667: }
                    668: 
1.5       www       669: # ---------------------------------------------------------- Append Environment
                    670: 
                    671: sub appenv {
1.949     raeburn   672:     my ($newenv,$roles) = @_;
                    673:     if (ref($newenv) eq 'HASH') {
                    674:         foreach my $key (keys(%{$newenv})) {
                    675:             my $refused = 0;
                    676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    677:                 $refused = 1;
                    678:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    681:                         $refused = 0;
                    682:                     }
                    683:                 }
                    684:             }
                    685:             if ($refused) {
                    686:                 &logthis("<font color=\"blue\">WARNING: ".
                    687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    688:                          .'</font>');
                    689: 	        delete($newenv->{$key});
                    690:             } else {
                    691:                 $env{$key}=$newenv->{$key};
                    692:             }
                    693:         }
                    694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    695:         if ($opened
                    696: 	    && &timed_flock($env_file,LOCK_EX)
                    697: 	    &&
                    698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    700: 	    while (my ($key,$value) = each(%{$newenv})) {
                    701: 	        $disk_env{$key} = $value;
                    702: 	    }
                    703: 	    untie(%disk_env);
1.35      www       704:         }
1.191     harris41  705:     }
1.56      www       706:     return 'ok';
                    707: }
                    708: # ----------------------------------------------------- Delete from Environment
                    709: 
                    710: sub delenv {
1.1104    raeburn   711:     my ($delthis,$regexp,$roles) = @_;
                    712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    713:         my $refused = 1;
                    714:         if (ref($roles) eq 'ARRAY') {
                    715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    716:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    717:                 $refused = 0;
                    718:             }
                    719:         }
                    720:         if ($refused) {
                    721:             &logthis("<font color=\"blue\">WARNING: ".
                    722:                      "Attempt to delete from environment ".$delthis);
                    723:             return 'error';
                    724:         }
1.56      www       725:     }
1.917     albertel  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    727:     if ($opened
1.915     albertel  728: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  729: 	&&
                    730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  732: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   733: 	    if ($regexp) {
                    734:                 if ($key=~/^$delthis/) {
                    735:                     delete($env{$key});
                    736:                     delete($disk_env{$key});
                    737:                 } 
                    738:             } else {
                    739:                 if ($key=~/^\Q$delthis\E/) {
                    740: 		    delete($env{$key});
                    741: 		    delete($disk_env{$key});
                    742: 	        }
                    743:             }
1.448     albertel  744: 	}
1.783     albertel  745: 	untie(%disk_env);
1.5       www       746:     }
                    747:     return 'ok';
1.369     albertel  748: }
                    749: 
1.790     albertel  750: sub get_env_multiple {
                    751:     my ($name) = @_;
                    752:     my @values;
                    753:     if (defined($env{$name})) {
                    754:         # exists is it an array
                    755:         if (ref($env{$name})) {
                    756:             @values=@{ $env{$name} };
                    757:         } else {
                    758:             $values[0]=$env{$name};
                    759:         }
                    760:     }
                    761:     return(@values);
                    762: }
                    763: 
1.958     www       764: # ------------------------------------------------------------------- Locking
                    765: 
                    766: sub set_lock {
                    767:     my ($text)=@_;
                    768:     $locknum++;
                    769:     my $id=$$.'-'.$locknum;
                    770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    771:              'session.lock.'.$id => $text});
                    772:     return $id;
                    773: }
                    774: 
                    775: sub get_locks {
                    776:     my $num=0;
                    777:     my %texts=();
                    778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    779:        if ($lock=~/\w/) {
                    780:           $num++;
                    781:           $texts{$lock}=$env{'session.lock.'.$lock};
                    782:        }
                    783:    }
                    784:    return ($num,%texts);
                    785: }
                    786: 
                    787: sub remove_lock {
                    788:     my ($id)=@_;
                    789:     my $newlocks='';
                    790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    791:        if (($lock=~/\w/) && ($lock ne $id)) {
                    792:           $newlocks.=','.$lock;
                    793:        }
                    794:     }
                    795:     &appenv({'session.locks' => $newlocks});
                    796:     &delenv('session.lock.'.$id);
                    797: }
                    798: 
                    799: sub remove_all_locks {
                    800:     my $activelocks=$env{'session.locks'};
                    801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    802:        if ($lock=~/\w/) {
                    803:           &remove_lock($lock);
                    804:        }
                    805:     }
                    806: }
                    807: 
                    808: 
1.369     albertel  809: # ------------------------------------------ Find out current server userload
                    810: sub userload {
                    811:     my $numusers=0;
                    812:     {
                    813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    814: 	my $filename;
                    815: 	my $curtime=time;
                    816: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  817: 	    next if ($filename eq '.' || $filename eq '..');
                    818: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  821: 	}
                    822: 	closedir(LONIDS);
                    823:     }
                    824:     my $userloadpercent=0;
                    825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    826:     if ($maxuserload) {
1.371     albertel  827: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  828:     }
1.372     albertel  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  830:     return $userloadpercent;
1.283     www       831: }
                    832: 
1.1       albertel  833: # ------------------------------ Find server with least workload from spare.tab
1.11      www       834: 
1.1       albertel  835: sub spareserver {
1.1083    raeburn   836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  837:     my $spare_server;
1.370     albertel  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    840:                                                      :  $userloadpercent;
1.1083    raeburn   841:     my ($uint_dom,$remotesessions);
                    842:     if (($udom ne '') && (&domain($udom) ne '')) {
                    843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    846:         $remotesessions = $udomdefaults{'remotesessions'};
                    847:     }
1.1123    raeburn   848:     my $spareshash = &this_host_spares($udom);
                    849:     if (ref($spareshash) eq 'HASH') {
                    850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    852:                 if ($uint_dom) {
                    853:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    854:                                                  $try_server));
                    855:                 }
                    856: 	        ($spare_server, $lowest_load) =
                    857: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    858:             }
1.1083    raeburn   859:         }
1.784     albertel  860: 
1.1123    raeburn   861:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    862: 
                    863:         if (!$found_server) {
                    864:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    865: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    866:                     if ($uint_dom) {
                    867:                         next unless (&spare_can_host($udom,$uint_dom,
                    868:                                                      $remotesessions,$try_server));
                    869:                     }
                    870: 	            ($spare_server, $lowest_load) =
                    871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    872:                 }
                    873: 	    }
                    874:         }
1.784     albertel  875:     }
                    876: 
                    877:     if (!$want_server_name) {
1.968     raeburn   878:         my $protocol = 'http';
                    879:         if ($protocol{$spare_server} eq 'https') {
                    880:             $protocol = $protocol{$spare_server};
                    881:         }
1.1001    raeburn   882:         if (defined($spare_server)) {
                    883:             my $hostname = &hostname($spare_server);
1.1083    raeburn   884:             if (defined($hostname)) {
1.1001    raeburn   885: 	        $spare_server = $protocol.'://'.$hostname;
                    886:             }
                    887:         }
1.784     albertel  888:     }
                    889:     return $spare_server;
                    890: }
                    891: 
                    892: sub compare_server_load {
1.1253    raeburn   893:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    894: 
                    895:     if ($required) {
                    896:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    897:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    898:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    899:         if (($major eq '' && $minor eq '') ||
                    900:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    901:             return ($spare_server,$lowest_load);
                    902:         }
                    903:     }
1.784     albertel  904: 
                    905:     my $loadans     = &reply('load',    $try_server);
                    906:     my $userloadans = &reply('userload',$try_server);
                    907: 
                    908:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   909: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  910:     }
                    911: 
                    912:     my $load;
                    913:     if ($loadans =~ /\d/) {
                    914: 	if ($userloadans =~ /\d/) {
                    915: 	    #both are numbers, pick the bigger one
                    916: 	    $load = ($loadans > $userloadans) ? $loadans 
                    917: 		                              : $userloadans;
1.411     albertel  918: 	} else {
1.784     albertel  919: 	    $load = $loadans;
1.411     albertel  920: 	}
1.784     albertel  921:     } else {
                    922: 	$load = $userloadans;
                    923:     }
                    924: 
                    925:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    926: 	$spare_server = $try_server;
                    927: 	$lowest_load  = $load;
1.370     albertel  928:     }
1.784     albertel  929:     return ($spare_server,$lowest_load);
1.202     matthew   930: }
1.914     albertel  931: 
                    932: # --------------------------- ask offload servers if user already has a session
                    933: sub find_existing_session {
                    934:     my ($udom,$uname) = @_;
1.1123    raeburn   935:     my $spareshash = &this_host_spares($udom);
                    936:     if (ref($spareshash) eq 'HASH') {
                    937:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    938:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    940:             }
                    941:         }
                    942:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    943:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    944:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    945:             }
                    946:         }
1.914     albertel  947:     }
                    948:     return;
                    949: }
                    950: 
                    951: # -------------------------------- ask if server already has a session for user
                    952: sub has_user_session {
                    953:     my ($lonid,$udom,$uname) = @_;
                    954:     my $result = &reply(join(':','userhassession',
                    955: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    956:     return 1 if ($result eq 'ok');
                    957: 
                    958:     return 0;
                    959: }
                    960: 
1.1076    raeburn   961: # --------- determine least loaded server in a user's domain which allows login
                    962: 
                    963: sub choose_server {
1.1259    raeburn   964:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   965:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   966:     my %servers = &get_servers($udom);
1.1076    raeburn   967:     my $lowest_load = 30000;
1.1259    raeburn   968:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    969:     if ($skiploadbal) {
                    970:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    971:         unless (defined($cached)) {
                    972:             my $cachetime = 60*60*24;
                    973:             my %domconfig =
                    974:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    975:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    976:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    977:                                            $cachetime);
                    978:             }
                    979:         }
                    980:     }
1.1076    raeburn   981:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn   982:         if ($skiploadbal) {
                    983:             if (ref($balancers) eq 'HASH') {
                    984:                 next if (exists($balancers->{$lonhost}));
                    985:             }
                    986:         }   
1.1115    raeburn   987:         my $loginvia;
                    988:         if ($checkloginvia) {
                    989:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   990:             if ($loginvia) {
                    991:                 my ($server,$path) = split(/:/,$loginvia);
                    992:                 ($login_host, $lowest_load) =
1.1253    raeburn   993:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   994:                 if ($login_host eq $server) {
                    995:                     $portal_path = $path;
1.1151    raeburn   996:                     $isredirect = 1;
1.1116    raeburn   997:                 }
                    998:             } else {
                    999:                 ($login_host, $lowest_load) =
1.1253    raeburn  1000:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1001:                 if ($login_host eq $lonhost) {
                   1002:                     $portal_path = '';
1.1151    raeburn  1003:                     $isredirect = ''; 
1.1116    raeburn  1004:                 }
                   1005:             }
                   1006:         } else {
1.1076    raeburn  1007:             ($login_host, $lowest_load) =
1.1253    raeburn  1008:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1009:         }
                   1010:     }
                   1011:     if ($login_host ne '') {
1.1116    raeburn  1012:         $hostname = &hostname($login_host);
1.1076    raeburn  1013:     }
1.1151    raeburn  1014:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1015: }
                   1016: 
1.202     matthew  1017: # --------------------------------------------- Try to change a user's password
                   1018: 
                   1019: sub changepass {
1.799     raeburn  1020:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1021:     $currentpass = &escape($currentpass);
                   1022:     $newpass     = &escape($newpass);
1.1030    raeburn  1023:     my $lonhost = $perlvar{'lonHostID'};
                   1024:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1025: 		       $server);
                   1026:     if (! $answer) {
                   1027: 	&logthis("No reply on password change request to $server ".
                   1028: 		 "by $uname in domain $udom.");
                   1029:     } elsif ($answer =~ "^ok") {
                   1030:         &logthis("$uname in $udom successfully changed their password ".
                   1031: 		 "on $server.");
                   1032:     } elsif ($answer =~ "^pwchange_failure") {
                   1033: 	&logthis("$uname in $udom was unable to change their password ".
                   1034: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1035: 		 "or pwchange");
                   1036:     } elsif ($answer =~ "^non_authorized") {
                   1037:         &logthis("$uname in $udom did not get their password correct when ".
                   1038: 		 "attempting to change it on $server.");
                   1039:     } elsif ($answer =~ "^auth_mode_error") {
                   1040:         &logthis("$uname in $udom attempted to change their password despite ".
                   1041: 		 "not being locally or internally authenticated on $server.");
                   1042:     } elsif ($answer =~ "^unknown_user") {
                   1043:         &logthis("$uname in $udom attempted to change their password ".
                   1044: 		 "on $server but were unable to because $server is not ".
                   1045: 		 "their home server.");
                   1046:     } elsif ($answer =~ "^refused") {
                   1047: 	&logthis("$server refused to change $uname in $udom password because ".
                   1048: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1049:     } elsif ($answer =~ "invalid_client") {
                   1050:         &logthis("$server refused to change $uname in $udom password because ".
                   1051:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1052:     }
                   1053:     return $answer;
1.1       albertel 1054: }
                   1055: 
1.169     harris41 1056: # ----------------------- Try to determine user's current authentication scheme
                   1057: 
                   1058: sub queryauthenticate {
                   1059:     my ($uname,$udom)=@_;
1.456     albertel 1060:     my $uhome=&homeserver($uname,$udom);
                   1061:     if (!$uhome) {
                   1062: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1063: 	return 'no_host';
                   1064:     }
                   1065:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1066:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1067: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1068:     }
1.456     albertel 1069:     return $answer;
1.169     harris41 1070: }
                   1071: 
1.1       albertel 1072: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1073: 
1.1       albertel 1074: sub authenticate {
1.1073    raeburn  1075:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1076:     $upass=&escape($upass);
                   1077:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1078:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1079:     my $newhome;
1.836     www      1080:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1081: # Maybe the machine was offline and only re-appeared again recently?
                   1082:         &reconlonc();
                   1083: # One more
1.952     raeburn  1084: 	$uhome=&homeserver($uname,$udom,1);
                   1085:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1086:             if (defined(&domain($udom,'primary'))) {
                   1087:                 $newhome=&domain($udom,'primary');
                   1088:             }
                   1089:             if ($newhome ne '') {
                   1090:                 $uhome = $newhome;
                   1091:             }
                   1092:         }
1.836     www      1093: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1094: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1095: 	    return 'no_host';
                   1096:         }
1.1       albertel 1097:     }
1.1073    raeburn  1098:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1099:     if ($answer eq 'authorized') {
1.952     raeburn  1100:         if ($newhome) {
                   1101:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1102:             return 'no_account_on_host'; 
                   1103:         } else {
                   1104:             &logthis("User $uname at $udom authorized by $uhome");
                   1105:             return $uhome;
                   1106:         }
1.471     albertel 1107:     }
                   1108:     if ($answer eq 'non_authorized') {
                   1109: 	&logthis("User $uname at $udom rejected by $uhome");
                   1110: 	return 'no_host'; 
1.9       www      1111:     }
1.471     albertel 1112:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1113:     return 'no_host';
                   1114: }
                   1115: 
1.1073    raeburn  1116: sub can_host_session {
1.1074    raeburn  1117:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1118:     my $canhost = 1;
1.1074    raeburn  1119:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1120:     if (ref($remotesessions) eq 'HASH') {
                   1121:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1122:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1123:                 $canhost = 0;
                   1124:             } else {
                   1125:                 $canhost = 1;
                   1126:             }
                   1127:         }
                   1128:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1129:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1130:                 $canhost = 1;
                   1131:             } else {
                   1132:                 $canhost = 0;
                   1133:             }
                   1134:         }
                   1135:         if ($canhost) {
                   1136:             if ($remotesessions->{'version'} ne '') {
                   1137:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1138:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1139:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1140:                         my $major = $1;
                   1141:                         my $minor = $2;
                   1142:                         if (($major < $reqmajor ) ||
                   1143:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1144:                             $canhost = 0;
                   1145:                         }
                   1146:                     } else {
                   1147:                         $canhost = 0;
                   1148:                     }
                   1149:                 }
                   1150:             }
                   1151:         }
                   1152:     }
                   1153:     if ($canhost) {
                   1154:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1155:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1156:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1157:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1158:                 if (($uint_dom ne '') && 
                   1159:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1160:                     $canhost = 0;
                   1161:                 } else {
                   1162:                     $canhost = 1;
                   1163:                 }
                   1164:             }
                   1165:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1166:                 if (($uint_dom ne '') && 
                   1167:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1168:                     $canhost = 1;
                   1169:                 } else {
                   1170:                     $canhost = 0;
                   1171:                 }
                   1172:             }
                   1173:         }
                   1174:     }
                   1175:     return $canhost;
                   1176: }
                   1177: 
1.1083    raeburn  1178: sub spare_can_host {
                   1179:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1180:     my $canhost=1;
                   1181:     my @intdoms;
                   1182:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1183:     if (ref($internet_names) eq 'ARRAY') {
                   1184:         @intdoms = @{$internet_names};
                   1185:     }
                   1186:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1187:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1188:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1189:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1190:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1191:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1192:                                      $remotesessions,
                   1193:                                      $defdomdefaults{'hostedsessions'});
                   1194:     }
                   1195:     return $canhost;
                   1196: }
                   1197: 
1.1123    raeburn  1198: sub this_host_spares {
                   1199:     my ($dom) = @_;
1.1126    raeburn  1200:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1201:     my @hosts = &current_machine_ids();
                   1202:     foreach my $lonhost (@hosts) {
                   1203:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1204:             $dom_in_use = $dom;
                   1205:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1206:             last;
                   1207:         }
                   1208:     }
1.1126    raeburn  1209:     if ($dom_in_use ne '') {
                   1210:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1211:     }
                   1212:     if (ref($result) ne 'HASH') {
                   1213:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1214:         $dom_in_use = &host_domain($lonhost_in_use);
                   1215:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1216:         if (ref($result) ne 'HASH') {
                   1217:             $result = \%spareid;
                   1218:         }
                   1219:     }
                   1220:     return $result;
                   1221: }
                   1222: 
                   1223: sub spares_for_offload  {
                   1224:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1225:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1226:     if (defined($cached)) {
                   1227:         return $result;
                   1228:     } else {
1.1126    raeburn  1229:         my $cachetime = 60*60*24;
                   1230:         my %domconfig =
                   1231:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1232:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1233:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1234:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1235:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1236:                 }
                   1237:             }
                   1238:         }
                   1239:     }
1.1126    raeburn  1240:     return;
1.1123    raeburn  1241: }
                   1242: 
1.1129    raeburn  1243: sub get_lonbalancer_config {
                   1244:     my ($servers) = @_;
                   1245:     my ($currbalancer,$currtargets);
                   1246:     if (ref($servers) eq 'HASH') {
                   1247:         foreach my $server (keys(%{$servers})) {
                   1248:             my %what = (
                   1249:                          spareid => 1,
                   1250:                          perlvar => 1,
                   1251:                        );
                   1252:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1253:             if ($result eq 'ok') {
                   1254:                 if (ref($returnhash) eq 'HASH') {
                   1255:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1256:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1257:                             $currbalancer = $server;
                   1258:                             $currtargets = {};
                   1259:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1260:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1261:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1262:                                 }
                   1263:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1264:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1265:                                 }
                   1266:                             }
                   1267:                             last;
                   1268:                         }
                   1269:                     }
                   1270:                 }
                   1271:             }
                   1272:         }
                   1273:     }
                   1274:     return ($currbalancer,$currtargets);
                   1275: }
                   1276: 
                   1277: sub check_loadbalancing {
                   1278:     my ($uname,$udom) = @_;
1.1191    raeburn  1279:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1280:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1281:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1282:     my @hosts = &current_machine_ids();
1.1129    raeburn  1283:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1284:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1285:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1286:     my $serverhomedom = &host_domain($lonhost);
                   1287: 
                   1288:     my $cachetime = 60*60*24;
                   1289: 
                   1290:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1291:         $dom_in_use = $udom;
                   1292:         $homeintdom = 1;
                   1293:     } else {
                   1294:         $dom_in_use = $serverhomedom;
                   1295:     }
                   1296:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1297:     unless (defined($cached)) {
                   1298:         my %domconfig =
                   1299:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1300:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1301:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1302:         }
                   1303:     }
                   1304:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1305:         ($is_balancer,$currtargets,$currrules) = 
                   1306:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1307:         if ($is_balancer) {
                   1308:             if (ref($currrules) eq 'HASH') {
                   1309:                 if ($homeintdom) {
                   1310:                     if ($uname ne '') {
                   1311:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1312:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1313:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1314:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1315:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1316:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1317:                             }
                   1318:                         }
                   1319:                         if ($rule_in_effect eq '') {
                   1320:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1321:                             if ($userenv{'inststatus'} ne '') {
                   1322:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1323:                                 my ($othertitle,$usertypes,$types) =
                   1324:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1325:                                 if (ref($types) eq 'ARRAY') {
                   1326:                                     foreach my $type (@{$types}) {
                   1327:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1328:                                             if (exists($currrules->{$type})) {
                   1329:                                                 $rule_in_effect = $currrules->{$type};
                   1330:                                             }
                   1331:                                         }
                   1332:                                     }
                   1333:                                 }
                   1334:                             } else {
                   1335:                                 if (exists($currrules->{'default'})) {
                   1336:                                     $rule_in_effect = $currrules->{'default'};
                   1337:                                 }
                   1338:                             }
                   1339:                         }
                   1340:                     } else {
                   1341:                         if (exists($currrules->{'default'})) {
                   1342:                             $rule_in_effect = $currrules->{'default'};
                   1343:                         }
                   1344:                     }
                   1345:                 } else {
                   1346:                     if ($currrules->{'_LC_external'} ne '') {
                   1347:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1348:                     }
                   1349:                 }
                   1350:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1351:                                                        $uname,$udom);
                   1352:             }
                   1353:         }
                   1354:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1355:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1356:         unless (defined($cached)) {
                   1357:             my %domconfig =
                   1358:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1359:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1360:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1361:             }
                   1362:         }
                   1363:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1364:             ($is_balancer,$currtargets,$currrules) = 
                   1365:                 &check_balancer_result($result,@hosts);
                   1366:             if ($is_balancer) {
1.1129    raeburn  1367:                 if (ref($currrules) eq 'HASH') {
                   1368:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1369:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1370:                     }
                   1371:                 }
                   1372:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1373:                                                        $uname,$udom);
                   1374:             }
                   1375:         } else {
                   1376:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1377:                 $is_balancer = 1;
                   1378:                 $offloadto = &this_host_spares($dom_in_use);
                   1379:             }
                   1380:         }
                   1381:     } else {
                   1382:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1383:             $is_balancer = 1;
                   1384:             $offloadto = &this_host_spares($dom_in_use);
                   1385:         }
                   1386:     }
1.1176    raeburn  1387:     if ($is_balancer) {
                   1388:         my $lowest_load = 30000;
                   1389:         if (ref($offloadto) eq 'HASH') {
                   1390:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1391:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1392:                     ($otherserver,$lowest_load) =
                   1393:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1394:                 }
1.1129    raeburn  1395:             }
1.1176    raeburn  1396:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1397: 
1.1176    raeburn  1398:             if (!$found_server) {
                   1399:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1400:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1401:                         ($otherserver,$lowest_load) =
                   1402:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1403:                     }
                   1404:                 }
                   1405:             }
                   1406:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1407:             if (@{$offloadto} == 1) {
                   1408:                 $otherserver = $offloadto->[0];
                   1409:             } elsif (@{$offloadto} > 1) {
                   1410:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1411:                     ($otherserver,$lowest_load) =
                   1412:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1413:                 }
                   1414:             }
                   1415:         }
1.1176    raeburn  1416:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1417:             $is_balancer = 0;
                   1418:             if ($uname ne '' && $udom ne '') {
                   1419:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1420:                     
                   1421:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1422:                              'user.loadbalcheck.time' => time});
                   1423:                 }
1.1129    raeburn  1424:             }
                   1425:         }
                   1426:     }
                   1427:     return ($is_balancer,$otherserver);
                   1428: }
                   1429: 
1.1191    raeburn  1430: sub check_balancer_result {
                   1431:     my ($result,@hosts) = @_;
                   1432:     my ($is_balancer,$currtargets,$currrules);
                   1433:     if (ref($result) eq 'HASH') {
                   1434:         if ($result->{'lonhost'} ne '') {
                   1435:             my $currbalancer = $result->{'lonhost'};
                   1436:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1437:                 $is_balancer = 1;
                   1438:                 $currtargets = $result->{'targets'};
                   1439:                 $currrules = $result->{'rules'};
                   1440:             }
                   1441:         } else {
                   1442:             foreach my $key (keys(%{$result})) {
                   1443:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1444:                     (ref($result->{$key}) eq 'HASH')) {
                   1445:                     $is_balancer = 1;
                   1446:                     $currrules = $result->{$key}{'rules'};
                   1447:                     $currtargets = $result->{$key}{'targets'};
                   1448:                     last;
                   1449:                 }
                   1450:             }
                   1451:         }
                   1452:     }
                   1453:     return ($is_balancer,$currtargets,$currrules);
                   1454: }
                   1455: 
1.1129    raeburn  1456: sub get_loadbalancer_targets {
                   1457:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1458:     my $offloadto;
1.1175    raeburn  1459:     if ($rule_in_effect eq 'none') {
                   1460:         return [$perlvar{'lonHostID'}];
                   1461:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1462:         $offloadto = $currtargets;
                   1463:     } else {
                   1464:         if ($rule_in_effect eq 'homeserver') {
                   1465:             my $homeserver = &homeserver($uname,$udom);
                   1466:             if ($homeserver ne 'no_host') {
                   1467:                 $offloadto = [$homeserver];
                   1468:             }
                   1469:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1470:             my %domconfig =
                   1471:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1472:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1473:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1474:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1475:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1476:                     }
                   1477:                 }
                   1478:             } else {
1.1178    raeburn  1479:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1480:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1481:                 if (&hostname($remotebalancer) ne '') {
                   1482:                     $offloadto = [$remotebalancer];
                   1483:                 }
                   1484:             }
                   1485:         } elsif (&hostname($rule_in_effect) ne '') {
                   1486:             $offloadto = [$rule_in_effect];
                   1487:         }
                   1488:     }
                   1489:     return $offloadto;
                   1490: }
                   1491: 
1.1127    raeburn  1492: sub internet_dom_servers {
                   1493:     my ($dom) = @_;
                   1494:     my (%uniqservers,%servers);
                   1495:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1496:     my @machinedoms = &machine_domains($primaryserver);
                   1497:     foreach my $mdom (@machinedoms) {
                   1498:         my %currservers = %servers;
                   1499:         my %server = &get_servers($mdom);
                   1500:         %servers = (%currservers,%server);
                   1501:     }
                   1502:     my %by_hostname;
                   1503:     foreach my $id (keys(%servers)) {
                   1504:         push(@{$by_hostname{$servers{$id}}},$id);
                   1505:     }
                   1506:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1507:         if (@{$by_hostname{$hostname}} > 1) {
                   1508:             my $match = 0;
                   1509:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1510:                 if (&host_domain($id) eq $dom) {
                   1511:                     $uniqservers{$id} = $hostname;
                   1512:                     $match = 1;
                   1513:                 }
                   1514:             }
                   1515:             unless ($match) {
                   1516:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1517:             }
                   1518:         } else {
                   1519:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1520:         }
                   1521:     }
                   1522:     return %uniqservers;
                   1523: }
                   1524: 
1.1       albertel 1525: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1526: 
1.599     albertel 1527: my %homecache;
1.1       albertel 1528: sub homeserver {
1.230     stredwic 1529:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1530:     my $index="$uname:$udom";
1.426     albertel 1531: 
1.599     albertel 1532:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1533: 
                   1534:     my %servers = &get_servers($udom,'library');
                   1535:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1536:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1537: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1538: 
                   1539: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1540: 	if ($answer eq 'found') {
                   1541: 	    delete($badServerCache{$tryserver}); 
                   1542: 	    return $homecache{$index}=$tryserver;
                   1543: 	} elsif ($answer eq 'no_host') {
                   1544: 	    $badServerCache{$tryserver}=1;
                   1545: 	}
1.1       albertel 1546:     }    
                   1547:     return 'no_host';
1.70      www      1548: }
                   1549: 
                   1550: # ------------------------------------- Find the usernames behind a list of IDs
                   1551: 
                   1552: sub idget {
                   1553:     my ($udom,@ids)=@_;
                   1554:     my %returnhash=();
                   1555:     
1.841     albertel 1556:     my %servers = &get_servers($udom,'library');
                   1557:     foreach my $tryserver (keys(%servers)) {
                   1558: 	my $idlist=join('&',@ids);
                   1559: 	$idlist=~tr/A-Z/a-z/; 
                   1560: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1561: 	my @answer=();
                   1562: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1563: 	    @answer=split(/\&/,$reply);
                   1564: 	}                    ;
                   1565: 	my $i;
                   1566: 	for ($i=0;$i<=$#ids;$i++) {
                   1567: 	    if ($answer[$i]) {
                   1568: 		$returnhash{$ids[$i]}=$answer[$i];
                   1569: 	    } 
                   1570: 	}
                   1571:     } 
1.70      www      1572:     return %returnhash;
                   1573: }
                   1574: 
                   1575: # ------------------------------------- Find the IDs behind a list of usernames
                   1576: 
                   1577: sub idrget {
                   1578:     my ($udom,@unames)=@_;
                   1579:     my %returnhash=();
1.800     albertel 1580:     foreach my $uname (@unames) {
                   1581:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1582:     }
1.70      www      1583:     return %returnhash;
                   1584: }
                   1585: 
                   1586: # ------------------------------- Store away a list of names and associated IDs
                   1587: 
                   1588: sub idput {
                   1589:     my ($udom,%ids)=@_;
                   1590:     my %servers=();
1.800     albertel 1591:     foreach my $uname (keys(%ids)) {
                   1592: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1593:         my $uhom=&homeserver($uname,$udom);
1.70      www      1594:         if ($uhom ne 'no_host') {
1.800     albertel 1595:             my $id=&escape($ids{$uname});
1.70      www      1596:             $id=~tr/A-Z/a-z/;
1.800     albertel 1597:             my $esc_unam=&escape($uname);
1.70      www      1598: 	    if ($servers{$uhom}) {
1.800     albertel 1599: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1600:             } else {
1.800     albertel 1601:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1602:             }
                   1603:         }
1.191     harris41 1604:     }
1.800     albertel 1605:     foreach my $server (keys(%servers)) {
                   1606:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1607:     }
1.344     www      1608: }
                   1609: 
1.1231    raeburn  1610: # ---------------------------------------- Delete unwanted IDs from ids.db file 
                   1611: 
                   1612: sub iddel {
                   1613:     my ($udom,$idshashref,$uhome)=@_;
                   1614:     my %result=();
                   1615:     unless (ref($idshashref) eq 'HASH') {
                   1616:         return %result;
                   1617:     }
                   1618:     my %servers=();
                   1619:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1620:         my $uhom;
                   1621:         if ($uhome) {
                   1622:             $uhom = $uhome;
                   1623:         } else {
                   1624:             $uhom=&homeserver($uname,$udom);
                   1625:         }
                   1626:         if ($uhom ne 'no_host') {
                   1627:             if ($servers{$uhom}) {
                   1628:                 $servers{$uhom}.='&'.&escape($id);
                   1629:             } else {
                   1630:                 $servers{$uhom}=&escape($id);
                   1631:             }
                   1632:         }
                   1633:     }
                   1634:     foreach my $server (keys(%servers)) {
                   1635:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1636:     }
                   1637:     return %result;
                   1638: }
                   1639: 
1.1023    raeburn  1640: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1641: sub dump_dom {
1.1165    droeschl 1642:     my ($namespace, $udom, $regexp) = @_;
                   1643: 
                   1644:     $udom ||= $env{'user.domain'};
                   1645: 
                   1646:     return () unless $udom;
                   1647: 
                   1648:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1649: }
                   1650: 
1.1023    raeburn  1651: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1652: 
                   1653: sub get_dom {
1.860     raeburn  1654:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1655:     my $items='';
                   1656:     foreach my $item (@$storearr) {
                   1657:         $items.=&escape($item).'&';
                   1658:     }
                   1659:     $items=~s/\&$//;
1.860     raeburn  1660:     if (!$udom) {
                   1661:         $udom=$env{'user.domain'};
                   1662:         if (defined(&domain($udom,'primary'))) {
                   1663:             $uhome=&domain($udom,'primary');
                   1664:         } else {
1.874     albertel 1665:             undef($uhome);
1.860     raeburn  1666:         }
                   1667:     } else {
                   1668:         if (!$uhome) {
                   1669:             if (defined(&domain($udom,'primary'))) {
                   1670:                 $uhome=&domain($udom,'primary');
                   1671:             }
                   1672:         }
                   1673:     }
                   1674:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1675:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1676:         my %returnhash;
1.875     albertel 1677:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1678:             return %returnhash;
                   1679:         }
1.806     raeburn  1680:         my @pairs=split(/\&/,$rep);
                   1681:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1682:             return @pairs;
                   1683:         }
                   1684:         my $i=0;
                   1685:         foreach my $item (@$storearr) {
                   1686:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1687:             $i++;
                   1688:         }
                   1689:         return %returnhash;
                   1690:     } else {
1.880     banghart 1691:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1692:     }
                   1693: }
                   1694: 
                   1695: # -------------------------------------------- put items in domain db files 
                   1696: 
                   1697: sub put_dom {
1.860     raeburn  1698:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1699:     if (!$udom) {
                   1700:         $udom=$env{'user.domain'};
                   1701:         if (defined(&domain($udom,'primary'))) {
                   1702:             $uhome=&domain($udom,'primary');
                   1703:         } else {
1.874     albertel 1704:             undef($uhome);
1.860     raeburn  1705:         }
                   1706:     } else {
                   1707:         if (!$uhome) {
                   1708:             if (defined(&domain($udom,'primary'))) {
                   1709:                 $uhome=&domain($udom,'primary');
                   1710:             }
                   1711:         }
                   1712:     } 
                   1713:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1714:         my $items='';
                   1715:         foreach my $item (keys(%$storehash)) {
                   1716:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1717:         }
                   1718:         $items=~s/\&$//;
                   1719:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1720:     } else {
1.860     raeburn  1721:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1722:     }
                   1723: }
                   1724: 
1.1023    raeburn  1725: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1726: sub newput_dom {
1.1023    raeburn  1727:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1728:     my $result;
                   1729:     if (!$udom) {
                   1730:         $udom=$env{'user.domain'};
                   1731:     }
1.1023    raeburn  1732:     if ($udom) {
                   1733:         my $uname = &get_domainconfiguser($udom);
                   1734:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1735:     }
                   1736:     return $result;
                   1737: }
                   1738: 
1.1023    raeburn  1739: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1740: sub del_dom {
1.1023    raeburn  1741:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1742:     if (ref($storearr) eq 'ARRAY') {
                   1743:         if (!$udom) {
                   1744:             $udom=$env{'user.domain'};
                   1745:         }
1.1023    raeburn  1746:         if ($udom) {
                   1747:             my $uname = &get_domainconfiguser($udom); 
                   1748:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1749:         }
                   1750:     }
                   1751: }
                   1752: 
1.1023    raeburn  1753: # ----------------------------------construct domainconfig user for a domain 
                   1754: sub get_domainconfiguser {
                   1755:     my ($udom) = @_;
                   1756:     return $udom.'-domainconfig';
                   1757: }
                   1758: 
1.837     raeburn  1759: sub retrieve_inst_usertypes {
                   1760:     my ($udom) = @_;
                   1761:     my (%returnhash,@order);
1.989     raeburn  1762:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1763:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1764:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1765:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1766:     } else {
                   1767:         if (defined(&domain($udom,'primary'))) {
                   1768:             my $uhome=&domain($udom,'primary');
                   1769:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1770:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1771:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1772:                 return (\%returnhash,\@order);
                   1773:             }
                   1774:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1775:             my @pairs=split(/\&/,$hashitems);
                   1776:             foreach my $item (@pairs) {
                   1777:                 my ($key,$value)=split(/=/,$item,2);
                   1778:                 $key = &unescape($key);
                   1779:                 next if ($key =~ /^error: 2 /);
                   1780:                 $returnhash{$key}=&thaw_unescape($value);
                   1781:             }
                   1782:             my @esc_order = split(/\&/,$orderitems);
                   1783:             foreach my $item (@esc_order) {
                   1784:                 push(@order,&unescape($item));
                   1785:             }
                   1786:         } else {
1.1256    raeburn  1787:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1788:         }
1.1256    raeburn  1789:         return (\%returnhash,\@order);
1.837     raeburn  1790:     }
                   1791: }
                   1792: 
1.868     raeburn  1793: sub is_domainimage {
                   1794:     my ($url) = @_;
                   1795:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1796:         if (&domain($1) ne '') {
                   1797:             return '1';
                   1798:         }
                   1799:     }
                   1800:     return;
                   1801: }
                   1802: 
1.899     raeburn  1803: sub inst_directory_query {
                   1804:     my ($srch) = @_;
                   1805:     my $udom = $srch->{'srchdomain'};
                   1806:     my %results;
                   1807:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1808:     my $outcome;
1.899     raeburn  1809:     if ($homeserver ne '') {
1.904     albertel 1810: 	my $queryid=&reply("querysend:instdirsearch:".
                   1811: 			   &escape($srch->{'srchby'}).':'.
                   1812: 			   &escape($srch->{'srchterm'}).':'.
                   1813: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1814: 	my $host=&hostname($homeserver);
                   1815: 	if ($queryid !~/^\Q$host\E\_/) {
                   1816: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1817: 	    return;
                   1818: 	}
                   1819: 	my $response = &get_query_reply($queryid);
                   1820: 	my $maxtries = 5;
                   1821: 	my $tries = 1;
                   1822: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1823: 	    $response = &get_query_reply($queryid);
                   1824: 	    $tries ++;
                   1825: 	}
                   1826: 
                   1827:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1828:             if ($response eq 'unavailable') {
                   1829:                 $outcome = $response;
                   1830:             } else {
                   1831:                 $outcome = 'ok';
                   1832:                 my @matches = split(/\n/,$response);
                   1833:                 foreach my $match (@matches) {
                   1834:                     my ($key,$value) = split(/=/,$match);
                   1835:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1836:                 }
1.899     raeburn  1837:             }
                   1838:         }
                   1839:     }
1.909     raeburn  1840:     return ($outcome,%results);
1.899     raeburn  1841: }
                   1842: 
                   1843: sub usersearch {
                   1844:     my ($srch) = @_;
                   1845:     my $dom = $srch->{'srchdomain'};
                   1846:     my %results;
                   1847:     my %libserv = &all_library();
                   1848:     my $query = 'usersearch';
                   1849:     foreach my $tryserver (keys(%libserv)) {
                   1850:         if (&host_domain($tryserver) eq $dom) {
                   1851:             my $host=&hostname($tryserver);
                   1852:             my $queryid=
1.911     raeburn  1853:                 &reply("querysend:".&escape($query).':'.
                   1854:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1855:                        &escape($srch->{'srchtype'}).':'.
                   1856:                        &escape($srch->{'srchterm'}),$tryserver);
                   1857:             if ($queryid !~/^\Q$host\E\_/) {
                   1858:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1859:                 next;
1.899     raeburn  1860:             }
                   1861:             my $reply = &get_query_reply($queryid);
                   1862:             my $maxtries = 1;
                   1863:             my $tries = 1;
                   1864:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1865:                 $reply = &get_query_reply($queryid);
                   1866:                 $tries ++;
                   1867:             }
                   1868:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1869:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1870:             } else {
1.911     raeburn  1871:                 my @matches;
                   1872:                 if ($reply =~ /\n/) {
                   1873:                     @matches = split(/\n/,$reply);
                   1874:                 } else {
                   1875:                     @matches = split(/\&/,$reply);
                   1876:                 }
1.899     raeburn  1877:                 foreach my $match (@matches) {
                   1878:                     my ($uname,$udom,%userhash);
1.911     raeburn  1879:                     foreach my $entry (split(/:/,$match)) {
                   1880:                         my ($key,$value) =
                   1881:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1882:                         $userhash{$key} = $value;
                   1883:                         if ($key eq 'username') {
                   1884:                             $uname = $value;
                   1885:                         } elsif ($key eq 'domain') {
                   1886:                             $udom = $value;
1.911     raeburn  1887:                         }
1.899     raeburn  1888:                     }
                   1889:                     $results{$uname.':'.$udom} = \%userhash;
                   1890:                 }
                   1891:             }
                   1892:         }
                   1893:     }
                   1894:     return %results;
                   1895: }
                   1896: 
1.912     raeburn  1897: sub get_instuser {
                   1898:     my ($udom,$uname,$id) = @_;
                   1899:     my $homeserver = &domain($udom,'primary');
                   1900:     my ($outcome,%results);
                   1901:     if ($homeserver ne '') {
                   1902:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1903:                            &escape($id).':'.&escape($udom),$homeserver);
                   1904:         my $host=&hostname($homeserver);
                   1905:         if ($queryid !~/^\Q$host\E\_/) {
                   1906:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1907:             return;
                   1908:         }
                   1909:         my $response = &get_query_reply($queryid);
                   1910:         my $maxtries = 5;
                   1911:         my $tries = 1;
                   1912:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1913:             $response = &get_query_reply($queryid);
                   1914:             $tries ++;
                   1915:         }
                   1916:         if (!&error($response) && $response ne 'refused') {
                   1917:             if ($response eq 'unavailable') {
                   1918:                 $outcome = $response;
                   1919:             } else {
                   1920:                 $outcome = 'ok';
                   1921:                 my @matches = split(/\n/,$response);
                   1922:                 foreach my $match (@matches) {
                   1923:                     my ($key,$value) = split(/=/,$match);
                   1924:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1925:                 }
                   1926:             }
                   1927:         }
                   1928:     }
                   1929:     my %userinfo;
                   1930:     if (ref($results{$uname}) eq 'HASH') {
                   1931:         %userinfo = %{$results{$uname}};
                   1932:     } 
                   1933:     return ($outcome,%userinfo);
                   1934: }
                   1935: 
                   1936: sub inst_rulecheck {
1.923     raeburn  1937:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1938:     my %returnhash;
                   1939:     if ($udom ne '') {
                   1940:         if (ref($rules) eq 'ARRAY') {
                   1941:             @{$rules} = map {&escape($_);} (@{$rules});
                   1942:             my $rulestr = join(':',@{$rules});
                   1943:             my $homeserver=&domain($udom,'primary');
                   1944:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1945:                 my $response;
                   1946:                 if ($item eq 'username') {                
                   1947:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1948:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1949:                                               $homeserver));
1.923     raeburn  1950:                 } elsif ($item eq 'id') {
                   1951:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1952:                                               ':'.&escape($id).':'.$rulestr,
                   1953:                                               $homeserver));
1.945     raeburn  1954:                 } elsif ($item eq 'selfcreate') {
                   1955:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1956:                                                &escape($udom).':'.&escape($uname).
                   1957:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1958:                 }
1.912     raeburn  1959:                 if ($response ne 'refused') {
                   1960:                     my @pairs=split(/\&/,$response);
                   1961:                     foreach my $item (@pairs) {
                   1962:                         my ($key,$value)=split(/=/,$item,2);
                   1963:                         $key = &unescape($key);
                   1964:                         next if ($key =~ /^error: 2 /);
                   1965:                         $returnhash{$key}=&thaw_unescape($value);
                   1966:                     }
                   1967:                 }
                   1968:             }
                   1969:         }
                   1970:     }
                   1971:     return %returnhash;
                   1972: }
                   1973: 
                   1974: sub inst_userrules {
1.923     raeburn  1975:     my ($udom,$check) = @_;
1.912     raeburn  1976:     my (%ruleshash,@ruleorder);
                   1977:     if ($udom ne '') {
                   1978:         my $homeserver=&domain($udom,'primary');
                   1979:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1980:             my $response;
                   1981:             if ($check eq 'id') {
                   1982:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1983:                                  $homeserver);
1.943     raeburn  1984:             } elsif ($check eq 'email') {
                   1985:                 $response=&reply('instemailrules:'.&escape($udom),
                   1986:                                  $homeserver);
1.923     raeburn  1987:             } else {
                   1988:                 $response=&reply('instuserrules:'.&escape($udom),
                   1989:                                  $homeserver);
                   1990:             }
1.912     raeburn  1991:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1992:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1993:                 ($response ne 'no_such_host')) {
                   1994:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1995:                 my @pairs=split(/\&/,$hashitems);
                   1996:                 foreach my $item (@pairs) {
                   1997:                     my ($key,$value)=split(/=/,$item,2);
                   1998:                     $key = &unescape($key);
                   1999:                     next if ($key =~ /^error: 2 /);
                   2000:                     $ruleshash{$key}=&thaw_unescape($value);
                   2001:                 }
                   2002:                 my @esc_order = split(/\&/,$orderitems);
                   2003:                 foreach my $item (@esc_order) {
                   2004:                     push(@ruleorder,&unescape($item));
                   2005:                 }
                   2006:             }
                   2007:         }
                   2008:     }
                   2009:     return (\%ruleshash,\@ruleorder);
                   2010: }
                   2011: 
1.976     raeburn  2012: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2013: 
                   2014: sub get_domain_defaults {
1.1240    raeburn  2015:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2016:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2017:     my $cachetime = 60*60*24;
1.1240    raeburn  2018:     unless ($ignore_cache) {
                   2019:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2020:         if (defined($cached)) {
                   2021:             if (ref($result) eq 'HASH') {
                   2022:                 return %{$result};
                   2023:             }
1.943     raeburn  2024:         }
                   2025:     }
                   2026:     my %domdefaults;
                   2027:     my %domconfig =
1.989     raeburn  2028:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2029:                                   'requestcourses','inststatus',
1.1183    raeburn  2030:                                   'coursedefaults','usersessions',
1.1258    raeburn  2031:                                   'requestauthor','selfenrollment',
                   2032:                                   'coursecategories'],$domain);
1.1254    raeburn  2033:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2034:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2035:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2036:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2037:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2038:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2039:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2040:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2041:     } else {
                   2042:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2043:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2044:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2045:     }
1.976     raeburn  2046:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2047:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2048:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2049:         } else {
                   2050:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2051:         }
1.1177    raeburn  2052:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2053:         foreach my $item (@usertools) {
                   2054:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2055:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2056:             }
                   2057:         }
1.1229    raeburn  2058:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2059:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2060:         }
1.976     raeburn  2061:     }
1.985     raeburn  2062:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246    raeburn  2063:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2064:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2065:         }
                   2066:     }
1.1183    raeburn  2067:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2068:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2069:     }
1.989     raeburn  2070:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2071:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2072:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2073:         }
                   2074:     }
1.1047    raeburn  2075:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2076:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1254    raeburn  2077:         foreach my $type (@coursetypes) {
                   2078:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2079:                 unless ($type eq 'community') {
                   2080:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2081:                 }
                   2082:             }
                   2083:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2084:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2085:             }
1.1230    raeburn  2086:         }
1.1047    raeburn  2087:     }
1.1073    raeburn  2088:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2089:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2090:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2091:         }
                   2092:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2093:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2094:         }
                   2095:     }
1.1254    raeburn  2096:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2097:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2098:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2099:                             'approval','limit');
                   2100:             foreach my $type (@coursetypes) {
                   2101:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2102:                     my @mgrdc = ();
                   2103:                     foreach my $item (@settings) {
                   2104:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2105:                             push(@mgrdc,$item);
                   2106:                         }
                   2107:                     }
                   2108:                     if (@mgrdc) {
                   2109:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2110:                     }
                   2111:                 }
                   2112:             }
                   2113:         }
                   2114:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2115:             foreach my $type (@coursetypes) {
                   2116:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2117:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2118:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2119:                     }
                   2120:                 }
                   2121:             }
                   2122:         }
                   2123:     }
1.1258    raeburn  2124:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2125:         $domdefaults{'catauth'} = 'std';
                   2126:         $domdefaults{'catunauth'} = 'std';
                   2127:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2128:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2129:         }
                   2130:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2131:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2132:         }
                   2133:     }
1.1219    raeburn  2134:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2135:     return %domdefaults;
                   2136: }
                   2137: 
1.344     www      2138: # --------------------------------------------------- Assign a key to a student
                   2139: 
                   2140: sub assign_access_key {
1.364     www      2141: #
                   2142: # a valid key looks like uname:udom#comments
                   2143: # comments are being appended
                   2144: #
1.498     www      2145:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2146:     $kdom=
1.620     albertel 2147:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2148:     $knum=
1.620     albertel 2149:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2150:     $cdom=
1.620     albertel 2151:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2152:     $cnum=
1.620     albertel 2153:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2154:     $udom=$env{'user.name'} unless (defined($udom));
                   2155:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2156:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2157:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2158:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2159:                                                   # assigned to this person
                   2160:                                                   # - this should not happen,
1.345     www      2161:                                                   # unless something went wrong
                   2162:                                                   # the first time around
                   2163: # ready to assign
1.364     www      2164:         $logentry=$1.'; '.$logentry;
1.496     www      2165:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2166:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2167: # key now belongs to user
1.346     www      2168: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2169:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2170:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2171:                 return 'ok';
                   2172:             } else {
                   2173:                 return 
                   2174:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2175: 	    }
                   2176:         } else {
                   2177:             return 'error: Could not assign key, try again later.';
                   2178:         }
1.364     www      2179:     } elsif (!$existing{$ckey}) {
1.345     www      2180: # the key does not exist
                   2181: 	return 'error: The key does not exist';
                   2182:     } else {
                   2183: # the key is somebody else's
                   2184: 	return 'error: The key is already in use';
                   2185:     }
1.344     www      2186: }
                   2187: 
1.364     www      2188: # ------------------------------------------ put an additional comment on a key
                   2189: 
                   2190: sub comment_access_key {
                   2191: #
                   2192: # a valid key looks like uname:udom#comments
                   2193: # comments are being appended
                   2194: #
                   2195:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2196:     $cdom=
1.620     albertel 2197:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2198:     $cnum=
1.620     albertel 2199:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2200:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2201:     if ($existing{$ckey}) {
                   2202:         $existing{$ckey}.='; '.$logentry;
                   2203: # ready to assign
1.367     www      2204:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2205:                                                  $cdom,$cnum) eq 'ok') {
                   2206: 	    return 'ok';
                   2207:         } else {
                   2208: 	    return 'error: Count not store comment.';
                   2209:         }
                   2210:     } else {
                   2211: # the key does not exist
                   2212: 	return 'error: The key does not exist';
                   2213:     }
                   2214: }
                   2215: 
1.344     www      2216: # ------------------------------------------------------ Generate a set of keys
                   2217: 
                   2218: sub generate_access_keys {
1.364     www      2219:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2220:     $cdom=
1.620     albertel 2221:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2222:     $cnum=
1.620     albertel 2223:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2224:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2225:     unless (($cdom) && ($cnum)) { return 0; }
                   2226:     if ($number>10000) { return 0; }
                   2227:     sleep(2); # make sure don't get same seed twice
                   2228:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2229:     my $total=0;
                   2230:     for (my $i=1;$i<=$number;$i++) {
                   2231:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2232:                   sprintf("%lx",int(100000*rand)).'-'.
                   2233:                   sprintf("%lx",int(100000*rand));
                   2234:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2235:        $newkey=~s/0/h/g; # and also 0 and O
                   2236:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2237:        if ($existing{$newkey}) {
                   2238:            $i--;
                   2239:        } else {
1.364     www      2240: 	  if (&put('accesskeys',
                   2241:               { $newkey => '# generated '.localtime().
1.620     albertel 2242:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2243:                            '; '.$logentry },
                   2244: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2245:               $total++;
                   2246: 	  }
                   2247:        }
                   2248:     }
1.620     albertel 2249:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2250:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2251:     return $total;
                   2252: }
                   2253: 
                   2254: # ------------------------------------------------------- Validate an accesskey
                   2255: 
                   2256: sub validate_access_key {
                   2257:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2258:     $cdom=
1.620     albertel 2259:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2260:     $cnum=
1.620     albertel 2261:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2262:     $udom=$env{'user.domain'} unless (defined($udom));
                   2263:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2264:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2265:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2266: }
                   2267: 
                   2268: # ------------------------------------- Find the section of student in a course
1.652     albertel 2269: sub devalidate_getsection_cache {
                   2270:     my ($udom,$unam,$courseid)=@_;
                   2271:     my $hashid="$udom:$unam:$courseid";
                   2272:     &devalidate_cache_new('getsection',$hashid);
                   2273: }
1.298     matthew  2274: 
1.815     albertel 2275: sub courseid_to_courseurl {
                   2276:     my ($courseid) = @_;
                   2277:     #already url style courseid
                   2278:     return $courseid if ($courseid =~ m{^/});
                   2279: 
                   2280:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2281: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2282: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2283: 	return "/$cdom/$cnum";
                   2284:     }
                   2285: 
                   2286:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2287:     if (exists($courseinfo{'num'})) {
                   2288: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2289:     }
                   2290: 
                   2291:     return undef;
                   2292: }
                   2293: 
1.298     matthew  2294: sub getsection {
                   2295:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2296:     my $cachetime=1800;
1.551     albertel 2297: 
                   2298:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2299:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2300:     if (defined($cached)) { return $result; }
                   2301: 
1.298     matthew  2302:     my %Pending; 
                   2303:     my %Expired;
                   2304:     #
                   2305:     # Each role can either have not started yet (pending), be active, 
                   2306:     #    or have expired.
                   2307:     #
                   2308:     # If there is an active role, we are done.
                   2309:     #
                   2310:     # If there is more than one role which has not started yet, 
                   2311:     #     choose the one which will start sooner
                   2312:     # If there is one role which has not started yet, return it.
                   2313:     #
                   2314:     # If there is more than one expired role, choose the one which ended last.
                   2315:     # If there is a role which has expired, return it.
                   2316:     #
1.815     albertel 2317:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2318:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2319:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2320:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2321:         my $section=$1;
                   2322:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2323:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2324:         my $now=time;
1.548     albertel 2325:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2326:             $Expired{$end}=$section;
                   2327:             next;
                   2328:         }
1.548     albertel 2329:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2330:             $Pending{$start}=$section;
                   2331:             next;
                   2332:         }
1.599     albertel 2333:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2334:     }
                   2335:     #
                   2336:     # Presumedly there will be few matching roles from the above
                   2337:     # loop and the sorting time will be negligible.
                   2338:     if (scalar(keys(%Pending))) {
                   2339:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2340:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2341:     } 
                   2342:     if (scalar(keys(%Expired))) {
                   2343:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2344:         my $time = pop(@sorted);
1.599     albertel 2345:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2346:     }
1.599     albertel 2347:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2348: }
1.70      www      2349: 
1.599     albertel 2350: sub save_cache {
                   2351:     &purge_remembered();
1.722     albertel 2352:     #&Apache::loncommon::validate_page();
1.620     albertel 2353:     undef(%env);
1.780     albertel 2354:     undef($env_loaded);
1.599     albertel 2355: }
1.452     albertel 2356: 
1.599     albertel 2357: my $to_remember=-1;
                   2358: my %remembered;
                   2359: my %accessed;
                   2360: my $kicks=0;
                   2361: my $hits=0;
1.849     albertel 2362: sub make_key {
                   2363:     my ($name,$id) = @_;
1.872     albertel 2364:     if (length($id) > 65 
                   2365: 	&& length(&escape($id)) > 200) {
                   2366: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2367:     }
1.849     albertel 2368:     return &escape($name.':'.$id);
                   2369: }
                   2370: 
1.599     albertel 2371: sub devalidate_cache_new {
                   2372:     my ($name,$id,$debug) = @_;
                   2373:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2374:     $id=&make_key($name,$id);
1.599     albertel 2375:     $memcache->delete($id);
                   2376:     delete($remembered{$id});
                   2377:     delete($accessed{$id});
                   2378: }
                   2379: 
                   2380: sub is_cached_new {
                   2381:     my ($name,$id,$debug) = @_;
1.849     albertel 2382:     $id=&make_key($name,$id);
1.599     albertel 2383:     if (exists($remembered{$id})) {
1.1133    foxr     2384: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2385: 	$accessed{$id}=[&gettimeofday()];
                   2386: 	$hits++;
                   2387: 	return ($remembered{$id},1);
                   2388:     }
                   2389:     my $value = $memcache->get($id);
                   2390:     if (!(defined($value))) {
                   2391: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2392: 	return (undef,undef);
1.416     albertel 2393:     }
1.599     albertel 2394:     if ($value eq '__undef__') {
                   2395: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2396: 	$value=undef;
                   2397:     }
                   2398:     &make_room($id,$value,$debug);
                   2399:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2400:     return ($value,1);
                   2401: }
                   2402: 
                   2403: sub do_cache_new {
                   2404:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2405:     $id=&make_key($name,$id);
1.599     albertel 2406:     my $setvalue=$value;
                   2407:     if (!defined($setvalue)) {
                   2408: 	$setvalue='__undef__';
                   2409:     }
1.623     albertel 2410:     if (!defined($time) ) {
                   2411: 	$time=600;
                   2412:     }
1.599     albertel 2413:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2414:     my $result = $memcache->set($id,$setvalue,$time);
                   2415:     if (! $result) {
1.872     albertel 2416: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2417: 	$memcache->disconnect_all();
1.872     albertel 2418:     }
1.600     albertel 2419:     # need to make a copy of $value
1.919     albertel 2420:     &make_room($id,$value,$debug);
1.599     albertel 2421:     return $value;
                   2422: }
                   2423: 
                   2424: sub make_room {
                   2425:     my ($id,$value,$debug)=@_;
1.919     albertel 2426: 
                   2427:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2428:                                     : $value;
1.599     albertel 2429:     if ($to_remember<0) { return; }
                   2430:     $accessed{$id}=[&gettimeofday()];
                   2431:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2432:     my $to_kick;
                   2433:     my $max_time=0;
                   2434:     foreach my $other (keys(%accessed)) {
                   2435: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2436: 	    $to_kick=$other;
                   2437: 	    $max_time=&tv_interval($accessed{$other});
                   2438: 	}
                   2439:     }
                   2440:     delete($remembered{$to_kick});
                   2441:     delete($accessed{$to_kick});
                   2442:     $kicks++;
                   2443:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2444:     return;
                   2445: }
                   2446: 
1.599     albertel 2447: sub purge_remembered {
1.604     albertel 2448:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2449:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2450:     undef(%remembered);
                   2451:     undef(%accessed);
1.428     albertel 2452: }
1.70      www      2453: # ------------------------------------- Read an entry from a user's environment
                   2454: 
                   2455: sub userenvironment {
                   2456:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2457:     my $items;
                   2458:     foreach my $item (@what) {
                   2459:         $items.=&escape($item).'&';
                   2460:     }
                   2461:     $items=~s/\&$//;
1.70      www      2462:     my %returnhash=();
1.1009    raeburn  2463:     my $uhome = &homeserver($unam,$udom);
                   2464:     unless ($uhome eq 'no_host') {
                   2465:         my @answer=split(/\&/, 
                   2466:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2467:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2468:             return %returnhash;
                   2469:         }
1.1009    raeburn  2470:         my $i;
                   2471:         for ($i=0;$i<=$#what;$i++) {
                   2472: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2473:         }
1.70      www      2474:     }
                   2475:     return %returnhash;
1.1       albertel 2476: }
                   2477: 
1.617     albertel 2478: # ---------------------------------------------------------- Get a studentphoto
                   2479: sub studentphoto {
                   2480:     my ($udom,$unam,$ext) = @_;
                   2481:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2482:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2483:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2484:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2485:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2486:             } else {
                   2487:                 my ($result,$perm_reqd)=
1.707     albertel 2488: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2489:                 if ($result eq 'ok') {
                   2490:                     if (!($perm_reqd eq 'yes')) {
                   2491:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2492:                     }
                   2493:                 }
                   2494:             }
                   2495:         }
                   2496:     } else {
                   2497:         my ($result,$perm_reqd) = 
1.707     albertel 2498: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2499:         if ($result eq 'ok') {
                   2500:             if (!($perm_reqd eq 'yes')) {
                   2501:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2502:             }
                   2503:         }
                   2504:     }
                   2505:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2506: }
                   2507: 
                   2508: sub retrievestudentphoto {
                   2509:     my ($udom,$unam,$ext,$type) = @_;
                   2510:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2511:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2512:     if ($ret eq 'ok') {
                   2513:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2514:         if ($type eq 'thumbnail') {
                   2515:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2516:         }
                   2517:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2518:         return $tokenurl;
                   2519:     } else {
                   2520:         if ($type eq 'thumbnail') {
                   2521:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2522:         } else { 
                   2523:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2524:         }
1.617     albertel 2525:     }
                   2526: }
                   2527: 
1.263     www      2528: # -------------------------------------------------------------------- New chat
                   2529: 
                   2530: sub chatsend {
1.724     raeburn  2531:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2532:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2533:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2534:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2535:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2536: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2537: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2538: }
                   2539: 
                   2540: # ------------------------------------------ Find current version of a resource
                   2541: 
                   2542: sub getversion {
                   2543:     my $fname=&clutter(shift);
1.1189    raeburn  2544:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2545:     return &currentversion(&filelocation('',$fname));
                   2546: }
                   2547: 
                   2548: sub currentversion {
                   2549:     my $fname=shift;
                   2550:     my $author=$fname;
                   2551:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2552:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2553:     my $home=&homeserver($uname,$udom);
1.292     www      2554:     if ($home eq 'no_host') { 
                   2555:         return -1; 
                   2556:     }
1.1112    www      2557:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2558:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2559: 	return -1;
                   2560:     }
1.1112    www      2561:     return $answer;
1.263     www      2562: }
                   2563: 
1.1111    www      2564: #
                   2565: # Return special version number of resource if set by override, empty otherwise
                   2566: #
                   2567: sub usedversion {
                   2568:     my $fname=shift;
                   2569:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2570:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2571:     if ($urlversion) { return $urlversion; }
                   2572:     return '';
                   2573: }
                   2574: 
1.1       albertel 2575: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2576: 
1.1       albertel 2577: sub subscribe {
                   2578:     my $fname=shift;
1.761     raeburn  2579:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2580:     $fname=~s/[\n\r]//g;
1.1       albertel 2581:     my $author=$fname;
                   2582:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2583:     my ($udom,$uname)=split(/\//,$author);
                   2584:     my $home=homeserver($uname,$udom);
1.335     albertel 2585:     if ($home eq 'no_host') {
                   2586:         return 'not_found';
1.1       albertel 2587:     }
                   2588:     my $answer=reply("sub:$fname",$home);
1.64      www      2589:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2590: 	$answer.=' by '.$home;
                   2591:     }
1.1       albertel 2592:     return $answer;
                   2593: }
                   2594:     
1.8       www      2595: # -------------------------------------------------------------- Replicate file
                   2596: 
                   2597: sub repcopy {
                   2598:     my $filename=shift;
1.23      www      2599:     $filename=~s/\/+/\//g;
1.1142    raeburn  2600:     my $londocroot = $perlvar{'lonDocRoot'};
                   2601:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2602:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2603:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2604: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2605: 	return &repcopy_userfile($filename);
                   2606:     }
1.532     albertel 2607:     $filename=~s/[\n\r]//g;
1.8       www      2608:     my $transname="$filename.in.transfer";
1.828     www      2609: # FIXME: this should flock
1.607     raeburn  2610:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2611:     my $remoteurl=subscribe($filename);
1.64      www      2612:     if ($remoteurl =~ /^con_lost by/) {
                   2613: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2614:            return 'unavailable';
1.8       www      2615:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2616: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2617: 	   return 'not_found';
1.64      www      2618:     } elsif ($remoteurl =~ /^rejected by/) {
                   2619: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2620:            return 'forbidden';
1.20      www      2621:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2622:            return 'ok';
1.8       www      2623:     } else {
1.290     www      2624:         my $author=$filename;
                   2625:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2626:         my ($udom,$uname)=split(/\//,$author);
                   2627:         my $home=homeserver($uname,$udom);
                   2628:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2629:            my @parts=split(/\//,$filename);
                   2630:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2631:            if ($path ne "$londocroot/res") {
1.8       www      2632:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2633: 	       return 'bad_request';
1.8       www      2634:            }
                   2635:            my $count;
                   2636:            for ($count=5;$count<$#parts;$count++) {
                   2637:                $path.="/$parts[$count]";
                   2638:                if ((-e $path)!=1) {
                   2639: 		   mkdir($path,0777);
                   2640:                }
                   2641:            }
                   2642:            my $ua=new LWP::UserAgent;
                   2643:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2644:            my $response=$ua->request($request,$transname);
                   2645:            if ($response->is_error()) {
                   2646: 	       unlink($transname);
                   2647:                my $message=$response->status_line;
1.672     albertel 2648:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2649:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2650:                return 'unavailable';
1.8       www      2651:            } else {
1.16      www      2652: 	       if ($remoteurl!~/\.meta$/) {
                   2653:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2654:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2655:                   if ($mresponse->is_error()) {
                   2656: 		      unlink($filename.'.meta');
                   2657:                       &logthis(
1.672     albertel 2658:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2659:                   }
                   2660: 	       }
1.8       www      2661:                rename($transname,$filename);
1.607     raeburn  2662:                return 'ok';
1.8       www      2663:            }
1.290     www      2664:        }
1.8       www      2665:     }
1.330     www      2666: }
                   2667: 
                   2668: # ------------------------------------------------ Get server side include body
                   2669: sub ssi_body {
1.381     albertel 2670:     my ($filelink,%form)=@_;
1.606     matthew  2671:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2672:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2673:     }
1.953     www      2674:     my $output='';
                   2675:     my $response;
1.980     raeburn  2676:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2677:        ($output,$response)=&externalssi($filelink);
1.953     www      2678:     } else {
1.1004    droeschl 2679:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2680:        $filelink .= 'inhibitmenu=yes';
1.953     www      2681:        ($output,$response)=&ssi($filelink,%form);
                   2682:     }
1.778     albertel 2683:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2684:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2685:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2686:     if (wantarray) {
                   2687:         return ($output, $response);
                   2688:     } else {
                   2689:         return $output;
                   2690:     }
1.8       www      2691: }
                   2692: 
1.15      www      2693: # --------------------------------------------------------- Server Side Include
                   2694: 
1.782     albertel 2695: sub absolute_url {
                   2696:     my ($host_name) = @_;
                   2697:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2698:     if ($host_name eq '') {
                   2699: 	$host_name = $ENV{'SERVER_NAME'};
                   2700:     }
                   2701:     return $protocol.$host_name;
                   2702: }
                   2703: 
1.942     foxr     2704: #
                   2705: #   Server side include.
                   2706: # Parameters:
                   2707: #  fn     Possibly encrypted resource name/id.
                   2708: #  form   Hash that describes how the rendering should be done
                   2709: #         and other things.
1.944     foxr     2710: # Returns:
1.950     raeburn  2711: #   Scalar context: The content of the response.
                   2712: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2713: #     
1.15      www      2714: sub ssi {
                   2715: 
1.944     foxr     2716:     my ($fn,%form)=@_;
1.15      www      2717:     my $ua=new LWP::UserAgent;
1.23      www      2718:     my $request;
1.711     albertel 2719: 
                   2720:     $form{'no_update_last_known'}=1;
1.895     albertel 2721:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2722:     if (%form) {
1.782     albertel 2723:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2724:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2725:     } else {
1.782     albertel 2726:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2727:     }
                   2728: 
1.15      www      2729:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2730:     my $response= $ua->request($request);
1.1182    foxr     2731:     my $content = $response->content;
                   2732: 
                   2733: 
1.944     foxr     2734:     if (wantarray) {
1.1173    foxr     2735: 	return ($content, $response);
1.944     foxr     2736:     } else {
1.1173    foxr     2737: 	return $content;
1.942     foxr     2738:     }
1.324     www      2739: }
                   2740: 
                   2741: sub externalssi {
                   2742:     my ($url)=@_;
                   2743:     my $ua=new LWP::UserAgent;
                   2744:     my $request=new HTTP::Request('GET',$url);
                   2745:     my $response=$ua->request($request);
1.954     raeburn  2746:     if (wantarray) {
                   2747:         return ($response->content, $response);
                   2748:     } else {
                   2749:         return $response->content;
                   2750:     }
1.15      www      2751: }
1.254     www      2752: 
1.492     albertel 2753: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2754: 
                   2755: sub allowuploaded {
                   2756:     my ($srcurl,$url)=@_;
                   2757:     $url=&clutter(&declutter($url));
                   2758:     my $dir=$url;
                   2759:     $dir=~s/\/[^\/]+$//;
                   2760:     my %httpref=();
                   2761:     my $httpurl=&hreflocation('',$url);
                   2762:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2763:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2764: }
1.477     raeburn  2765: 
1.1193    raeburn  2766: #
                   2767: # Determine if the current user should be able to edit a particular resource,
                   2768: # when viewing in course context.
                   2769: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2770: #     Functions.
                   2771: # (b) When displaying folder contents in course editor, used to determine if
                   2772: #     "Edit" link will be displayed alongside resource.
                   2773: #
1.1196    raeburn  2774: #  input: six args -- filename (decluttered), course number, course domain,
                   2775: #                   url, symb (if registered) and group (if this is a group
                   2776: #                   item -- e.g., bulletin board, group page etc.).
                   2777: #  output: array of five scalars -- 
1.1193    raeburn  2778: #          $cfile -- url for file editing if editable on current server
                   2779: #          $home -- homeserver of resource (i.e., for author if published,
                   2780: #                                           or course if uploaded.).
                   2781: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2782: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2783: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2784: #
                   2785: 
                   2786: sub can_edit_resource {
1.1194    raeburn  2787:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2788:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2789: #
                   2790: # For aboutme pages user can only edit his/her own.
                   2791: #
1.1199    raeburn  2792:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2793:         my ($sdom,$sname) = ($1,$2);
                   2794:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2795:             $home = $env{'user.home'};
                   2796:             $cfile = $resurl;
                   2797:             if ($env{'form.forceedit'}) {
                   2798:                 $forceview = 1;
                   2799:             } else {
                   2800:                 $forceedit = 1;
                   2801:             }
                   2802:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2803:         } else {
                   2804:             return;
                   2805:         }
                   2806:     }
                   2807: 
                   2808:     if ($env{'request.course.id'}) {
                   2809:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2810:         if ($group ne '') {
                   2811: # if this is a group homepage or group bulletin board, check group privs
                   2812:             my $allowed = 0;
1.1197    raeburn  2813:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2814:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2815:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2816:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2817:                     $allowed = 1;
                   2818:                 }
1.1197    raeburn  2819:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2820:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2821:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2822:                     $allowed = 1;
                   2823:                 }
                   2824:             }
                   2825:             if ($allowed) {
                   2826:                 $home=&homeserver($cnum,$cdom);
                   2827:                 if ($env{'form.forceedit'}) {
                   2828:                     $forceview = 1;
                   2829:                 } else {
                   2830:                     $forceedit = 1;
                   2831:                 }
                   2832:                 $cfile = $resurl;
                   2833:             } else {
                   2834:                 return;
                   2835:             }
                   2836:         } else {
1.1208    raeburn  2837:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2838:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2839:                     return;
                   2840:                 }
                   2841:             } elsif (!$crsedit) {
1.1194    raeburn  2842: #
                   2843: # No edit allowed where CC has switched to student role.
                   2844: #
                   2845:                 return;
                   2846:             }
                   2847:         }
                   2848:     }
                   2849: 
1.1193    raeburn  2850:     if ($file ne '') {
                   2851:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2852:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2853:                 $uploaded = 1;
                   2854:                 $incourse = 1;
1.1193    raeburn  2855:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2856:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2857:                     if ($env{'form.forceedit'}) {
                   2858:                         $forceview = 1;
                   2859:                     } else {
                   2860:                         $forceedit = 1;
                   2861:                     }
1.1194    raeburn  2862:                 }
                   2863:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2864:                 $incourse = 1;
                   2865:                 if ($env{'form.forceedit'}) {
                   2866:                     $forceview = 1;
                   2867:                 } else {
                   2868:                     $forceedit = 1;
                   2869:                 }
                   2870:                 $cfile = $resurl;
                   2871:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2872:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2873:                     $incourse = 1;
                   2874:                     if ($env{'form.forceedit'}) {
                   2875:                         $forceview = 1;
                   2876:                     } else {
                   2877:                         $forceedit = 1;
                   2878:                     }
                   2879:                     $cfile = $resurl;
1.1199    raeburn  2880:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2881:                     $incourse = 1;
                   2882:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2883:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2884:                     $incourse = 1;
1.1199    raeburn  2885:                     if ($env{'form.forceedit'}) {
                   2886:                         $forceview = 1;
                   2887:                     } else {
                   2888:                         $forceedit = 1;
                   2889:                     }
                   2890:                     $cfile = $resurl;
1.1208    raeburn  2891:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2892:                     $incourse = 1;
                   2893:                     if ($env{'form.forceedit'}) {
                   2894:                         $forceview = 1;
                   2895:                     } else {
                   2896:                         $forceedit = 1;
                   2897:                     }
                   2898:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2899:                 }
                   2900:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2901:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2902:                 if (&is_on_map($template)) { 
                   2903:                     $incourse = 1;
                   2904:                     $forceview = 1;
                   2905:                     $cfile = $template;
1.1193    raeburn  2906:                 }
1.1199    raeburn  2907:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2908:                     $incourse = 1;
                   2909:                     if ($env{'form.forceedit'}) {
                   2910:                         $forceview = 1;
                   2911:                     } else {
                   2912:                         $forceedit = 1;
                   2913:                     }
                   2914:                     $cfile = $resurl;
                   2915:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2916:                 $incourse = 1;
                   2917:                 $forceview = 1;
                   2918:                 if ($symb) {
                   2919:                     my ($map,$id,$res)=&decode_symb($symb);
                   2920:                     $env{'request.symb'} = $symb;
                   2921:                     $cfile = &clutter($res);
                   2922:                 } else {
                   2923:                     $cfile = $env{'form.suppurl'};
                   2924:                     $cfile =~ s{^http://}{};
                   2925:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2926:                 }
1.1234    raeburn  2927:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2928:                 if ($env{'form.forceedit'}) {
                   2929:                     $forceview = 1;
                   2930:                 } else {
                   2931:                     $forceedit = 1;
                   2932:                 }
                   2933:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  2934:             }
                   2935:         }
1.1194    raeburn  2936:         if ($uploaded || $incourse) {
                   2937:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2938:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2939:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2940:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2941:             # Check that the user has permission to edit this resource
                   2942:             my $setpriv = 1;
                   2943:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2944:             if (defined($cfudom)) {
                   2945:                 $home=&homeserver($cfuname,$cfudom);
                   2946:                 $cfile=$file;
                   2947:             }
                   2948:         }
1.1194    raeburn  2949:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2950:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2951:             my @ids=&current_machine_ids();
                   2952:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2953:                 $switchserver=1;
                   2954:             }
                   2955:         }
                   2956:     }
1.1194    raeburn  2957:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2958: }
                   2959: 
                   2960: sub is_course_upload {
                   2961:     my ($file,$cnum,$cdom) = @_;
                   2962:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2963:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2964:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2965:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2966:         return 1;
                   2967:     }
                   2968:     return;
                   2969: }
                   2970: 
1.1194    raeburn  2971: sub in_course {
1.1195    raeburn  2972:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2973:     if ($hideprivileged) {
                   2974:         my $skipuser;
1.1219    raeburn  2975:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2976:         my @possdoms = ($cdom);  
                   2977:         if ($coursehash{'checkforpriv'}) { 
                   2978:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   2979:         }
                   2980:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  2981:             $skipuser = 1;
                   2982:             if ($coursehash{'nothideprivileged'}) {
                   2983:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2984:                     my $user;
                   2985:                     if ($item =~ /:/) {
                   2986:                         $user = $item;
                   2987:                     } else {
                   2988:                         $user = join(':',split(/[\@]/,$item));
                   2989:                     }
                   2990:                     if ($user eq $uname.':'.$udom) {
                   2991:                         undef($skipuser);
                   2992:                         last;
                   2993:                     }
                   2994:                 }
                   2995:             }
                   2996:             if ($skipuser) {
                   2997:                 return 0;
                   2998:             }
                   2999:         }
                   3000:     }
1.1194    raeburn  3001:     $type ||= 'any';
                   3002:     if (!defined($cdom) || !defined($cnum)) {
                   3003:         my $cid  = $env{'request.course.id'};
                   3004:         $cdom = $env{'course.'.$cid.'.domain'};
                   3005:         $cnum = $env{'course.'.$cid.'.num'};
                   3006:     }
                   3007:     my $typesref;
1.1195    raeburn  3008:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3009:         $typesref = ['active','previous','future'];
                   3010:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3011:         $typesref = [$type];
                   3012:     }
                   3013:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3014:                               $typesref,undef,[$cdom]);
                   3015:     my ($tmp) = keys(%roles);
                   3016:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3017:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3018:     if (@course_roles > 0) {
                   3019:         return 1;
                   3020:     }
                   3021:     return 0;
                   3022: }
                   3023: 
1.478     albertel 3024: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3025: # input: action, courseID, current domain, intended
1.637     raeburn  3026: #        path to file, source of file, instruction to parse file for objects,
                   3027: #        ref to hash for embedded objects,
                   3028: #        ref to hash for codebase of java objects.
1.1095    raeburn  3029: #        reference to scalar to accommodate mime type determined
                   3030: #          from File::MMagic if $parser = parse.
1.637     raeburn  3031: #
1.485     raeburn  3032: # output: url to file (if action was uploaddoc), 
                   3033: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3034: #
1.478     albertel 3035: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3036: # course.
1.477     raeburn  3037: #
1.478     albertel 3038: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3039: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3040: #          course's home server.
1.477     raeburn  3041: #
1.478     albertel 3042: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3043: #          be copied from $source (current location) to 
                   3044: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3045: #         and will then be copied to
                   3046: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3047: #         course's home server.
1.485     raeburn  3048: #
1.481     raeburn  3049: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3050: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3051: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3052: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3053: #         in course's home server.
1.637     raeburn  3054: #
1.477     raeburn  3055: 
                   3056: sub process_coursefile {
1.1095    raeburn  3057:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3058:         $mimetype)=@_;
1.477     raeburn  3059:     my $fetchresult;
1.638     albertel 3060:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3061:     if ($action eq 'propagate') {
1.638     albertel 3062:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3063: 			     $home);
1.481     raeburn  3064:     } else {
1.477     raeburn  3065:         my $fpath = '';
                   3066:         my $fname = $file;
1.478     albertel 3067:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3068:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3069:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3070:         if ($action eq 'copy') {
                   3071:             if ($source eq '') {
                   3072:                 $fetchresult = 'no source file';
                   3073:                 return $fetchresult;
                   3074:             } else {
                   3075:                 my $destination = $filepath.'/'.$fname;
                   3076:                 rename($source,$destination);
                   3077:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3078:                                  $home);
1.481     raeburn  3079:             }
                   3080:         } elsif ($action eq 'uploaddoc') {
                   3081:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3082:             print $fh $env{'form.'.$source};
1.481     raeburn  3083:             close($fh);
1.637     raeburn  3084:             if ($parser eq 'parse') {
1.1024    raeburn  3085:                 my $mm = new File::MMagic;
1.1095    raeburn  3086:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3087:                 if ($type eq 'text/html') {
1.1024    raeburn  3088:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3089:                     unless ($parse_result eq 'ok') {
                   3090:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3091:                     }
1.637     raeburn  3092:                 }
1.1095    raeburn  3093:                 if (ref($mimetype)) {
                   3094:                     $$mimetype = $type;
                   3095:                 } 
1.637     raeburn  3096:             }
1.477     raeburn  3097:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3098:                                  $home);
1.481     raeburn  3099:             if ($fetchresult eq 'ok') {
                   3100:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3101:             } else {
                   3102:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3103:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3104:                 return '/adm/notfound.html';
                   3105:             }
1.477     raeburn  3106:         }
                   3107:     }
1.485     raeburn  3108:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3109:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3110:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3111:     }
                   3112:     return $fetchresult;
                   3113: }
                   3114: 
1.637     raeburn  3115: sub build_filepath {
                   3116:     my ($fpath) = @_;
                   3117:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3118:     unless ($fpath eq '') {
                   3119:         my @parts=split('/',$fpath);
                   3120:         foreach my $part (@parts) {
                   3121:             $filepath.= '/'.$part;
                   3122:             if ((-e $filepath)!=1) {
                   3123:                 mkdir($filepath,0777);
                   3124:             }
                   3125:         }
                   3126:     }
                   3127:     return $filepath;
                   3128: }
                   3129: 
                   3130: sub store_edited_file {
1.638     albertel 3131:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3132:     my $file = $primary_url;
                   3133:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3134:     my $fpath = '';
                   3135:     my $fname = $file;
                   3136:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3137:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3138:     my $filepath = &build_filepath($fpath);
                   3139:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3140:     print $fh $content;
                   3141:     close($fh);
1.638     albertel 3142:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3143:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3144: 			  $home);
1.637     raeburn  3145:     if ($$fetchresult eq 'ok') {
                   3146:         return '/uploaded/'.$fpath.'/'.$fname;
                   3147:     } else {
1.638     albertel 3148:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3149: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3150:         return '/adm/notfound.html';
                   3151:     }
                   3152: }
                   3153: 
1.531     albertel 3154: sub clean_filename {
1.831     albertel 3155:     my ($fname,$args)=@_;
1.315     www      3156: # Replace Windows backslashes by forward slashes
1.257     www      3157:     $fname=~s/\\/\//g;
1.831     albertel 3158:     if (!$args->{'keep_path'}) {
                   3159:         # Get rid of everything but the actual filename
                   3160: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3161:     }
1.315     www      3162: # Replace spaces by underscores
                   3163:     $fname=~s/\s+/\_/g;
                   3164: # Replace all other weird characters by nothing
1.831     albertel 3165:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3166: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3167: # numbers
                   3168:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3169:     return $fname;
                   3170: }
1.1051    raeburn  3171: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3172: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3173: # image with the same aspect ratio as the original, but with dimensions which do 
                   3174: # not exceed $resizewidth and $resizeheight.
                   3175:  
1.984     neumanie 3176: sub resizeImage {
1.1051    raeburn  3177:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3178:     my $ima = Image::Magick->new;
                   3179:     my $resized;
                   3180:     if (-e $img_path) {
                   3181:         $ima->Read($img_path);
                   3182:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3183:             my $width = $ima->Get('width');
                   3184:             my $height = $ima->Get('height');
                   3185:             if ($width > $resizewidth) {
                   3186: 	        my $factor = $width/$resizewidth;
                   3187:                 my $newheight = $height/$factor;
                   3188:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3189:                 $resized = 1;
                   3190:             }
                   3191:         }
                   3192:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3193:             my $width = $ima->Get('width');
                   3194:             my $height = $ima->Get('height');
                   3195:             if ($height > $resizeheight) {
                   3196:                 my $factor = $height/$resizeheight;
                   3197:                 my $newwidth = $width/$factor;
                   3198:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3199:                 $resized = 1;
                   3200:             }
                   3201:         }
                   3202:         if ($resized) {
                   3203:             $ima->Write($img_path);
                   3204:         }
                   3205:     }
                   3206:     return;
1.977     amueller 3207: }
                   3208: 
1.608     albertel 3209: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3210: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3211: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3212: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3213: #                                    canceloverwrite, or ''. 
                   3214: #                   if 'coursedoc': upload to the current course
                   3215: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3216: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3217: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3218: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3219: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3220: #        $allfiles - reference to hash for embedded objects
                   3221: #        $codebase - reference to hash for codebase of java objects
                   3222: #        $desuname - username for permanent storage of uploaded file
                   3223: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3224: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3225: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3226: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3227: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3228: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3229: #                    from File::MMagic.
1.858     raeburn  3230: # 
1.686     albertel 3231: # output: url of file in userspace, or error: <message> 
                   3232: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3233: 
1.531     albertel 3234: sub userfileupload {
1.1090    raeburn  3235:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3236:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3237:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3238:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3239:     $fname=&clean_filename($fname);
1.1090    raeburn  3240:     # See if there is anything left
1.257     www      3241:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3242:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3243:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3244:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3245:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3246:         my $now = time;
1.1090    raeburn  3247:         my $filepath;
1.1095    raeburn  3248:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3249:              $filepath = 'tmp/helprequests/'.$now;
                   3250:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3251:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3252:                          '_'.$env{'user.domain'}.'/pending';
                   3253:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3254:             my ($docuname,$docudom);
                   3255:             if ($destudom) {
                   3256:                 $docudom = $destudom;
                   3257:             } else {
                   3258:                 $docudom = $env{'user.domain'};
                   3259:             }
                   3260:             if ($destuname) {
                   3261:                 $docuname = $destuname;
                   3262:             } else {
                   3263:                 $docuname = $env{'user.name'};
                   3264:             }
                   3265:             if (exists($env{'form.group'})) {
                   3266:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3267:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3268:             }
                   3269:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3270:             if ($context eq 'canceloverwrite') {
                   3271:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3272:                 if (-e  $tempfile) {
                   3273:                     my @info = stat($tempfile);
                   3274:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3275:                         unlink($tempfile);
                   3276:                     }
                   3277:                 }
                   3278:                 return;
1.523     raeburn  3279:             }
                   3280:         }
1.1090    raeburn  3281:         # Create the directory if not present
1.741     raeburn  3282:         my @parts=split(/\//,$filepath);
                   3283:         my $fullpath = $perlvar{'lonDaemons'};
                   3284:         for (my $i=0;$i<@parts;$i++) {
                   3285:             $fullpath .= '/'.$parts[$i];
                   3286:             if ((-e $fullpath)!=1) {
                   3287:                 mkdir($fullpath,0777);
                   3288:             }
                   3289:         }
                   3290:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3291:         print $fh $env{'form.'.$formname};
                   3292:         close($fh);
1.1090    raeburn  3293:         if ($context eq 'existingfile') {
                   3294:             my @info = stat($fullpath.'/'.$fname);
                   3295:             return ($fullpath.'/'.$fname,$info[9]);
                   3296:         } else {
                   3297:             return $fullpath.'/'.$fname;
                   3298:         }
1.523     raeburn  3299:     }
1.995     raeburn  3300:     if ($subdir eq 'scantron') {
                   3301:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3302:     } else {
1.995     raeburn  3303:         $fname="$subdir/$fname";
                   3304:     }
1.1090    raeburn  3305:     if ($context eq 'coursedoc') {
1.638     albertel 3306: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3307: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3308:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3309:             return &finishuserfileupload($docuname,$docudom,
                   3310: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3311: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3312:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3313:         } else {
1.1218    raeburn  3314:             if ($env{'form.folder'}) {
                   3315:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3316:             }
1.638     albertel 3317:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3318: 				       $fname,$formname,$parser,
1.1095    raeburn  3319: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3320:         }
1.719     banghart 3321:     } elsif (defined($destuname)) {
                   3322:         my $docuname=$destuname;
                   3323:         my $docudom=$destudom;
1.860     raeburn  3324: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3325: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3326:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3327:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3328:     } else {
1.638     albertel 3329:         my $docuname=$env{'user.name'};
                   3330:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3331:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3332:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3333:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3334:         }
1.860     raeburn  3335: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3336: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3337:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3338:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3339:     }
1.271     www      3340: }
                   3341: 
                   3342: sub finishuserfileupload {
1.860     raeburn  3343:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3344:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3345:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3346:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3347:   
1.860     raeburn  3348:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3349:     $file=$fname;
                   3350:     if ($fname=~m|/|) {
                   3351:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3352: 	$path.=$fnamepath.'/';
                   3353:     }
1.259     www      3354:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3355:     my $count;
                   3356:     for ($count=4;$count<=$#parts;$count++) {
                   3357:         $filepath.="/$parts[$count]";
                   3358:         if ((-e $filepath)!=1) {
                   3359: 	    mkdir($filepath,0777);
                   3360:         }
                   3361:     }
1.984     neumanie 3362: 
1.258     www      3363: # Save the file
                   3364:     {
1.701     albertel 3365: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3366: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3367: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3368: 	    return '/adm/notfound.html';
                   3369: 	}
1.1090    raeburn  3370:         if ($context eq 'overwrite') {
1.1117    foxr     3371:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3372:             my $target = $filepath.'/'.$file;
                   3373:             if (-e $source) {
                   3374:                 my @info = stat($source);
                   3375:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3376:                     unless (&File::Copy::move($source,$target)) {
                   3377:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3378:                         return "Moving from $source failed";
                   3379:                     }
                   3380:                 } else {
                   3381:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3382:                 }
                   3383:             } else {
                   3384:                 return "Temporary file: $source missing";
                   3385:             }
                   3386:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3387: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3388: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3389: 	    return '/adm/notfound.html';
                   3390: 	}
1.570     albertel 3391: 	close(FH);
1.1051    raeburn  3392:         if ($resizewidth && $resizeheight) {
                   3393:             my $mm = new File::MMagic;
                   3394:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3395:             if ($mime_type =~ m{^image/}) {
                   3396: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3397:             }  
1.977     amueller 3398: 	}
1.258     www      3399:     }
1.1152    raeburn  3400:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3401:         if (ref($mimetype)) {
                   3402:             if ($$mimetype eq '') {
                   3403:                 my $mm = new File::MMagic;
                   3404:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3405:                 $$mimetype = $type;
                   3406:             }
                   3407:         }
                   3408:     }
1.637     raeburn  3409:     if ($parser eq 'parse') {
1.1152    raeburn  3410:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3411:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3412:                                                        $allfiles,$codebase);
                   3413:             unless ($parse_result eq 'ok') {
                   3414:                 &logthis('Failed to parse '.$filepath.$file.
                   3415: 	   	         ' for embedded media: '.$parse_result); 
                   3416:             }
1.637     raeburn  3417:         }
                   3418:     }
1.860     raeburn  3419:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3420:         my $input = $filepath.'/'.$file;
                   3421:         my $output = $filepath.'/'.'tn-'.$file;
                   3422:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3423:         system("convert -sample $thumbsize $input $output");
                   3424:         if (-e $filepath.'/'.'tn-'.$file) {
                   3425:             $fetchthumb  = 1; 
                   3426:         }
                   3427:     }
1.858     raeburn  3428:  
1.259     www      3429: # Notify homeserver to grep it
                   3430: #
1.984     neumanie 3431:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3432:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3433:     if ($fetchresult eq 'ok') {
1.860     raeburn  3434:         if ($fetchthumb) {
                   3435:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3436:             if ($thumbresult ne 'ok') {
                   3437:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3438:                          $docuhome.': '.$thumbresult);
                   3439:             }
                   3440:         }
1.259     www      3441: #
1.258     www      3442: # Return the URL to it
1.494     albertel 3443:         return '/uploaded/'.$path.$file;
1.263     www      3444:     } else {
1.494     albertel 3445:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3446: 		 ': '.$fetchresult);
1.263     www      3447:         return '/adm/notfound.html';
1.858     raeburn  3448:     }
1.493     albertel 3449: }
                   3450: 
1.637     raeburn  3451: sub extract_embedded_items {
1.961     raeburn  3452:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3453:     my @state = ();
1.1164    raeburn  3454:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3455:     my %javafiles = (
                   3456:                       codebase => '',
                   3457:                       code => '',
                   3458:                       archive => ''
                   3459:                     );
                   3460:     my %mediafiles = (
                   3461:                       src => '',
                   3462:                       movie => '',
                   3463:                      );
1.648     raeburn  3464:     my $p;
                   3465:     if ($content) {
                   3466:         $p = HTML::LCParser->new($content);
                   3467:     } else {
1.961     raeburn  3468:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3469:     }
1.641     albertel 3470:     while (my $t=$p->get_token()) {
1.640     albertel 3471: 	if ($t->[0] eq 'S') {
                   3472: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3473: 	    push(@state, $tagname);
1.648     raeburn  3474:             if (lc($tagname) eq 'allow') {
                   3475:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3476:             }
1.640     albertel 3477: 	    if (lc($tagname) eq 'img') {
                   3478: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3479: 	    }
1.886     albertel 3480: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3481:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3482:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3483:                 }
1.886     albertel 3484: 	    }
1.645     raeburn  3485:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3486:                 my $src;
1.645     raeburn  3487:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3488:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3489:                 } else {
1.1164    raeburn  3490:                     if ($attr->{'src'} ne '') {
                   3491:                         $src = $attr->{'src'};
                   3492:                         &add_filetype($allfiles,$src,'src');
                   3493:                     }
                   3494:                 }
                   3495:                 my $text = $p->get_trimmed_text();
                   3496:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3497:                     my @swfargs = split(/,/,$1);
                   3498:                     foreach my $item (@swfargs) {
                   3499:                         $item =~ s/["']//g;
                   3500:                         $item =~ s/^\s+//;
                   3501:                         $item =~ s/\s+$//;
                   3502:                     }
                   3503:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3504:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3505:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3506:                         } else {
                   3507:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3508:                         }
                   3509:                     }
1.645     raeburn  3510:                 }
                   3511:             }
                   3512:             if (lc($tagname) eq 'link') {
                   3513:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3514:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3515:                 }
                   3516:             }
1.640     albertel 3517: 	    if (lc($tagname) eq 'object' ||
                   3518: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3519: 		foreach my $item (keys(%javafiles)) {
                   3520: 		    $javafiles{$item} = '';
                   3521: 		}
1.1164    raeburn  3522:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3523:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3524:                 }
1.640     albertel 3525: 	    }
                   3526: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3527: 		my $name = lc($attr->{'name'});
                   3528: 		foreach my $item (keys(%javafiles)) {
                   3529: 		    if ($name eq $item) {
                   3530: 			$javafiles{$item} = $attr->{'value'};
                   3531: 			last;
                   3532: 		    }
                   3533: 		}
1.1164    raeburn  3534:                 my $pathfrom;
1.640     albertel 3535: 		foreach my $item (keys(%mediafiles)) {
                   3536: 		    if ($name eq $item) {
1.1164    raeburn  3537:                         $pathfrom = $attr->{'value'};
                   3538:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3539: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3540: 			last;
                   3541: 		    }
                   3542: 		}
1.1164    raeburn  3543:                 if ($name eq 'flashvars') {
                   3544:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3545:                 }
                   3546:                 if ($pathfrom ne '') {
                   3547:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3548:                                          $pathfrom);
                   3549:                 }
1.640     albertel 3550: 	    }
                   3551: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3552: 		foreach my $item (keys(%javafiles)) {
                   3553: 		    if ($attr->{$item}) {
                   3554: 			$javafiles{$item} = $attr->{$item};
                   3555: 			last;
                   3556: 		    }
                   3557: 		}
                   3558: 		foreach my $item (keys(%mediafiles)) {
                   3559: 		    if ($attr->{$item}) {
                   3560: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3561: 			last;
                   3562: 		    }
                   3563: 		}
1.1164    raeburn  3564:                 if (lc($tagname) eq 'embed') {
                   3565:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3566:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3567:                                              $attr->{'src'});
                   3568:                     }
                   3569:                 }
1.640     albertel 3570: 	    }
1.1243    raeburn  3571:             if (lc($tagname) eq 'iframe') {
                   3572:                 my $src = $attr->{'src'} ;
                   3573:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3574:                     &add_filetype($allfiles,$src,'src');
                   3575:                 } elsif ($src =~ m{^/}) {
                   3576:                     if ($env{'request.course.id'}) {
                   3577:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3578:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3579:                         my $url = &hreflocation('',$fullpath);
                   3580:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3581:                             my $relpath = $1;
                   3582:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3583:                                 &add_filetype($allfiles,$1,'src');
                   3584:                             }
                   3585:                         }
                   3586:                     }
                   3587:                 }
                   3588:             }
1.1164    raeburn  3589:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3590:                 pop(@state);
1.1164    raeburn  3591:             }
1.640     albertel 3592: 	} elsif ($t->[0] eq 'E') {
                   3593: 	    my ($tagname) = ($t->[1]);
                   3594: 	    if ($javafiles{'codebase'} ne '') {
                   3595: 		$javafiles{'codebase'} .= '/';
                   3596: 	    }  
                   3597: 	    if (lc($tagname) eq 'applet' ||
                   3598: 		lc($tagname) eq 'object' ||
                   3599: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3600: 		) {
                   3601: 		foreach my $item (keys(%javafiles)) {
                   3602: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3603: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3604: 			&add_filetype($allfiles,$file,$item);
                   3605: 		    }
                   3606: 		}
                   3607: 	    } 
                   3608: 	    pop @state;
                   3609: 	}
                   3610:     }
1.1164    raeburn  3611:     foreach my $id (sort(keys(%flashvars))) {
                   3612:         if ($shockwave{$id} ne '') {
                   3613:             my @pairs = split(/\&/,$flashvars{$id});
                   3614:             foreach my $pair (@pairs) {
                   3615:                 my ($key,$value) = split(/\=/,$pair);
                   3616:                 if ($key eq 'thumb') {
                   3617:                     &add_filetype($allfiles,$value,$key);
                   3618:                 } elsif ($key eq 'content') {
                   3619:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3620:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3621:                     if ($ext ne '') {
                   3622:                         &add_filetype($allfiles,$path.$value,$ext);
                   3623:                     }
                   3624:                 }
                   3625:             }
                   3626:         }
                   3627:     }
1.637     raeburn  3628:     return 'ok';
                   3629: }
                   3630: 
1.639     albertel 3631: sub add_filetype {
                   3632:     my ($allfiles,$file,$type)=@_;
                   3633:     if (exists($allfiles->{$file})) {
                   3634: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3635: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3636: 	}
                   3637:     } else {
                   3638: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3639:     }
                   3640: }
                   3641: 
1.1164    raeburn  3642: sub embedded_dependency {
                   3643:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3644:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3645:         if (($identifier ne '') &&
                   3646:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3647:             ($pathfrom ne '')) {
                   3648:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3649:             foreach my $dep (@{$related->{$identifier}}) {
                   3650:                 &add_filetype($allfiles,$path.$dep,'object');
                   3651:             }
                   3652:         }
                   3653:     }
                   3654:     return;
                   3655: }
                   3656: 
1.493     albertel 3657: sub removeuploadedurl {
1.984     neumanie 3658:     my ($url)=@_;	
                   3659:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3660:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3661: }
                   3662: 
                   3663: sub removeuserfile {
                   3664:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3665:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3666:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3667:     if ($result eq 'ok') {	
1.798     raeburn  3668:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3669:             my $metafile = $fname.'.meta';
                   3670:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3671: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3672:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3673:             my $sqlresult = 
1.823     albertel 3674:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3675:                                         'portfolio_metadata',$group,
                   3676:                                         'delete');
1.798     raeburn  3677:         }
                   3678:     }
                   3679:     return $result;
1.257     www      3680: }
1.15      www      3681: 
1.530     albertel 3682: sub mkdiruserfile {
                   3683:     my ($docuname,$docudom,$dir)=@_;
                   3684:     my $home=&homeserver($docuname,$docudom);
                   3685:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3686: }
                   3687: 
1.531     albertel 3688: sub renameuserfile {
                   3689:     my ($docuname,$docudom,$old,$new)=@_;
                   3690:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3691:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3692:                         &escape("$old").':'.&escape("$new"),$home);
                   3693:     if ($result eq 'ok') {
                   3694:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3695:             my $oldmeta = $old.'.meta';
                   3696:             my $newmeta = $new.'.meta';
                   3697:             my $metaresult = 
                   3698:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3699: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3700:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3701:             my $sqlresult = 
1.823     albertel 3702:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3703:                                         'portfolio_metadata',$group,
                   3704:                                         'delete');
1.798     raeburn  3705:         }
                   3706:     }
                   3707:     return $result;
1.531     albertel 3708: }
                   3709: 
1.14      www      3710: # ------------------------------------------------------------------------- Log
                   3711: 
                   3712: sub log {
                   3713:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3714:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3715: }
                   3716: 
                   3717: # ------------------------------------------------------------------ Course Log
1.352     www      3718: #
                   3719: # This routine flushes several buffers of non-mission-critical nature
                   3720: #
1.157     www      3721: 
                   3722: sub flushcourselogs {
1.352     www      3723:     &logthis('Flushing log buffers');
                   3724: #
                   3725: # course logs
                   3726: # This is a log of all transactions in a course, which can be used
                   3727: # for data mining purposes
                   3728: #
                   3729: # It also collects the courseid database, which lists last transaction
                   3730: # times and course titles for all courseids
                   3731: #
                   3732:     my %courseidbuffer=();
1.921     raeburn  3733:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3734:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3735: 		          &escape($courselogs{$crsid}),
                   3736: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3737: 	    delete $courselogs{$crsid};
                   3738:         } else {
                   3739:             &logthis('Failed to flush log buffer for '.$crsid);
                   3740:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3741:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3742:                         " exceeded maximum size, deleting.</font>");
                   3743:                delete $courselogs{$crsid};
                   3744:             }
1.352     www      3745:         }
1.920     raeburn  3746:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3747:             'description' => $coursedescrbuf{$crsid},
                   3748:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3749:             'type'        => $coursetypebuf{$crsid},
                   3750:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3751:         };
1.191     harris41 3752:     }
1.352     www      3753: #
                   3754: # Write course id database (reverse lookup) to homeserver of courses 
                   3755: # Is used in pickcourse
                   3756: #
1.840     albertel 3757:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3758:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3759:                                     $courseidbuffer{$crs_home},
                   3760:                                     $crs_home,'timeonly');
1.352     www      3761:     }
                   3762: #
                   3763: # File accesses
                   3764: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3765: #
1.449     matthew  3766:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3767:         if ($entry =~ /___count$/) {
                   3768:             my ($dom,$name);
1.807     albertel 3769:             ($dom,$name,undef)=
1.811     albertel 3770: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3771:             if (! defined($dom) || $dom eq '' || 
                   3772:                 ! defined($name) || $name eq '') {
1.620     albertel 3773:                 my $cid = $env{'request.course.id'};
                   3774:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3775:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3776:             }
1.450     matthew  3777:             my $value = $accesshash{$entry};
                   3778:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3779:             my %temphash=($url => $value);
1.449     matthew  3780:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3781:             if ($result eq 'ok') {
                   3782:                 delete $accesshash{$entry};
                   3783:             }
                   3784:         } else {
1.811     albertel 3785:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3786:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3787:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3788:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3789:                 delete $accesshash{$entry};
                   3790:             }
1.185     www      3791:         }
1.191     harris41 3792:     }
1.352     www      3793: #
                   3794: # Roles
                   3795: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3796: #
1.800     albertel 3797:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3798:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3799: 	    split(/\:/,$entry);
                   3800:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3801:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3802:                 $rudom,$runame) eq 'ok') {
                   3803: 	    delete $userrolehash{$entry};
                   3804:         }
                   3805:     }
1.662     raeburn  3806: #
                   3807: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3808: #
                   3809:     my %domrolebuffer = ();
1.1000    raeburn  3810:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3811:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3812:         if ($domrolebuffer{$rudom}) {
                   3813:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3814:                       '='.&escape($domainrolehash{$entry});
                   3815:         } else {
                   3816:             $domrolebuffer{$rudom}.=&escape($entry).
                   3817:                       '='.&escape($domainrolehash{$entry});
                   3818:         }
                   3819:         delete $domainrolehash{$entry};
                   3820:     }
                   3821:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3822: 	my %servers = &get_servers($dom,'library');
                   3823: 	foreach my $tryserver (keys(%servers)) {
                   3824: 	    unless (&reply('domroleput:'.$dom.':'.
                   3825: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3826: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3827: 	    }
1.662     raeburn  3828:         }
                   3829:     }
1.186     www      3830:     $dumpcount++;
1.157     www      3831: }
                   3832: 
                   3833: sub courselog {
                   3834:     my $what=shift;
1.158     www      3835:     $what=time.':'.$what;
1.620     albertel 3836:     unless ($env{'request.course.id'}) { return ''; }
                   3837:     $coursedombuf{$env{'request.course.id'}}=
                   3838:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3839:     $coursenumbuf{$env{'request.course.id'}}=
                   3840:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3841:     $coursehombuf{$env{'request.course.id'}}=
                   3842:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3843:     $coursedescrbuf{$env{'request.course.id'}}=
                   3844:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3845:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3846:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3847:     $courseownerbuf{$env{'request.course.id'}}=
                   3848:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3849:     $coursetypebuf{$env{'request.course.id'}}=
                   3850:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3851:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3852: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3853:     } else {
1.620     albertel 3854: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3855:     }
1.620     albertel 3856:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3857: 	&flushcourselogs();
                   3858:     }
1.158     www      3859: }
                   3860: 
                   3861: sub courseacclog {
                   3862:     my $fnsymb=shift;
1.620     albertel 3863:     unless ($env{'request.course.id'}) { return ''; }
                   3864:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3865:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3866:         $what.=':POST';
1.583     matthew  3867:         # FIXME: Probably ought to escape things....
1.800     albertel 3868: 	foreach my $key (keys(%env)) {
                   3869:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3870:                 my $formitem = $1;
                   3871:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3872:                     $what.=':'.$formitem.'='.$env{$key};
                   3873:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3874:                     $what.=':'.$formitem.'='.$env{$key};
                   3875:                 }
1.158     www      3876:             }
1.191     harris41 3877:         }
1.583     matthew  3878:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3879:         # FIXME: We should not be depending on a form parameter that someone
                   3880:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3881:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3882:             $what.= ':POST';
                   3883:             # FIXME: Probably ought to escape things....
                   3884:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3885:                                  'crsdiscuss') {
1.620     albertel 3886:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3887:             }
                   3888:         }
1.158     www      3889:     }
                   3890:     &courselog($what);
1.149     www      3891: }
                   3892: 
1.185     www      3893: sub countacc {
                   3894:     my $url=&declutter(shift);
1.458     matthew  3895:     return if (! defined($url) || $url eq '');
1.620     albertel 3896:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3897: #
                   3898: # Mark that this url was used in this course
                   3899: #
1.620     albertel 3900:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3901: #
                   3902: # Increase the access count for this resource in this child process
                   3903: #
1.281     www      3904:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3905:     $accesshash{$key}++;
1.185     www      3906: }
1.349     www      3907: 
1.361     www      3908: sub linklog {
                   3909:     my ($from,$to)=@_;
                   3910:     $from=&declutter($from);
                   3911:     $to=&declutter($to);
                   3912:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3913:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3914: }
1.1160    www      3915: 
                   3916: sub statslog {
                   3917:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3918:     if ($users<2) { return; }
                   3919:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3920:             'course'       => $env{'request.course.id'},
                   3921:             'sections'     => '"all"',
                   3922:             'num_students' => $users,
                   3923:             'part'         => $part,
                   3924:             'symb'         => $symb,
                   3925:             'mean_tries'   => $av_attempts,
                   3926:             'deg_of_diff'  => $degdiff});
                   3927:     foreach my $key (keys(%dynstore)) {
                   3928:         $accesshash{$key}=$dynstore{$key};
                   3929:     }
                   3930: }
1.361     www      3931:   
1.349     www      3932: sub userrolelog {
                   3933:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3934:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3935:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3936:        $userrolehash
                   3937:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3938:                     =$tend.':'.$tstart;
1.662     raeburn  3939:     }
1.1169    droeschl 3940:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3941:        $userrolehash
                   3942:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3943:                     =$tend.':'.$tstart;
                   3944:     }
1.1169    droeschl 3945:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3946:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3947:        $domainrolehash
                   3948:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3949:                     = $tend.':'.$tstart;
                   3950:     }
1.351     www      3951: }
                   3952: 
1.957     raeburn  3953: sub courserolelog {
                   3954:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3955:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3956:         my $cdom = $1;
                   3957:         my $cnum = $2;
                   3958:         my $sec = $3;
                   3959:         my $namespace = 'rolelog';
                   3960:         my %storehash = (
                   3961:                            role    => $trole,
                   3962:                            start   => $tstart,
                   3963:                            end     => $tend,
                   3964:                            selfenroll => $selfenroll,
                   3965:                            context    => $context,
                   3966:                         );
                   3967:         if ($trole eq 'gr') {
                   3968:             $namespace = 'groupslog';
                   3969:             $storehash{'group'} = $sec;
                   3970:         } else {
                   3971:             $storehash{'section'} = $sec;
                   3972:         }
1.1188    raeburn  3973:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3974:                    $domain,$cnum,$cdom);
1.1184    raeburn  3975:         if (($trole ne 'st') || ($sec ne '')) {
                   3976:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3977:         }
                   3978:     }
                   3979:     return;
                   3980: }
                   3981: 
1.1184    raeburn  3982: sub domainrolelog {
                   3983:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3984:     if ($area =~ m{^/($match_domain)/$}) {
                   3985:         my $cdom = $1;
                   3986:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3987:         my $namespace = 'rolelog';
                   3988:         my %storehash = (
                   3989:                            role    => $trole,
                   3990:                            start   => $tstart,
                   3991:                            end     => $tend,
                   3992:                            context => $context,
                   3993:                         );
1.1188    raeburn  3994:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3995:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3996:     }
                   3997:     return;
                   3998: 
                   3999: }
                   4000: 
                   4001: sub coauthorrolelog {
                   4002:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4003:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4004:         my $audom = $1;
                   4005:         my $auname = $2;
                   4006:         my $namespace = 'rolelog';
                   4007:         my %storehash = (
                   4008:                            role    => $trole,
                   4009:                            start   => $tstart,
                   4010:                            end     => $tend,
                   4011:                            context => $context,
                   4012:                         );
1.1188    raeburn  4013:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4014:                    $domain,$auname,$audom);
1.1184    raeburn  4015:     }
                   4016:     return;
                   4017: }
                   4018: 
1.351     www      4019: sub get_course_adv_roles {
1.948     raeburn  4020:     my ($cid,$codes) = @_;
1.620     albertel 4021:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4022:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4023:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4024:     my %nothide=();
1.800     albertel 4025:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4026:         if ($user !~ /:/) {
                   4027: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4028:         } else {
                   4029:             $nothide{$user}=1;
                   4030:         }
1.470     www      4031:     }
1.1219    raeburn  4032:     my @possdoms = ($coursehash{'domain'});
                   4033:     if ($coursehash{'checkforpriv'}) {
                   4034:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4035:     }
1.351     www      4036:     my %returnhash=();
                   4037:     my %dumphash=
                   4038:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4039:     my $now=time;
1.997     raeburn  4040:     my %privileged;
1.1000    raeburn  4041:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4042: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4043:         if (($tstart) && ($tstart<0)) { next; }
                   4044:         if (($tend) && ($tend<$now)) { next; }
                   4045:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4046:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4047: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4048:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4049:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4050: 	if ($role eq 'cr') { next; }
1.948     raeburn  4051:         if ($codes) {
                   4052:             if ($section) { $role .= ':'.$section; }
                   4053:             if ($returnhash{$role}) {
                   4054:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4055:             } else {
                   4056:                 $returnhash{$role}=$username.':'.$domain;
                   4057:             }
1.351     www      4058:         } else {
1.988     raeburn  4059:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4060:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4061:             if ($returnhash{$key}) {
                   4062: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4063:             } else {
                   4064:                 $returnhash{$key}=$username.':'.$domain;
                   4065:             }
1.351     www      4066:         }
1.948     raeburn  4067:     }
1.400     www      4068:     return %returnhash;
                   4069: }
                   4070: 
                   4071: sub get_my_roles {
1.937     raeburn  4072:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4073:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4074:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4075:     my (%dumphash,%nothide);
1.1086    raeburn  4076:     if ($context eq 'userroles') {
1.1166    raeburn  4077:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4078:     } else {
1.1219    raeburn  4079:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4080:         if ($hidepriv) {
                   4081:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4082:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4083:                 if ($user !~ /:/) {
                   4084:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4085:                 } else {
                   4086:                     $nothide{$user} = 1;
                   4087:                 }
                   4088:             }
                   4089:         }
1.858     raeburn  4090:     }
1.400     www      4091:     my %returnhash=();
                   4092:     my $now=time;
1.999     raeburn  4093:     my %privileged;
1.800     albertel 4094:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4095:         my ($role,$tend,$tstart);
                   4096:         if ($context eq 'userroles') {
1.1149    raeburn  4097:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4098: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4099:         } else {
                   4100:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4101:         }
1.400     www      4102:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4103:         my $status = 'active';
1.939     raeburn  4104:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4105:             $status = 'previous';
                   4106:         } 
                   4107:         if (($tstart) && ($now<$tstart)) {
                   4108:             $status = 'future';
                   4109:         }
                   4110:         if (ref($types) eq 'ARRAY') {
                   4111:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4112:                 next;
                   4113:             } 
                   4114:         } else {
                   4115:             if ($status ne 'active') {
                   4116:                 next;
                   4117:             }
                   4118:         }
1.867     raeburn  4119:         my ($rolecode,$username,$domain,$section,$area);
                   4120:         if ($context eq 'userroles') {
1.1186    raeburn  4121:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4122:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4123:         } else {
                   4124:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4125:         }
1.832     raeburn  4126:         if (ref($roledoms) eq 'ARRAY') {
                   4127:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4128:                 next;
                   4129:             }
                   4130:         }
                   4131:         if (ref($roles) eq 'ARRAY') {
                   4132:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4133:                 if ($role =~ /^cr\//) {
                   4134:                     if (!grep(/^cr$/,@{$roles})) {
                   4135:                         next;
                   4136:                     }
1.1104    raeburn  4137:                 } elsif ($role =~ /^gr\//) {
                   4138:                     if (!grep(/^gr$/,@{$roles})) {
                   4139:                         next;
                   4140:                     }
1.922     raeburn  4141:                 } else {
                   4142:                     next;
                   4143:                 }
1.832     raeburn  4144:             }
1.867     raeburn  4145:         }
1.937     raeburn  4146:         if ($hidepriv) {
1.1219    raeburn  4147:             my @privroles = ('dc','su');
1.999     raeburn  4148:             if ($context eq 'userroles') {
1.1219    raeburn  4149:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4150:             } else {
1.1219    raeburn  4151:                 my $possdoms = [$domain];
                   4152:                 if (ref($roledoms) eq 'ARRAY') {
                   4153:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4154:                 }
1.1219    raeburn  4155:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4156:                     if (!$nothide{$username.':'.$domain}) {
                   4157:                         next;
                   4158:                     }
                   4159:                 }
1.937     raeburn  4160:             }
                   4161:         }
1.933     raeburn  4162:         if ($withsec) {
                   4163:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4164:                 $tstart.':'.$tend;
                   4165:         } else {
                   4166:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4167:         }
1.832     raeburn  4168:     }
1.373     www      4169:     return %returnhash;
1.399     www      4170: }
                   4171: 
                   4172: # ----------------------------------------------------- Frontpage Announcements
                   4173: #
                   4174: #
                   4175: 
                   4176: sub postannounce {
                   4177:     my ($server,$text)=@_;
1.844     albertel 4178:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4179:     unless ($text=~/\w/) { $text=''; }
                   4180:     return &reply('setannounce:'.&escape($text),$server);
                   4181: }
                   4182: 
                   4183: sub getannounce {
1.448     albertel 4184: 
                   4185:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4186: 	my $announcement='';
1.800     albertel 4187: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4188: 	close($fh);
1.399     www      4189: 	if ($announcement=~/\w/) { 
                   4190: 	    return 
                   4191:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4192:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4193: 	} else {
                   4194: 	    return '';
                   4195: 	}
                   4196:     } else {
                   4197: 	return '';
                   4198:     }
1.351     www      4199: }
1.353     www      4200: 
                   4201: # ---------------------------------------------------------- Course ID routines
                   4202: # Deal with domain's nohist_courseid.db files
                   4203: #
                   4204: 
                   4205: sub courseidput {
1.921     raeburn  4206:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4207:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4208:     my $outcome;
                   4209:     if ($caller eq 'timeonly') {
                   4210:         my $cids = '';
                   4211:         foreach my $item (keys(%$storehash)) {
                   4212:             $cids.=&escape($item).'&';
                   4213:         }
                   4214:         $cids=~s/\&$//;
                   4215:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4216:                           $coursehome);       
                   4217:     } else {
                   4218:         my $items = '';
                   4219:         foreach my $item (keys(%$storehash)) {
                   4220:             $items.= &escape($item).'='.
                   4221:                      &freeze_escape($$storehash{$item}).'&';
                   4222:         }
                   4223:         $items=~s/\&$//;
                   4224:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4225:                           $coursehome);
1.918     raeburn  4226:     }
                   4227:     if ($outcome eq 'unknown_cmd') {
                   4228:         my $what;
                   4229:         foreach my $cid (keys(%$storehash)) {
                   4230:             $what .= &escape($cid).'=';
1.921     raeburn  4231:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4232:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4233:             }
                   4234:             $what =~ s/\:$/&/;
                   4235:         }
                   4236:         $what =~ s/\&$//;  
                   4237:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4238:     } else {
                   4239:         return $outcome;
                   4240:     }
1.353     www      4241: }
                   4242: 
                   4243: sub courseiddump {
1.921     raeburn  4244:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4245:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4246:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4247:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4248:         $hasuniquecode)=@_;
1.918     raeburn  4249:     my $as_hash = 1;
                   4250:     my %returnhash;
                   4251:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4252:     my %libserv = &all_library();
                   4253:     foreach my $tryserver (keys(%libserv)) {
                   4254:         if ( (  $hostidflag == 1 
                   4255: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4256: 	     || (!defined($hostidflag)) ) {
                   4257: 
1.918     raeburn  4258: 	    if (($domfilter eq '') ||
                   4259: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4260:                 my $rep;
                   4261:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4262:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4263:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4264:                                 &escape($descfilter), &escape($instcodefilter), 
                   4265:                                 &escape($ownerfilter), &escape($coursefilter),
                   4266:                                 &escape($typefilter), &escape($regexp_ok), 
                   4267:                                 $as_hash, &escape($selfenrollonly), 
                   4268:                                 &escape($catfilter), $showhidden, $caller, 
                   4269:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4270:                                 &escape($createdbefore), &escape($createdafter), 
1.1247    raeburn  4271:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180    droeschl 4272:                 } else {
                   4273:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4274:                              $sincefilter.':'.&escape($descfilter).':'.
                   4275:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4276:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4277:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4278:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4279:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4280:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4281:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247    raeburn  4282:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180    droeschl 4283:                              $tryserver);
                   4284:                 }
                   4285:                      
1.918     raeburn  4286:                 my @pairs=split(/\&/,$rep);
                   4287:                 foreach my $item (@pairs) {
                   4288:                     my ($key,$value)=split(/\=/,$item,2);
                   4289:                     $key = &unescape($key);
                   4290:                     next if ($key =~ /^error: 2 /);
                   4291:                     my $result = &thaw_unescape($value);
                   4292:                     if (ref($result) eq 'HASH') {
                   4293:                         $returnhash{$key}=$result;
                   4294:                     } else {
1.921     raeburn  4295:                         my @responses = split(/:/,$value);
                   4296:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4297:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4298:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4299:                         }
1.1008    raeburn  4300:                     }
1.353     www      4301:                 }
                   4302:             }
                   4303:         }
                   4304:     }
                   4305:     return %returnhash;
                   4306: }
                   4307: 
1.1055    raeburn  4308: sub courselastaccess {
                   4309:     my ($cdom,$cnum,$hostidref) = @_;
                   4310:     my %returnhash;
                   4311:     if ($cdom && $cnum) {
                   4312:         my $chome = &homeserver($cnum,$cdom);
                   4313:         if ($chome ne 'no_host') {
                   4314:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4315:             &extract_lastaccess(\%returnhash,$rep);
                   4316:         }
                   4317:     } else {
                   4318:         if (!$cdom) { $cdom=''; }
                   4319:         my %libserv = &all_library();
                   4320:         foreach my $tryserver (keys(%libserv)) {
                   4321:             if (ref($hostidref) eq 'ARRAY') {
                   4322:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4323:             } 
                   4324:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4325:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4326:                 &extract_lastaccess(\%returnhash,$rep);
                   4327:             }
                   4328:         }
                   4329:     }
                   4330:     return %returnhash;
                   4331: }
                   4332: 
                   4333: sub extract_lastaccess {
                   4334:     my ($returnhash,$rep) = @_;
                   4335:     if (ref($returnhash) eq 'HASH') {
                   4336:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4337:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4338:                  $rep eq '') {
                   4339:             my @pairs=split(/\&/,$rep);
                   4340:             foreach my $item (@pairs) {
                   4341:                 my ($key,$value)=split(/\=/,$item,2);
                   4342:                 $key = &unescape($key);
                   4343:                 next if ($key =~ /^error: 2 /);
                   4344:                 $returnhash->{$key} = &thaw_unescape($value);
                   4345:             }
                   4346:         }
                   4347:     }
                   4348:     return;
                   4349: }
                   4350: 
1.658     raeburn  4351: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4352: 
                   4353: sub dcmailput {
1.685     raeburn  4354:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4355:     my $status = &Apache::lonnet::critical(
1.740     www      4356:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4357:        &escape($message),$server);
1.662     raeburn  4358:     return $status;
                   4359: }
                   4360: 
1.658     raeburn  4361: sub dcmaildump {
                   4362:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4363:     my %returnhash=();
1.846     albertel 4364: 
                   4365:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4366:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4367:                                                          &escape($enddate).':';
                   4368: 	my @esc_senders=map { &escape($_)} @$senders;
                   4369: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4370: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4371:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4372:             if (($key) && ($value)) {
                   4373:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4374:             }
                   4375:         }
                   4376:     }
                   4377:     return %returnhash;
                   4378: }
1.662     raeburn  4379: # ---------------------------------------------------------- Domain roles
                   4380: 
                   4381: sub get_domain_roles {
                   4382:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4383:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4384:         $startdate = '.';
                   4385:     }
1.1018    raeburn  4386:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4387:         $enddate = '.';
                   4388:     }
1.922     raeburn  4389:     my $rolelist;
                   4390:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4391:         $rolelist = join('&',@{$roles});
1.922     raeburn  4392:     }
1.662     raeburn  4393:     my %personnel = ();
1.841     albertel 4394: 
                   4395:     my %servers = &get_servers($dom,'library');
                   4396:     foreach my $tryserver (keys(%servers)) {
                   4397: 	%{$personnel{$tryserver}}=();
                   4398: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4399: 					    &escape($startdate).':'.
                   4400: 					    &escape($enddate).':'.
                   4401: 					    &escape($rolelist), $tryserver))) {
                   4402: 	    my ($key,$value) = split(/\=/,$line,2);
                   4403: 	    if (($key) && ($value)) {
                   4404: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4405: 	    }
                   4406: 	}
1.662     raeburn  4407:     }
                   4408:     return %personnel;
                   4409: }
1.658     raeburn  4410: 
1.1057    www      4411: # ----------------------------------------------------------- Interval timing 
1.149     www      4412: 
1.1153    www      4413: {
                   4414: # Caches needed for speedup of navmaps
                   4415: # We don't want to cache this for very long at all (5 seconds at most)
                   4416: # 
                   4417: # The user for whom we cache
                   4418: my $cachedkey='';
                   4419: # The cached times for this user
                   4420: my %cachedtimes=();
                   4421: # When this was last done
                   4422: my $cachedtime=();
                   4423: 
                   4424: sub load_all_first_access {
1.1154    raeburn  4425:     my ($uname,$udom)=@_;
1.1156    www      4426:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4427:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4428:         return;
                   4429:     }
                   4430:     $cachedtime=time;
                   4431:     $cachedkey=$uname.':'.$udom;
                   4432:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4433: }
                   4434: 
1.504     albertel 4435: sub get_first_access {
1.1162    raeburn  4436:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4437:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4438:     if ($argsymb) { $symb=$argsymb; }
                   4439:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4440:     if ($argmap) { $map = $argmap; }
1.926     albertel 4441:     if ($type eq 'course') {
                   4442: 	$res='course';
                   4443:     } elsif ($type eq 'map') {
1.588     albertel 4444: 	$res=&symbread($map);
                   4445:     } else {
                   4446: 	$res=$symb;
                   4447:     }
1.1153    www      4448:     &load_all_first_access($uname,$udom);
                   4449:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4450: }
                   4451: 
                   4452: sub set_first_access {
1.1162    raeburn  4453:     my ($type,$interval)=@_;
1.790     albertel 4454:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4455:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4456:     if ($type eq 'course') {
                   4457: 	$res='course';
                   4458:     } elsif ($type eq 'map') {
1.588     albertel 4459: 	$res=&symbread($map);
                   4460:     } else {
                   4461: 	$res=$symb;
                   4462:     }
1.1153    www      4463:     $cachedkey='';
1.1162    raeburn  4464:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4465:     if (!$firstaccess) {
1.1162    raeburn  4466:         my $start = time;
                   4467: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4468:                           $udom,$uname);
                   4469:         if ($putres eq 'ok') {
                   4470:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4471:                  $udom,$uname); 
                   4472:             &appenv(
                   4473:                      {
                   4474:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4475:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4476:                      }
                   4477:                   );
                   4478:         }
                   4479:         return $putres;
1.505     albertel 4480:     }
                   4481:     return 'already_set';
1.504     albertel 4482: }
1.1153    www      4483: }
1.110     www      4484: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4485: 
                   4486: sub expirespread {
                   4487:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4488:     my $cid=$env{'request.course.id'}; 
1.110     www      4489:     if ($cid) {
                   4490:        my $now=time;
                   4491:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4492:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4493:                             $env{'course.'.$cid.'.num'}.
1.110     www      4494: 	        	    ':nohist_expirationdates:'.
                   4495:                             &escape($key).'='.$now,
1.620     albertel 4496:                             $env{'course.'.$cid.'.home'})
1.110     www      4497:     }
                   4498:     return 'ok';
1.14      www      4499: }
                   4500: 
1.109     www      4501: # ----------------------------------------------------- Devalidate Spreadsheets
                   4502: 
                   4503: sub devalidate {
1.325     www      4504:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4505:     my $cid=$env{'request.course.id'}; 
1.109     www      4506:     if ($cid) {
1.391     matthew  4507:         # delete the stored spreadsheets for
                   4508:         # - the student level sheet of this user in course's homespace
                   4509:         # - the assessment level sheet for this resource 
                   4510:         #   for this user in user's homespace
1.553     albertel 4511: 	# - current conditional state info
1.325     www      4512: 	my $key=$uname.':'.$udom.':';
1.109     www      4513:         my $status=
1.299     matthew  4514: 	    &del('nohist_calculatedsheets',
1.391     matthew  4515: 		 [$key.'studentcalc:'],
1.620     albertel 4516: 		 $env{'course.'.$cid.'.domain'},
                   4517: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4518: 		.' '.
                   4519: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4520: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4521:         unless ($status eq 'ok ok') {
                   4522:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4523:                     $uname.' at '.$udom.' for '.
1.109     www      4524: 		    $symb.': '.$status);
1.133     albertel 4525:         }
1.553     albertel 4526: 	&delenv('user.state.'.$cid);
1.109     www      4527:     }
                   4528: }
                   4529: 
1.265     albertel 4530: sub get_scalar {
                   4531:     my ($string,$end) = @_;
                   4532:     my $value;
                   4533:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4534: 	$value = $1;
                   4535:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4536: 	$value = $1;
                   4537:     }
                   4538:     return &unescape($value);
                   4539: }
                   4540: 
                   4541: sub array2str {
                   4542:   my (@array) = @_;
                   4543:   my $result=&arrayref2str(\@array);
                   4544:   $result=~s/^__ARRAY_REF__//;
                   4545:   $result=~s/__END_ARRAY_REF__$//;
                   4546:   return $result;
                   4547: }
                   4548: 
1.204     albertel 4549: sub arrayref2str {
                   4550:   my ($arrayref) = @_;
1.265     albertel 4551:   my $result='__ARRAY_REF__';
1.204     albertel 4552:   foreach my $elem (@$arrayref) {
1.265     albertel 4553:     if(ref($elem) eq 'ARRAY') {
                   4554:       $result.=&arrayref2str($elem).'&';
                   4555:     } elsif(ref($elem) eq 'HASH') {
                   4556:       $result.=&hashref2str($elem).'&';
                   4557:     } elsif(ref($elem)) {
                   4558:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4559:     } else {
                   4560:       $result.=&escape($elem).'&';
                   4561:     }
                   4562:   }
                   4563:   $result=~s/\&$//;
1.265     albertel 4564:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4565:   return $result;
                   4566: }
                   4567: 
1.168     albertel 4568: sub hash2str {
1.204     albertel 4569:   my (%hash) = @_;
                   4570:   my $result=&hashref2str(\%hash);
1.265     albertel 4571:   $result=~s/^__HASH_REF__//;
                   4572:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4573:   return $result;
                   4574: }
                   4575: 
                   4576: sub hashref2str {
                   4577:   my ($hashref)=@_;
1.265     albertel 4578:   my $result='__HASH_REF__';
1.800     albertel 4579:   foreach my $key (sort(keys(%$hashref))) {
                   4580:     if (ref($key) eq 'ARRAY') {
                   4581:       $result.=&arrayref2str($key).'=';
                   4582:     } elsif (ref($key) eq 'HASH') {
                   4583:       $result.=&hashref2str($key).'=';
                   4584:     } elsif (ref($key)) {
1.265     albertel 4585:       $result.='=';
1.800     albertel 4586:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4587:     } else {
1.1132    raeburn  4588: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4589:     }
                   4590: 
1.800     albertel 4591:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4592:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4593:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4594:       $result.=&hashref2str($hashref->{$key}).'&';
                   4595:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4596:        $result.='&';
1.800     albertel 4597:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4598:     } else {
1.800     albertel 4599:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4600:     }
                   4601:   }
1.168     albertel 4602:   $result=~s/\&$//;
1.265     albertel 4603:   $result .= '__END_HASH_REF__';
1.168     albertel 4604:   return $result;
                   4605: }
                   4606: 
                   4607: sub str2hash {
1.265     albertel 4608:     my ($string)=@_;
                   4609:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4610:     return %$hash;
                   4611: }
                   4612: 
                   4613: sub str2hashref {
1.168     albertel 4614:   my ($string) = @_;
1.265     albertel 4615: 
                   4616:   my %hash;
                   4617: 
                   4618:   if($string !~ /^__HASH_REF__/) {
                   4619:       if (! ($string eq '' || !defined($string))) {
                   4620: 	  $hash{'error'}='Not hash reference';
                   4621:       }
                   4622:       return (\%hash, $string);
                   4623:   }
                   4624: 
                   4625:   $string =~ s/^__HASH_REF__//;
                   4626: 
                   4627:   while($string !~ /^__END_HASH_REF__/) {
                   4628:       #key
                   4629:       my $key='';
                   4630:       if($string =~ /^__HASH_REF__/) {
                   4631:           ($key, $string)=&str2hashref($string);
                   4632:           if(defined($key->{'error'})) {
                   4633:               $hash{'error'}='Bad data';
                   4634:               return (\%hash, $string);
                   4635:           }
                   4636:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4637:           ($key, $string)=&str2arrayref($string);
                   4638:           if($key->[0] eq 'Array reference error') {
                   4639:               $hash{'error'}='Bad data';
                   4640:               return (\%hash, $string);
                   4641:           }
                   4642:       } else {
                   4643:           $string =~ s/^(.*?)=//;
1.267     albertel 4644: 	  $key=&unescape($1);
1.265     albertel 4645:       }
                   4646:       $string =~ s/^=//;
                   4647: 
                   4648:       #value
                   4649:       my $value='';
                   4650:       if($string =~ /^__HASH_REF__/) {
                   4651:           ($value, $string)=&str2hashref($string);
                   4652:           if(defined($value->{'error'})) {
                   4653:               $hash{'error'}='Bad data';
                   4654:               return (\%hash, $string);
                   4655:           }
                   4656:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4657:           ($value, $string)=&str2arrayref($string);
                   4658:           if($value->[0] eq 'Array reference error') {
                   4659:               $hash{'error'}='Bad data';
                   4660:               return (\%hash, $string);
                   4661:           }
                   4662:       } else {
                   4663: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4664:       }
                   4665:       $string =~ s/^&//;
                   4666: 
                   4667:       $hash{$key}=$value;
1.204     albertel 4668:   }
1.265     albertel 4669: 
                   4670:   $string =~ s/^__END_HASH_REF__//;
                   4671: 
                   4672:   return (\%hash, $string);
1.204     albertel 4673: }
                   4674: 
                   4675: sub str2array {
1.265     albertel 4676:     my ($string)=@_;
                   4677:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4678:     return @$array;
                   4679: }
                   4680: 
                   4681: sub str2arrayref {
1.204     albertel 4682:   my ($string) = @_;
1.265     albertel 4683:   my @array;
                   4684: 
                   4685:   if($string !~ /^__ARRAY_REF__/) {
                   4686:       if (! ($string eq '' || !defined($string))) {
                   4687: 	  $array[0]='Array reference error';
                   4688:       }
                   4689:       return (\@array, $string);
                   4690:   }
                   4691: 
                   4692:   $string =~ s/^__ARRAY_REF__//;
                   4693: 
                   4694:   while($string !~ /^__END_ARRAY_REF__/) {
                   4695:       my $value='';
                   4696:       if($string =~ /^__HASH_REF__/) {
                   4697:           ($value, $string)=&str2hashref($string);
                   4698:           if(defined($value->{'error'})) {
                   4699:               $array[0] ='Array reference error';
                   4700:               return (\@array, $string);
                   4701:           }
                   4702:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4703:           ($value, $string)=&str2arrayref($string);
                   4704:           if($value->[0] eq 'Array reference error') {
                   4705:               $array[0] ='Array reference error';
                   4706:               return (\@array, $string);
                   4707:           }
                   4708:       } else {
                   4709: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4710:       }
                   4711:       $string =~ s/^&//;
                   4712: 
                   4713:       push(@array, $value);
1.191     harris41 4714:   }
1.265     albertel 4715: 
                   4716:   $string =~ s/^__END_ARRAY_REF__//;
                   4717: 
                   4718:   return (\@array, $string);
1.168     albertel 4719: }
                   4720: 
1.167     albertel 4721: # -------------------------------------------------------------------Temp Store
                   4722: 
1.168     albertel 4723: sub tmpreset {
                   4724:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4725:   if (!$symb) {
                   4726:     $symb=&symbread();
1.620     albertel 4727:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4728:   }
                   4729:   $symb=escape($symb);
                   4730: 
1.620     albertel 4731:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4732:   $namespace=~s/\//\_/g;
                   4733:   $namespace=~s/\W//g;
                   4734: 
1.620     albertel 4735:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4736:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4737:   if ($domain eq 'public' && $stuname eq 'public') {
                   4738:       $stuname=$ENV{'REMOTE_ADDR'};
                   4739:   }
1.1117    foxr     4740:   my $path=LONCAPA::tempdir();
1.168     albertel 4741:   my %hash;
                   4742:   if (tie(%hash,'GDBM_File',
                   4743: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4744: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4745:     foreach my $key (keys(%hash)) {
1.180     albertel 4746:       if ($key=~ /:$symb/) {
1.168     albertel 4747: 	delete($hash{$key});
                   4748:       }
                   4749:     }
                   4750:   }
                   4751: }
                   4752: 
1.167     albertel 4753: sub tmpstore {
1.168     albertel 4754:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4755: 
                   4756:   if (!$symb) {
                   4757:     $symb=&symbread();
1.620     albertel 4758:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4759:   }
                   4760:   $symb=escape($symb);
                   4761: 
                   4762:   if (!$namespace) {
                   4763:     # I don't think we would ever want to store this for a course.
                   4764:     # it seems this will only be used if we don't have a course.
1.620     albertel 4765:     #$namespace=$env{'request.course.id'};
1.168     albertel 4766:     #if (!$namespace) {
1.620     albertel 4767:       $namespace=$env{'request.state'};
1.168     albertel 4768:     #}
                   4769:   }
                   4770:   $namespace=~s/\//\_/g;
                   4771:   $namespace=~s/\W//g;
1.620     albertel 4772:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4773:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4774:   if ($domain eq 'public' && $stuname eq 'public') {
                   4775:       $stuname=$ENV{'REMOTE_ADDR'};
                   4776:   }
1.168     albertel 4777:   my $now=time;
                   4778:   my %hash;
1.1117    foxr     4779:   my $path=LONCAPA::tempdir();
1.168     albertel 4780:   if (tie(%hash,'GDBM_File',
                   4781: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4782: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4783:     $hash{"version:$symb"}++;
                   4784:     my $version=$hash{"version:$symb"};
                   4785:     my $allkeys=''; 
                   4786:     foreach my $key (keys(%$storehash)) {
                   4787:       $allkeys.=$key.':';
1.591     albertel 4788:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4789:     }
                   4790:     $hash{"$version:$symb:timestamp"}=$now;
                   4791:     $allkeys.='timestamp';
                   4792:     $hash{"$version:keys:$symb"}=$allkeys;
                   4793:     if (untie(%hash)) {
                   4794:       return 'ok';
                   4795:     } else {
                   4796:       return "error:$!";
                   4797:     }
                   4798:   } else {
                   4799:     return "error:$!";
                   4800:   }
                   4801: }
1.167     albertel 4802: 
1.168     albertel 4803: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4804: 
1.168     albertel 4805: sub tmprestore {
                   4806:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4807: 
1.168     albertel 4808:   if (!$symb) {
                   4809:     $symb=&symbread();
1.620     albertel 4810:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4811:   }
                   4812:   $symb=escape($symb);
                   4813: 
1.620     albertel 4814:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4815: 
1.620     albertel 4816:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4817:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4818:   if ($domain eq 'public' && $stuname eq 'public') {
                   4819:       $stuname=$ENV{'REMOTE_ADDR'};
                   4820:   }
1.168     albertel 4821:   my %returnhash;
                   4822:   $namespace=~s/\//\_/g;
                   4823:   $namespace=~s/\W//g;
                   4824:   my %hash;
1.1117    foxr     4825:   my $path=LONCAPA::tempdir();
1.168     albertel 4826:   if (tie(%hash,'GDBM_File',
                   4827: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4828: 	  &GDBM_READER(),0640)) {
1.168     albertel 4829:     my $version=$hash{"version:$symb"};
                   4830:     $returnhash{'version'}=$version;
                   4831:     my $scope;
                   4832:     for ($scope=1;$scope<=$version;$scope++) {
                   4833:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4834:       my @keys=split(/:/,$vkeys);
                   4835:       my $key;
                   4836:       $returnhash{"$scope:keys"}=$vkeys;
                   4837:       foreach $key (@keys) {
1.591     albertel 4838: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4839: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4840:       }
                   4841:     }
1.168     albertel 4842:     if (!(untie(%hash))) {
                   4843:       return "error:$!";
                   4844:     }
                   4845:   } else {
                   4846:     return "error:$!";
                   4847:   }
                   4848:   return %returnhash;
1.167     albertel 4849: }
                   4850: 
1.9       www      4851: # ----------------------------------------------------------------------- Store
                   4852: 
                   4853: sub store {
1.124     www      4854:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4855:     my $home='';
                   4856: 
1.168     albertel 4857:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4858: 
1.213     www      4859:     $symb=&symbclean($symb);
1.122     albertel 4860:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4861: 
1.620     albertel 4862:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4863:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4864: 
                   4865:     &devalidate($symb,$stuname,$domain);
1.109     www      4866: 
                   4867:     $symb=escape($symb);
1.187     www      4868:     if (!$namespace) { 
1.620     albertel 4869:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4870:           return ''; 
                   4871:        } 
                   4872:     }
1.620     albertel 4873:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4874: 
                   4875:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4876:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4877: 
1.12      www      4878:     my $namevalue='';
1.800     albertel 4879:     foreach my $key (keys(%$storehash)) {
                   4880:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4881:     }
1.12      www      4882:     $namevalue=~s/\&$//;
1.187     www      4883:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4884:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4885: }
                   4886: 
1.47      www      4887: # -------------------------------------------------------------- Critical Store
                   4888: 
                   4889: sub cstore {
1.124     www      4890:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4891:     my $home='';
                   4892: 
1.168     albertel 4893:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4894: 
1.213     www      4895:     $symb=&symbclean($symb);
1.122     albertel 4896:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4897: 
1.620     albertel 4898:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4899:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4900: 
                   4901:     &devalidate($symb,$stuname,$domain);
1.109     www      4902: 
                   4903:     $symb=escape($symb);
1.187     www      4904:     if (!$namespace) { 
1.620     albertel 4905:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4906:           return ''; 
                   4907:        } 
                   4908:     }
1.620     albertel 4909:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4910: 
                   4911:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4912:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4913: 
1.47      www      4914:     my $namevalue='';
1.800     albertel 4915:     foreach my $key (keys(%$storehash)) {
                   4916:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4917:     }
1.47      www      4918:     $namevalue=~s/\&$//;
1.187     www      4919:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4920:     return critical
                   4921:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4922: }
                   4923: 
1.9       www      4924: # --------------------------------------------------------------------- Restore
                   4925: 
                   4926: sub restore {
1.124     www      4927:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4928:     my $home='';
                   4929: 
1.168     albertel 4930:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4931: 
1.122     albertel 4932:     if (!$symb) {
1.1224    raeburn  4933:         return if ($namespace eq 'courserequests');
                   4934:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4935:     } else {
1.1224    raeburn  4936:         unless ($namespace eq 'courserequests') {
                   4937:             $symb=&escape(&symbclean($symb));
                   4938:         }
1.122     albertel 4939:     }
1.188     www      4940:     if (!$namespace) { 
1.620     albertel 4941:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4942:           return ''; 
                   4943:        } 
                   4944:     }
1.620     albertel 4945:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4946:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4947:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4948:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4949: 
1.12      www      4950:     my %returnhash=();
1.800     albertel 4951:     foreach my $line (split(/\&/,$answer)) {
                   4952: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4953:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4954:     }
1.75      www      4955:     my $version;
                   4956:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4957:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4958:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4959:        }
1.75      www      4960:     }
1.13      www      4961:     return %returnhash;
1.34      www      4962: }
                   4963: 
                   4964: # ---------------------------------------------------------- Course Description
1.1118    foxr     4965: #
                   4966: #  
1.34      www      4967: 
                   4968: sub coursedescription {
1.731     albertel 4969:     my ($courseid,$args)=@_;
1.34      www      4970:     $courseid=~s/^\///;
1.49      www      4971:     $courseid=~s/\_/\//g;
1.34      www      4972:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4973:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4974:     my $normalid=$cdomain.'_'.$cnum;
                   4975:     # need to always cache even if we get errors otherwise we keep 
                   4976:     # trying and trying and trying to get the course description.
                   4977:     my %envhash=();
                   4978:     my %returnhash=();
1.731     albertel 4979:     
                   4980:     my $expiretime=600;
                   4981:     if ($env{'request.course.id'} eq $normalid) {
                   4982: 	$expiretime=120;
                   4983:     }
                   4984: 
                   4985:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4986:     if (!$args->{'freshen_cache'}
                   4987: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4988: 	foreach my $key (keys(%env)) {
                   4989: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4990: 	    my ($setting) = $1;
                   4991: 	    $returnhash{$setting} = $env{$key};
                   4992: 	}
                   4993: 	return %returnhash;
                   4994:     }
                   4995: 
1.1118    foxr     4996:     # get the data again
                   4997: 
1.731     albertel 4998:     if (!$args->{'one_time'}) {
                   4999: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5000:     }
1.811     albertel 5001: 
1.34      www      5002:     if ($chome ne 'no_host') {
1.302     albertel 5003:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5004:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5005: 	   my $username = $env{'user.name'}; # Defult username
                   5006: 	   if(defined $args->{'user'}) {
                   5007: 	       $username = $args->{'user'};
                   5008: 	   }
1.129     albertel 5009:            $returnhash{'home'}= $chome;
                   5010: 	   $returnhash{'domain'} = $cdomain;
                   5011: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5012:            if (!defined($returnhash{'type'})) {
                   5013:                $returnhash{'type'} = 'Course';
                   5014:            }
1.130     albertel 5015:            while (my ($name,$value) = each %returnhash) {
1.53      www      5016:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5017:            }
1.270     www      5018:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5019:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5020: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5021:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5022:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5023:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5024:        }
                   5025:     }
1.731     albertel 5026:     if (!$args->{'one_time'}) {
1.949     raeburn  5027: 	&appenv(\%envhash);
1.731     albertel 5028:     }
1.302     albertel 5029:     return %returnhash;
1.461     www      5030: }
                   5031: 
1.1080    raeburn  5032: sub update_released_required {
                   5033:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5034:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5035:         $cid = $env{'request.course.id'};
                   5036:         $cdom = $env{'course.'.$cid.'.domain'};
                   5037:         $cnum = $env{'course.'.$cid.'.num'};
                   5038:         $chome = $env{'course.'.$cid.'.home'};
                   5039:     }
                   5040:     if ($needsrelease) {
                   5041:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5042:         my $needsupdate;
                   5043:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5044:             $needsupdate = 1;
                   5045:         } else {
                   5046:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5047:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5048:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5049:                 $needsupdate = 1;
                   5050:             }
                   5051:         }
                   5052:         if ($needsupdate) {
                   5053:             my %needshash = (
                   5054:                              'internal.releaserequired' => $needsrelease,
                   5055:                             );
                   5056:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5057:             if ($putresult eq 'ok') {
                   5058:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5059:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5060:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5061:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5062:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5063:                 }
                   5064:             }
                   5065:         }
                   5066:     }
                   5067:     return;
                   5068: }
                   5069: 
1.461     www      5070: # -------------------------------------------------See if a user is privileged
                   5071: 
                   5072: sub privileged {
1.1219    raeburn  5073:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5074:     my $now = time;
1.1219    raeburn  5075:     my $roles;
                   5076:     if (ref($possroles) eq 'ARRAY') {
                   5077:         $roles = $possroles; 
                   5078:     } else {
                   5079:         $roles = ['dc','su'];
                   5080:     }
                   5081:     if (ref($possdomains) eq 'ARRAY') {
                   5082:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5083:         foreach my $dom (@{$possdomains}) {
                   5084:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5085:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5086:                 foreach my $role (@{$roles}) {
                   5087:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5088:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5089:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5090:                             return 1 unless (($end && $end < $now) ||
                   5091:                                              ($start && $start > $now));
                   5092:                         }
                   5093:                     }
                   5094:                 }
                   5095:             }
                   5096:         }
                   5097:     } else {
                   5098:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5099:         my $now = time;
1.1170    droeschl 5100: 
1.1219    raeburn  5101:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5102:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5103:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5104:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5105:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5106:             }
1.1219    raeburn  5107:         }
                   5108:     }
                   5109:     return 0;
                   5110: }
1.1170    droeschl 5111: 
1.1219    raeburn  5112: sub privileged_by_domain {
                   5113:     my ($domains,$roles) = @_;
                   5114:     my %privileged = ();
                   5115:     my $cachetime = 60*60*24;
                   5116:     my $now = time;
                   5117:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5118:         return %privileged;
                   5119:     }
                   5120:     foreach my $dom (@{$domains}) {
                   5121:         next if (ref($privileged{$dom}) eq 'HASH');
                   5122:         my $needroles;
                   5123:         foreach my $role (@{$roles}) {
                   5124:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5125:             if (defined($cached)) {
                   5126:                 if (ref($result) eq 'HASH') {
                   5127:                     $privileged{$dom}{$role} = $result;
                   5128:                 }
                   5129:             } else {
                   5130:                 $needroles = 1;
                   5131:             }
                   5132:         }
                   5133:         if ($needroles) {
                   5134:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5135:             $privileged{$dom} = {};
                   5136:             foreach my $server (keys(%dompersonnel)) {
                   5137:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5138:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5139:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5140:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5141:                         next if ($end && $end < $now);
                   5142:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5143:                             $dompersonnel{$server}{$item};
                   5144:                     }
                   5145:                 }
                   5146:             }
                   5147:             if (ref($privileged{$dom}) eq 'HASH') {
                   5148:                 foreach my $role (@{$roles}) {
                   5149:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5150:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5151:                     } else {
                   5152:                         my %hash = ();
                   5153:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5154:                     }
                   5155:                 }
                   5156:             }
                   5157:         }
                   5158:     }
                   5159:     return %privileged;
1.9       www      5160: }
1.1       albertel 5161: 
1.103     harris41 5162: # -------------------------------------------------------- Get user privileges
1.11      www      5163: 
                   5164: sub rolesinit {
1.1169    droeschl 5165:     my ($domain, $username) = @_;
                   5166:     my %userroles = ('user.login.time' => time);
                   5167:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5168: 
                   5169:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5170:     # also, blocking can be triggered by an activating timer
                   5171:     # it's saved in the user's %env.
                   5172:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5173:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5174:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5175:         %timerintchk, %timerintenv);
                   5176: 
1.1162    raeburn  5177:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5178:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5179:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5180:     }
1.1169    droeschl 5181: 
1.1162    raeburn  5182:     foreach my $key (keys(%timerinterval)) {
                   5183:         my ($cid,$rest) = split(/\0/,$key);
                   5184:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5185:     }
1.1169    droeschl 5186: 
1.11      www      5187:     my %allroles=();
1.1162    raeburn  5188:     my %allgroups=();
1.11      www      5189: 
1.1169    droeschl 5190:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5191:         my $role = $rolesdump{$area};
                   5192:         $area =~ s/\_\w\w$//;
                   5193: 
                   5194:         my ($trole, $tend, $tstart, $group_privs);
                   5195: 
                   5196:         if ($role =~ /^cr/) {
                   5197:         # Custom role, defined by a user 
                   5198:         # e.g., user.role.cr/msu/smith/mynewrole
                   5199:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5200:                 $trole = $1;
                   5201:                 ($tend, $tstart) = split('_', $2);
                   5202:             } else {
                   5203:                 $trole = $role;
                   5204:             }
                   5205:         } elsif ($role =~ m|^gr/|) {
                   5206:         # Role of member in a group, defined within a course/community
                   5207:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5208:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5209:             next if $tstart eq '-1';
                   5210:             ($trole, $group_privs) = split(/\//, $trole);
                   5211:             $group_privs = &unescape($group_privs);
                   5212:         } else {
                   5213:         # Just a normal role, defined in roles.tab
                   5214:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5215:         }
                   5216: 
                   5217:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5218:                  $username);
                   5219:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5220: 
                   5221:         # role expired or not available yet?
                   5222:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5223:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5224: 
                   5225:         next if $area eq '' or $trole eq '';
                   5226: 
                   5227:         my $spec = "$trole.$area";
                   5228:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5229: 
                   5230:         if ($trole =~ /^cr\//) {
                   5231:         # Custom role, defined by a user
                   5232:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5233:         } elsif ($trole eq 'gr') {
                   5234:         # Role of a member in a group, defined within a course/community
                   5235:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5236:             next;
                   5237:         } else {
                   5238:         # Normal role, defined in roles.tab
                   5239:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5240:         }
                   5241: 
                   5242:         my $cid = $tdomain.'_'.$trest;
                   5243:         unless ($firstaccchk{$cid}) {
                   5244:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5245:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5246:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5247:                         $coursetimerstarts{$cid}{$item}; 
                   5248:                 }
                   5249:             }
                   5250:             $firstaccchk{$cid} = 1;
                   5251:         }
                   5252:         unless ($timerintchk{$cid}) {
                   5253:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5254:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5255:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5256:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5257:                 }
1.12      www      5258:             }
1.1169    droeschl 5259:             $timerintchk{$cid} = 1;
1.191     harris41 5260:         }
1.11      www      5261:     }
1.1169    droeschl 5262: 
                   5263:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5264:         \%allroles, \%allgroups);
                   5265:     $env{'user.adv'} = $userroles{'user.adv'};
                   5266: 
1.1162    raeburn  5267:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5268: }
                   5269: 
1.567     raeburn  5270: sub set_arearole {
1.1215    raeburn  5271:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5272:     unless ($nolog) {
1.567     raeburn  5273: # log the associated role with the area
1.1215    raeburn  5274:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5275:     }
1.743     albertel 5276:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5277: }
                   5278: 
                   5279: sub custom_roleprivs {
                   5280:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5281:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5282:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5283:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5284:         my ($rdummy,$roledef)=
                   5285:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5286:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5287:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5288:             if (defined($syspriv)) {
1.1043    raeburn  5289:                 if ($trest =~ /^$match_community$/) {
                   5290:                     $syspriv =~ s/bre\&S//; 
                   5291:                 }
1.567     raeburn  5292:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5293:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5294:             }
                   5295:             if ($tdomain ne '') {
                   5296:                 if (defined($dompriv)) {
                   5297:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5298:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5299:                 }
                   5300:                 if (($trest ne '') && (defined($coursepriv))) {
                   5301:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5302:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5303:                 }
                   5304:             }
                   5305:         }
                   5306:     }
                   5307: }
                   5308: 
1.678     raeburn  5309: sub group_roleprivs {
                   5310:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5311:     my $access = 1;
                   5312:     my $now = time;
                   5313:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5314:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5315:     if ($access) {
1.811     albertel 5316:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5317:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5318:     }
                   5319: }
1.567     raeburn  5320: 
                   5321: sub standard_roleprivs {
                   5322:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5323:     if (defined($pr{$trole.':s'})) {
                   5324:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5325:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5326:     }
                   5327:     if ($tdomain ne '') {
                   5328:         if (defined($pr{$trole.':d'})) {
                   5329:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5330:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5331:         }
                   5332:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5333:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5334:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5335:         }
                   5336:     }
                   5337: }
                   5338: 
                   5339: sub set_userprivs {
1.1064    raeburn  5340:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5341:     my $author=0;
                   5342:     my $adv=0;
1.678     raeburn  5343:     my %grouproles = ();
                   5344:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5345:         my @groupkeys; 
1.1000    raeburn  5346:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5347:             push(@groupkeys,$role);
                   5348:         }
                   5349:         if (ref($groups_roles) eq 'HASH') {
                   5350:             foreach my $key (keys(%{$groups_roles})) {
                   5351:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5352:                     push(@groupkeys,$key);
                   5353:                 }
                   5354:             }
                   5355:         }
                   5356:         if (@groupkeys > 0) {
                   5357:             foreach my $role (@groupkeys) {
                   5358:                 my ($trole,$area,$sec,$extendedarea);
                   5359:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5360:                     $trole = $1;
                   5361:                     $area = $2;
                   5362:                     $sec = $3;
                   5363:                     $extendedarea = $area.$sec;
                   5364:                     if (exists($$allgroups{$area})) {
                   5365:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5366:                             my $spec = $trole.'.'.$extendedarea;
                   5367:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5368:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5369:                         }
1.678     raeburn  5370:                     }
                   5371:                 }
                   5372:             }
                   5373:         }
                   5374:     }
1.800     albertel 5375:     foreach my $group (keys(%grouproles)) {
                   5376:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5377:     }
1.800     albertel 5378:     foreach my $role (keys(%{$allroles})) {
                   5379:         my %thesepriv;
1.941     raeburn  5380:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5381:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5382:             if ($item ne '') {
                   5383:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5384:                 if ($restrictions eq '') {
                   5385:                     $thesepriv{$privilege}='F';
                   5386:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5387:                     $thesepriv{$privilege}.=$restrictions;
                   5388:                 }
                   5389:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5390:             }
                   5391:         }
                   5392:         my $thesestr='';
1.1104    raeburn  5393:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5394: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5395: 	}
                   5396:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5397:     }
                   5398:     return ($author,$adv);
                   5399: }
                   5400: 
1.994     raeburn  5401: sub role_status {
1.1104    raeburn  5402:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5403:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5404:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5405:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5406:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5407:             $$where = '/'.$two;
1.994     raeburn  5408:             $$trolecode=$$role.'.'.$$where;
                   5409:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5410:             $$tstatus='is';
1.1104    raeburn  5411:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5412:                 $$tstatus='future';
1.1034    raeburn  5413:                 if ($$tstart<$now) {
                   5414:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5415:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5416:                             my (%allroles,%allgroups,$group_privs,
                   5417:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5418:                             my %userroles = (
                   5419:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5420:                             );
1.1064    raeburn  5421:                             @rolecodes = ('cm'); 
1.1002    raeburn  5422:                             my $spec=$$role.'.'.$$where;
                   5423:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5424:                             if ($$role =~ /^cr\//) {
                   5425:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5426:                                 push(@rolecodes,'cr');
1.1002    raeburn  5427:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5428:                                 push(@rolecodes,$$role);
1.1002    raeburn  5429:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5430:                                                     $env{'user.name'});
1.1064    raeburn  5431:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5432:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5433:                                 $group_privs = &unescape($group_privs);
                   5434:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5435:                                 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  5436:                                 &get_groups_roles($tdomain,$trest,
                   5437:                                                   \%course_roles,\@rolecodes,
                   5438:                                                   \%groups_roles);
1.1002    raeburn  5439:                             } else {
1.1064    raeburn  5440:                                 push(@rolecodes,$$role);
1.1002    raeburn  5441:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5442:                             }
1.1064    raeburn  5443:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5444:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5445:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5446:                         }
                   5447:                     }
1.1034    raeburn  5448:                     $$tstatus = 'is';
1.1002    raeburn  5449:                 }
1.994     raeburn  5450:             }
                   5451:             if ($$tend) {
1.1104    raeburn  5452:                 if ($$tend<$update) {
1.994     raeburn  5453:                     $$tstatus='expired';
                   5454:                 } elsif ($$tend<$now) {
                   5455:                     $$tstatus='will_not';
                   5456:                 }
                   5457:             }
                   5458:         }
                   5459:     }
                   5460: }
                   5461: 
1.1104    raeburn  5462: sub get_groups_roles {
                   5463:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5464:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5465:                   (ref($rolecodes) eq 'ARRAY') && 
                   5466:                   (ref($groups_roles) eq 'HASH')); 
                   5467:     if (keys(%{$cdom_courseroles}) > 0) {
                   5468:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5469:         if ($cdom ne '' && $cnum ne '') {
                   5470:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5471:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5472:                     my $crsrole = $1;
                   5473:                     my $crssec = $2;
                   5474:                     if ($crsrole =~ /^cr/) {
                   5475:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5476:                             push(@{$rolecodes},'cr');
                   5477:                         }
                   5478:                     } else {
                   5479:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5480:                             push(@{$rolecodes},$crsrole);
                   5481:                         }
                   5482:                     }
                   5483:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5484:                     if ($crssec ne '') {
                   5485:                         $rolekey .= "/$crssec";
                   5486:                     }
                   5487:                     $rolekey .= './';
                   5488:                     $groups_roles->{$rolekey} = $rolecodes;
                   5489:                 }
                   5490:             }
                   5491:         }
                   5492:     }
                   5493:     return;
                   5494: }
                   5495: 
                   5496: sub delete_env_groupprivs {
                   5497:     my ($where,$courseroles,$possroles) = @_;
                   5498:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5499:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5500:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5501:         %{$courseroles->{$udom}} =
                   5502:             &get_my_roles('','','userroles',['active'],
                   5503:                           $possroles,[$udom],1);
                   5504:     }
                   5505:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5506:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5507:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5508:             my $area = '/'.$cdom.'/'.$cnum;
                   5509:             my $privkey = "user.priv.$crsrole.$area";
                   5510:             if ($crssec ne '') {
                   5511:                 $privkey .= '/'.$crssec;
                   5512:             }
                   5513:             $privkey .= ".$area/$group";
                   5514:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5515:         }
                   5516:     }
                   5517:     return;
                   5518: }
                   5519: 
1.994     raeburn  5520: sub check_adhoc_privs {
1.1104    raeburn  5521:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5522:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5523:     my $setprivs;
1.994     raeburn  5524:     if ($env{$cckey}) {
                   5525:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5526:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5527:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5528:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5529:             $setprivs = 1;
1.994     raeburn  5530:         }
                   5531:     } else {
1.1088    raeburn  5532:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5533:         $setprivs = 1;
1.994     raeburn  5534:     }
1.1185    raeburn  5535:     return $setprivs;
1.994     raeburn  5536: }
                   5537: 
                   5538: sub set_adhoc_privileges {
                   5539: # role can be cc or ca
1.1088    raeburn  5540:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5541:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5542:     my $spec = $role.'.'.$area;
                   5543:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5544:                                   $env{'user.name'},1);
1.994     raeburn  5545:     my %ccrole = ();
                   5546:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5547:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5548:     &appenv(\%userroles,[$role,'cm']);
                   5549:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5550:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5551:         &appenv( {'request.role'        => $spec,
                   5552:                   'request.role.domain' => $dcdom,
                   5553:                   'request.course.sec'  => ''
                   5554:                  }
                   5555:                );
                   5556:         my $tadv=0;
                   5557:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5558:         &appenv({'request.role.adv'    => $tadv});
                   5559:     }
1.994     raeburn  5560: }
                   5561: 
1.12      www      5562: # --------------------------------------------------------------- get interface
                   5563: 
                   5564: sub get {
1.131     albertel 5565:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5566:    my $items='';
1.800     albertel 5567:    foreach my $item (@$storearr) {
                   5568:        $items.=&escape($item).'&';
1.191     harris41 5569:    }
1.12      www      5570:    $items=~s/\&$//;
1.620     albertel 5571:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5572:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5573:    my $uhome=&homeserver($uname,$udomain);
                   5574: 
1.133     albertel 5575:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5576:    my @pairs=split(/\&/,$rep);
1.273     albertel 5577:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5578:      return @pairs;
                   5579:    }
1.15      www      5580:    my %returnhash=();
1.42      www      5581:    my $i=0;
1.800     albertel 5582:    foreach my $item (@$storearr) {
                   5583:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5584:       $i++;
1.191     harris41 5585:    }
1.15      www      5586:    return %returnhash;
1.27      www      5587: }
                   5588: 
                   5589: # --------------------------------------------------------------- del interface
                   5590: 
                   5591: sub del {
1.133     albertel 5592:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5593:    my $items='';
1.800     albertel 5594:    foreach my $item (@$storearr) {
                   5595:        $items.=&escape($item).'&';
1.191     harris41 5596:    }
1.984     neumanie 5597: 
1.27      www      5598:    $items=~s/\&$//;
1.620     albertel 5599:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5600:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5601:    my $uhome=&homeserver($uname,$udomain);
                   5602:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5603: }
                   5604: 
                   5605: # -------------------------------------------------------------- dump interface
                   5606: 
1.1180    droeschl 5607: sub unserialize {
                   5608:     my ($rep, $escapedkeys) = @_;
                   5609: 
                   5610:     return {} if $rep =~ /^error/;
                   5611: 
                   5612:     my %returnhash=();
1.1252    raeburn  5613: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5614: 	    my ($key, $value) = split(/=/, $item, 2);
                   5615: 	    $key = unescape($key) unless $escapedkeys;
                   5616: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5617: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5618: 	}
                   5619:     #return %returnhash;
                   5620:     return \%returnhash;
                   5621: }        
                   5622: 
                   5623: # see Lond::dump_with_regexp
                   5624: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5625: sub dump {
1.1180    droeschl 5626:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5627:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5628:     if (!$uname) { $uname=$env{'user.name'}; }
                   5629:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5630: 
1.1180    droeschl 5631:     my $reply;
                   5632:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5633:         # user is hosted on this machine
                   5634:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5635:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5636:         return %{unserialize($reply, $escapedkeys)};
                   5637:     }
1.755     albertel 5638:     if ($regexp) {
                   5639: 	$regexp=&escape($regexp);
                   5640:     } else {
                   5641: 	$regexp='.';
                   5642:     }
1.1166    raeburn  5643:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5644:     my @pairs=split(/\&/,$rep);
                   5645:     my %returnhash=();
1.1098    foxr     5646:     if (!($rep =~ /^error/ )) {
                   5647: 	foreach my $item (@pairs) {
                   5648: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5649:         $key = unescape($key) unless $escapedkeys;
                   5650:         #$key = &unescape($key);
1.1098    foxr     5651: 	    next if ($key =~ /^error: 2 /);
                   5652: 	    $returnhash{$key}=&thaw_unescape($value);
                   5653: 	}
1.755     albertel 5654:     }
                   5655:     return %returnhash;
1.407     www      5656: }
                   5657: 
1.1098    foxr     5658: 
1.717     albertel 5659: # --------------------------------------------------------- dumpstore interface
                   5660: 
                   5661: sub dumpstore {
                   5662:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5663:    # same as dump but keys must be escaped. They may contain colon separated
                   5664:    # lists of values that may themself contain colons (e.g. symbs).
                   5665:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5666: }
                   5667: 
1.407     www      5668: # -------------------------------------------------------------- keys interface
                   5669: 
                   5670: sub getkeys {
                   5671:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5672:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5673:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5674:    my $uhome=&homeserver($uname,$udomain);
                   5675:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5676:    my @keyarray=();
1.800     albertel 5677:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5678:       next if ($key =~ /^error: 2 /);
1.800     albertel 5679:       push(@keyarray,&unescape($key));
1.407     www      5680:    }
                   5681:    return @keyarray;
1.318     matthew  5682: }
                   5683: 
1.319     matthew  5684: # --------------------------------------------------------------- currentdump
                   5685: sub currentdump {
1.328     matthew  5686:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5687:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5688:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5689:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5690:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5691:    my $rep;
                   5692: 
                   5693:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5694:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5695:                    $courseid)));
                   5696:    } else {
                   5697:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5698:    }
                   5699: 
1.318     matthew  5700:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5701:    #
1.318     matthew  5702:    my %returnhash=();
1.319     matthew  5703:    #
                   5704:    if ($rep eq "unknown_cmd") { 
                   5705:        # an old lond will not know currentdump
                   5706:        # Do a dump and make it look like a currentdump
1.822     albertel 5707:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5708:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5709:        my %hash = @tmp;
                   5710:        @tmp=();
1.424     matthew  5711:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5712:    } else {
                   5713:        my @pairs=split(/\&/,$rep);
1.800     albertel 5714:        foreach my $pair (@pairs) {
                   5715:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5716:            my ($symb,$param) = split(/:/,$key);
                   5717:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5718:                                                         &thaw_unescape($value);
1.319     matthew  5719:        }
1.191     harris41 5720:    }
1.12      www      5721:    return %returnhash;
1.424     matthew  5722: }
                   5723: 
                   5724: sub convert_dump_to_currentdump{
                   5725:     my %hash = %{shift()};
                   5726:     my %returnhash;
                   5727:     # Code ripped from lond, essentially.  The only difference
                   5728:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5729:     # we might run in to problems with parameter names =~ /^v\./
                   5730:     while (my ($key,$value) = each(%hash)) {
                   5731:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5732: 	$symb  = &unescape($symb);
                   5733: 	$param = &unescape($param);
1.424     matthew  5734:         next if ($v eq 'version' || $symb eq 'keys');
                   5735:         next if (exists($returnhash{$symb}) &&
                   5736:                  exists($returnhash{$symb}->{$param}) &&
                   5737:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5738:         $returnhash{$symb}->{$param}=$value;
                   5739:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5740:     }
                   5741:     #
                   5742:     # Remove all of the keys in the hashes which keep track of
                   5743:     # the version of the parameter.
                   5744:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5745:         # use a foreach because we are going to delete from the hash.
                   5746:         foreach my $key (keys(%$param_hash)) {
                   5747:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5748:         }
                   5749:     }
                   5750:     return \%returnhash;
1.12      www      5751: }
                   5752: 
1.627     albertel 5753: # ------------------------------------------------------ critical inc interface
                   5754: 
                   5755: sub cinc {
                   5756:     return &inc(@_,'critical');
                   5757: }
                   5758: 
1.449     matthew  5759: # --------------------------------------------------------------- inc interface
                   5760: 
                   5761: sub inc {
1.627     albertel 5762:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5763:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5764:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5765:     my $uhome=&homeserver($uname,$udomain);
                   5766:     my $items='';
                   5767:     if (! ref($store)) {
                   5768:         # got a single value, so use that instead
                   5769:         $items = &escape($store).'=&';
                   5770:     } elsif (ref($store) eq 'SCALAR') {
                   5771:         $items = &escape($$store).'=&';        
                   5772:     } elsif (ref($store) eq 'ARRAY') {
                   5773:         $items = join('=&',map {&escape($_);} @{$store});
                   5774:     } elsif (ref($store) eq 'HASH') {
                   5775:         while (my($key,$value) = each(%{$store})) {
                   5776:             $items.= &escape($key).'='.&escape($value).'&';
                   5777:         }
                   5778:     }
                   5779:     $items=~s/\&$//;
1.627     albertel 5780:     if ($critical) {
                   5781: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5782:     } else {
                   5783: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5784:     }
1.449     matthew  5785: }
                   5786: 
1.12      www      5787: # --------------------------------------------------------------- put interface
                   5788: 
                   5789: sub put {
1.134     albertel 5790:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5791:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5792:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5793:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5794:    my $items='';
1.800     albertel 5795:    foreach my $item (keys(%$storehash)) {
                   5796:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5797:    }
1.12      www      5798:    $items=~s/\&$//;
1.134     albertel 5799:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5800: }
                   5801: 
1.631     albertel 5802: # ------------------------------------------------------------ newput interface
                   5803: 
                   5804: sub newput {
                   5805:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5806:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5807:    if (!$uname) { $uname=$env{'user.name'}; }
                   5808:    my $uhome=&homeserver($uname,$udomain);
                   5809:    my $items='';
                   5810:    foreach my $key (keys(%$storehash)) {
                   5811:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5812:    }
                   5813:    $items=~s/\&$//;
                   5814:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5815: }
                   5816: 
                   5817: # ---------------------------------------------------------  putstore interface
                   5818: 
1.524     raeburn  5819: sub putstore {
1.715     albertel 5820:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5821:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5822:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5823:    my $uhome=&homeserver($uname,$udomain);
                   5824:    my $items='';
1.715     albertel 5825:    foreach my $key (keys(%$storehash)) {
                   5826:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5827:    }
1.715     albertel 5828:    $items=~s/\&$//;
1.716     albertel 5829:    my $esc_symb=&escape($symb);
                   5830:    my $esc_v=&escape($version);
1.715     albertel 5831:    my $reply =
1.716     albertel 5832:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5833: 	      $uhome);
                   5834:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5835:        # gfall back to way things use to be done
1.715     albertel 5836:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5837: 			    $uname);
1.524     raeburn  5838:    }
1.715     albertel 5839:    return $reply;
                   5840: }
                   5841: 
                   5842: sub old_putstore {
1.716     albertel 5843:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5844:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5845:     if (!$uname) { $uname=$env{'user.name'}; }
                   5846:     my $uhome=&homeserver($uname,$udomain);
                   5847:     my %newstorehash;
1.800     albertel 5848:     foreach my $item (keys(%$storehash)) {
                   5849: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5850: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5851:     }
                   5852:     my $items='';
                   5853:     my %allitems = ();
1.800     albertel 5854:     foreach my $item (keys(%newstorehash)) {
                   5855: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5856: 	    my $key = $1.':keys:'.$2;
                   5857: 	    $allitems{$key} .= $3.':';
                   5858: 	}
1.800     albertel 5859: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5860:     }
1.800     albertel 5861:     foreach my $item (keys(%allitems)) {
                   5862: 	$allitems{$item} =~ s/\:$//;
                   5863: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5864:     }
                   5865:     $items=~s/\&$//;
                   5866:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5867: }
                   5868: 
1.47      www      5869: # ------------------------------------------------------ critical put interface
                   5870: 
                   5871: sub cput {
1.134     albertel 5872:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5873:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5874:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5875:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5876:    my $items='';
1.800     albertel 5877:    foreach my $item (keys(%$storehash)) {
                   5878:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5879:    }
1.47      www      5880:    $items=~s/\&$//;
1.134     albertel 5881:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5882: }
                   5883: 
                   5884: # -------------------------------------------------------------- eget interface
                   5885: 
                   5886: sub eget {
1.133     albertel 5887:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5888:    my $items='';
1.800     albertel 5889:    foreach my $item (@$storearr) {
                   5890:        $items.=&escape($item).'&';
1.191     harris41 5891:    }
1.12      www      5892:    $items=~s/\&$//;
1.620     albertel 5893:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5894:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5895:    my $uhome=&homeserver($uname,$udomain);
                   5896:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5897:    my @pairs=split(/\&/,$rep);
                   5898:    my %returnhash=();
1.42      www      5899:    my $i=0;
1.800     albertel 5900:    foreach my $item (@$storearr) {
                   5901:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5902:       $i++;
1.191     harris41 5903:    }
1.12      www      5904:    return %returnhash;
                   5905: }
                   5906: 
1.667     albertel 5907: # ------------------------------------------------------------ tmpput interface
                   5908: sub tmpput {
1.802     raeburn  5909:     my ($storehash,$server,$context)=@_;
1.667     albertel 5910:     my $items='';
1.800     albertel 5911:     foreach my $item (keys(%$storehash)) {
                   5912: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5913:     }
                   5914:     $items=~s/\&$//;
1.802     raeburn  5915:     if (defined($context)) {
                   5916:         $items .= ':'.&escape($context);
                   5917:     }
1.667     albertel 5918:     return &reply("tmpput:$items",$server);
                   5919: }
                   5920: 
                   5921: # ------------------------------------------------------------ tmpget interface
                   5922: sub tmpget {
1.688     albertel 5923:     my ($token,$server)=@_;
                   5924:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5925:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5926:     my %returnhash;
                   5927:     foreach my $item (split(/\&/,$rep)) {
                   5928: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5929:         next if ($key =~ /^error: 2 /);
1.667     albertel 5930: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5931:     }
                   5932:     return %returnhash;
                   5933: }
                   5934: 
1.1113    raeburn  5935: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5936: sub tmpdel {
                   5937:     my ($token,$server)=@_;
                   5938:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5939:     return &reply("tmpdel:$token",$server);
                   5940: }
                   5941: 
1.1198    raeburn  5942: # ------------------------------------------------------------ get_timebased_id 
                   5943: 
                   5944: sub get_timebased_id {
                   5945:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5946:         $maxtries) = @_;
                   5947:     my ($newid,$error,$dellock);
                   5948:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5949:         return ('','ok','invalid call to get suffix');
                   5950:     }
                   5951: 
                   5952: # set defaults for any optional args for which values were not supplied
                   5953:     if ($who eq '') {
                   5954:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5955:     }
                   5956:     if (!$locktries) {
                   5957:         $locktries = 3;
                   5958:     }
                   5959:     if (!$maxtries) {
                   5960:         $maxtries = 10;
                   5961:     }
                   5962:     
                   5963:     if (($cdom eq '') || ($cnum eq '')) {
                   5964:         if ($env{'request.course.id'}) {
                   5965:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5966:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5967:         }
                   5968:         if (($cdom eq '') || ($cnum eq '')) {
                   5969:             return ('','ok','call to get suffix not in course context');
                   5970:         }
                   5971:     }
                   5972: 
                   5973: # construct locking item
                   5974:     my $lockhash = {
                   5975:                       $prefix."\0".'locked_'.$keyid => $who,
                   5976:                    };
                   5977:     my $tries = 0;
                   5978: 
                   5979: # attempt to get lock on nohist_$namespace file
                   5980:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5981:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5982:         $tries ++;
                   5983:         sleep 1;
                   5984:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5985:     }
                   5986: 
                   5987: # attempt to get unique identifier, based on current timestamp
                   5988:     if ($gotlock eq 'ok') {
                   5989:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5990:         my $id = time;
                   5991:         $newid = $id;
                   5992:         my $idtries = 0;
                   5993:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5994:             if ($idtype eq 'concat') {
                   5995:                 $newid = $id.$idtries;
                   5996:             } else {
                   5997:                 $newid ++;
                   5998:             }
                   5999:             $idtries ++;
                   6000:         }
                   6001:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6002:             my %new_item =  (
                   6003:                               $prefix."\0".$newid => $who,
                   6004:                             );
                   6005:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6006:                                                  $cdom,$cnum);
                   6007:             if ($putresult ne 'ok') {
                   6008:                 undef($newid);
                   6009:                 $error = 'error saving new item: '.$putresult;
                   6010:             }
                   6011:         } else {
                   6012:              $error = ('error: no unique suffix available for the new item ');
                   6013:         }
                   6014: #  remove lock
                   6015:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6016:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6017:     } else {
                   6018:         $error = "error: could not obtain lockfile\n";
                   6019:         $dellock = 'ok';
                   6020:     }
                   6021:     return ($newid,$dellock,$error);
                   6022: }
                   6023: 
1.765     albertel 6024: # -------------------------------------------------- portfolio access checking
                   6025: 
                   6026: sub portfolio_access {
1.766     albertel 6027:     my ($requrl) = @_;
1.765     albertel 6028:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6029:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6030:     if ($result) {
                   6031:         my %setters;
                   6032:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6033:             my ($startblock,$endblock) =
                   6034:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6035:             if ($startblock && $endblock) {
                   6036:                 return 'B';
                   6037:             }
                   6038:         } else {
                   6039:             my ($startblock,$endblock) =
                   6040:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6041:             if ($startblock && $endblock) {
                   6042:                 return 'B';
                   6043:             }
                   6044:         }
                   6045:     }
1.765     albertel 6046:     if ($result eq 'ok') {
1.766     albertel 6047:        return 'F';
1.765     albertel 6048:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6049:        return 'A';
1.765     albertel 6050:     }
1.766     albertel 6051:     return '';
1.765     albertel 6052: }
                   6053: 
                   6054: sub get_portfolio_access {
1.767     albertel 6055:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6056: 
                   6057:     if (!ref($access_hash)) {
                   6058: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6059: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6060: 						   $file_name);
                   6061: 	$access_hash = $access_controls{$file_name};
                   6062:     }
                   6063: 
1.765     albertel 6064:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6065:     my $now = time;
                   6066:     if (ref($access_hash) eq 'HASH') {
                   6067:         foreach my $key (keys(%{$access_hash})) {
                   6068:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6069:             if ($start > $now) {
                   6070:                 next;
                   6071:             }
                   6072:             if ($end && $end<$now) {
                   6073:                 next;
                   6074:             }
                   6075:             if ($scope eq 'public') {
                   6076:                 $public = $key;
                   6077:                 last;
                   6078:             } elsif ($scope eq 'guest') {
                   6079:                 $guest = $key;
                   6080:             } elsif ($scope eq 'domains') {
                   6081:                 push(@domains,$key);
                   6082:             } elsif ($scope eq 'users') {
                   6083:                 push(@users,$key);
                   6084:             } elsif ($scope eq 'course') {
                   6085:                 push(@courses,$key);
                   6086:             } elsif ($scope eq 'group') {
                   6087:                 push(@groups,$key);
                   6088:             }
                   6089:         }
                   6090:         if ($public) {
                   6091:             return 'ok';
                   6092:         }
                   6093:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6094:             if ($guest) {
                   6095:                 return $guest;
                   6096:             }
                   6097:         } else {
                   6098:             if (@domains > 0) {
                   6099:                 foreach my $domkey (@domains) {
                   6100:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6101:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6102:                             return 'ok';
                   6103:                         }
                   6104:                     }
                   6105:                 }
                   6106:             }
                   6107:             if (@users > 0) {
                   6108:                 foreach my $userkey (@users) {
1.865     raeburn  6109:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6110:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6111:                             if (ref($item) eq 'HASH') {
                   6112:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6113:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6114:                                     return 'ok';
                   6115:                                 }
                   6116:                             }
                   6117:                         }
                   6118:                     } 
1.765     albertel 6119:                 }
                   6120:             }
                   6121:             my %roleshash;
                   6122:             my @courses_and_groups = @courses;
                   6123:             push(@courses_and_groups,@groups); 
                   6124:             if (@courses_and_groups > 0) {
                   6125:                 my (%allgroups,%allroles); 
                   6126:                 my ($start,$end,$role,$sec,$group);
                   6127:                 foreach my $envkey (%env) {
1.1060    raeburn  6128:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6129:                         my $cid = $2.'_'.$3; 
                   6130:                         if ($1 eq 'gr') {
                   6131:                             $group = $4;
                   6132:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6133:                         } else {
                   6134:                             if ($4 eq '') {
                   6135:                                 $sec = 'none';
                   6136:                             } else {
                   6137:                                 $sec = $4;
                   6138:                             }
                   6139:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6140:                         }
1.811     albertel 6141:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6142:                         my $cid = $2.'_'.$3;
                   6143:                         if ($4 eq '') {
                   6144:                             $sec = 'none';
                   6145:                         } else {
                   6146:                             $sec = $4;
                   6147:                         }
                   6148:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6149:                     }
                   6150:                 }
                   6151:                 if (keys(%allroles) == 0) {
                   6152:                     return;
                   6153:                 }
                   6154:                 foreach my $key (@courses_and_groups) {
                   6155:                     my %content = %{$$access_hash{$key}};
                   6156:                     my $cnum = $content{'number'};
                   6157:                     my $cdom = $content{'domain'};
                   6158:                     my $cid = $cdom.'_'.$cnum;
                   6159:                     if (!exists($allroles{$cid})) {
                   6160:                         next;
                   6161:                     }    
                   6162:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6163:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6164:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6165:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6166:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6167:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6168:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6169:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6170:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6171:                                         if (grep/^all$/,@sections) {
                   6172:                                             return 'ok';
                   6173:                                         } else {
                   6174:                                             if (grep/^$sec$/,@sections) {
                   6175:                                                 return 'ok';
                   6176:                                             }
                   6177:                                         }
                   6178:                                     }
                   6179:                                 }
                   6180:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6181:                                     if (grep/^none$/,@groups) {
                   6182:                                         return 'ok';
                   6183:                                     }
                   6184:                                 } else {
                   6185:                                     if (grep/^all$/,@groups) {
                   6186:                                         return 'ok';
                   6187:                                     } 
                   6188:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6189:                                         if (grep/^$group$/,@groups) {
                   6190:                                             return 'ok';
                   6191:                                         }
                   6192:                                     }
                   6193:                                 } 
                   6194:                             }
                   6195:                         }
                   6196:                     }
                   6197:                 }
                   6198:             }
                   6199:             if ($guest) {
                   6200:                 return $guest;
                   6201:             }
                   6202:         }
                   6203:     }
                   6204:     return;
                   6205: }
                   6206: 
                   6207: sub course_group_datechecker {
                   6208:     my ($dates,$now,$status) = @_;
                   6209:     my ($start,$end) = split(/\./,$dates);
                   6210:     if (!$start && !$end) {
                   6211:         return 'ok';
                   6212:     }
                   6213:     if (grep/^active$/,@{$status}) {
                   6214:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6215:             return 'ok';
                   6216:         }
                   6217:     }
                   6218:     if (grep/^previous$/,@{$status}) {
                   6219:         if ($end > $now ) {
                   6220:             return 'ok';
                   6221:         }
                   6222:     }
                   6223:     if (grep/^future$/,@{$status}) {
                   6224:         if ($start > $now) {
                   6225:             return 'ok';
                   6226:         }
                   6227:     }
                   6228:     return; 
                   6229: }
                   6230: 
                   6231: sub parse_portfolio_url {
                   6232:     my ($url) = @_;
                   6233: 
                   6234:     my ($type,$udom,$unum,$group,$file_name);
                   6235:     
1.823     albertel 6236:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6237: 	$type = 1;
                   6238:         $udom = $1;
                   6239:         $unum = $2;
                   6240:         $file_name = $3;
1.823     albertel 6241:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6242: 	$type = 2;
                   6243:         $udom = $1;
                   6244:         $unum = $2;
                   6245:         $group = $3;
                   6246:         $file_name = $3.'/'.$4;
                   6247:     }
                   6248:     if (wantarray) {
                   6249: 	return ($type,$udom,$unum,$file_name,$group);
                   6250:     }
                   6251:     return $type;
                   6252: }
                   6253: 
                   6254: sub is_portfolio_url {
                   6255:     my ($url) = @_;
                   6256:     return scalar(&parse_portfolio_url($url));
                   6257: }
                   6258: 
1.798     raeburn  6259: sub is_portfolio_file {
                   6260:     my ($file) = @_;
1.820     raeburn  6261:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6262:         return 1;
                   6263:     }
                   6264:     return;
                   6265: }
                   6266: 
1.976     raeburn  6267: sub usertools_access {
1.1084    raeburn  6268:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6269:     my ($access,%tools);
                   6270:     if ($context eq '') {
                   6271:         $context = 'tools';
                   6272:     }
                   6273:     if ($context eq 'requestcourses') {
                   6274:         %tools = (
                   6275:                       official   => 1,
                   6276:                       unofficial => 1,
1.1006    raeburn  6277:                       community  => 1,
1.1246    raeburn  6278:                       textbook   => 1,
1.985     raeburn  6279:                  );
1.1183    raeburn  6280:     } elsif ($context eq 'requestauthor') {
                   6281:         %tools = (
                   6282:                       requestauthor => 1,
                   6283:                  );
1.985     raeburn  6284:     } else {
                   6285:         %tools = (
                   6286:                       aboutme   => 1,
                   6287:                       blog      => 1,
1.1177    raeburn  6288:                       webdav    => 1,
1.985     raeburn  6289:                       portfolio => 1,
                   6290:                  );
                   6291:     }
1.976     raeburn  6292:     return if (!defined($tools{$tool}));
                   6293: 
1.1242    raeburn  6294:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6295:         $udom = $env{'user.domain'};
                   6296:         $uname = $env{'user.name'};
                   6297:     }
                   6298: 
1.978     raeburn  6299:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6300:         if ($action ne 'reload') {
1.985     raeburn  6301:             if ($context eq 'requestcourses') {
                   6302:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6303:             } elsif ($context eq 'requestauthor') {
                   6304:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6305:             } else {
                   6306:                 return $env{'environment.availabletools.'.$tool};
                   6307:             }
                   6308:         }
1.976     raeburn  6309:     }
                   6310: 
1.1183    raeburn  6311:     my ($toolstatus,$inststatus,$envkey);
                   6312:     if ($context eq 'requestauthor') {
                   6313:         $envkey = $context; 
                   6314:     } else {
                   6315:         $envkey = $context.'.'.$tool;
                   6316:     }
1.976     raeburn  6317: 
1.985     raeburn  6318:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6319:          ($action ne 'reload')) {
1.1183    raeburn  6320:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6321:         $inststatus = $env{'environment.inststatus'};
                   6322:     } else {
1.1084    raeburn  6323:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6324:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6325:             $inststatus = $userenvref->{'inststatus'};
                   6326:         } else {
1.1183    raeburn  6327:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6328:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6329:             $inststatus = $userenv{'inststatus'};
                   6330:         }
1.976     raeburn  6331:     }
                   6332: 
                   6333:     if ($toolstatus ne '') {
                   6334:         if ($toolstatus) {
                   6335:             $access = 1;
                   6336:         } else {
                   6337:             $access = 0;
                   6338:         }
                   6339:         return $access;
                   6340:     }
                   6341: 
1.1084    raeburn  6342:     my ($is_adv,%domdef);
                   6343:     if (ref($is_advref) eq 'HASH') {
                   6344:         $is_adv = $is_advref->{'is_adv'};
                   6345:     } else {
                   6346:         $is_adv = &is_advanced_user($udom,$uname);
                   6347:     }
                   6348:     if (ref($domdefref) eq 'HASH') {
                   6349:         %domdef = %{$domdefref};
                   6350:     } else {
                   6351:         %domdef = &get_domain_defaults($udom);
                   6352:     }
1.976     raeburn  6353:     if (ref($domdef{$tool}) eq 'HASH') {
                   6354:         if ($is_adv) {
                   6355:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6356:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6357:                     $access = 1;
                   6358:                 } else {
                   6359:                     $access = 0;
                   6360:                 }
                   6361:                 return $access;
                   6362:             }
                   6363:         }
                   6364:         if ($inststatus ne '') {
                   6365:             my ($hasaccess,$hasnoaccess);
                   6366:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6367:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6368:                     if ($domdef{$tool}{$affiliation}) {
                   6369:                         $hasaccess = 1;
                   6370:                     } else {
                   6371:                         $hasnoaccess = 1;
                   6372:                     }
                   6373:                 }
                   6374:             }
                   6375:             if ($hasaccess || $hasnoaccess) {
                   6376:                 if ($hasaccess) {
                   6377:                     $access = 1;
                   6378:                 } elsif ($hasnoaccess) {
                   6379:                     $access = 0; 
                   6380:                 }
                   6381:                 return $access;
                   6382:             }
                   6383:         } else {
                   6384:             if ($domdef{$tool}{'default'} ne '') {
                   6385:                 if ($domdef{$tool}{'default'}) {
                   6386:                     $access = 1;
                   6387:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6388:                     $access = 0;
                   6389:                 }
                   6390:                 return $access;
                   6391:             }
                   6392:         }
                   6393:     } else {
1.1177    raeburn  6394:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6395:             $access = 1;
                   6396:         } else {
                   6397:             $access = 0;
                   6398:         }
1.976     raeburn  6399:         return $access;
                   6400:     }
                   6401: }
                   6402: 
1.1050    raeburn  6403: sub is_course_owner {
                   6404:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6405:     if (($udom eq '') || ($uname eq '')) {
                   6406:         $udom = $env{'user.domain'};
                   6407:         $uname = $env{'user.name'};
                   6408:     }
                   6409:     unless (($udom eq '') || ($uname eq '')) {
                   6410:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6411:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6412:                 return 1;
                   6413:             } else {
                   6414:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6415:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6416:                     return 1;
                   6417:                 }
                   6418:             }
                   6419:         }
                   6420:     }
                   6421:     return;
                   6422: }
                   6423: 
1.976     raeburn  6424: sub is_advanced_user {
                   6425:     my ($udom,$uname) = @_;
1.1085    raeburn  6426:     if ($udom ne '' && $uname ne '') {
                   6427:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6428:             if (wantarray) {
                   6429:                 return ($env{'user.adv'},$env{'user.author'});
                   6430:             } else {
                   6431:                 return $env{'user.adv'};
                   6432:             }
1.1085    raeburn  6433:         }
                   6434:     }
1.976     raeburn  6435:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6436:     my %allroles;
1.1128    raeburn  6437:     my ($is_adv,$is_author);
1.976     raeburn  6438:     foreach my $role (keys(%roleshash)) {
                   6439:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6440:         my $area = '/'.$tdomain.'/'.$trest;
                   6441:         if ($sec ne '') {
                   6442:             $area .= '/'.$sec;
                   6443:         }
                   6444:         if (($area ne '') && ($trole ne '')) {
                   6445:             my $spec=$trole.'.'.$area;
                   6446:             if ($trole =~ /^cr\//) {
                   6447:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6448:             } elsif ($trole ne 'gr') {
                   6449:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6450:             }
1.1128    raeburn  6451:             if ($trole eq 'au') {
                   6452:                 $is_author = 1;
                   6453:             }
1.976     raeburn  6454:         }
                   6455:     }
                   6456:     foreach my $role (keys(%allroles)) {
                   6457:         last if ($is_adv);
                   6458:         foreach my $item (split(/:/,$allroles{$role})) {
                   6459:             if ($item ne '') {
                   6460:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6461:                 if ($privilege eq 'adv') {
                   6462:                     $is_adv = 1;
                   6463:                     last;
                   6464:                 }
                   6465:             }
                   6466:         }
                   6467:     }
1.1128    raeburn  6468:     if (wantarray) {
                   6469:         return ($is_adv,$is_author);
                   6470:     }
1.976     raeburn  6471:     return $is_adv;
                   6472: }
1.798     raeburn  6473: 
1.1035    raeburn  6474: sub check_can_request {
1.1036    raeburn  6475:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6476:     my $canreq = 0;
                   6477:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6478:     my @options = ('approval','validate','autolimit');
                   6479:     my $optregex = join('|',@options);
                   6480:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6481:         foreach my $type (@{$types}) {
                   6482:             if (&usertools_access($env{'user.name'},
                   6483:                                   $env{'user.domain'},
                   6484:                                   $type,undef,'requestcourses')) {
                   6485:                 $canreq ++;
1.1036    raeburn  6486:                 if (ref($request_domains) eq 'HASH') {
                   6487:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6488:                 }
1.1035    raeburn  6489:                 if ($dom eq $env{'user.domain'}) {
                   6490:                     $can_request->{$type} = 1;
                   6491:                 }
                   6492:             }
                   6493:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6494:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6495:                 if (@curr > 0) {
1.1036    raeburn  6496:                     foreach my $item (@curr) {
                   6497:                         if (ref($request_domains) eq 'HASH') {
                   6498:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6499:                             if ($otherdom ne '') {
                   6500:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6501:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6502:                                         push(@{$request_domains->{$type}},$otherdom);
                   6503:                                     }
                   6504:                                 } else {
                   6505:                                     push(@{$request_domains->{$type}},$otherdom);
                   6506:                                 }
                   6507:                             }
                   6508:                         }
                   6509:                     }
                   6510:                     unless($dom eq $env{'user.domain'}) {
                   6511:                         $canreq ++;
1.1035    raeburn  6512:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6513:                             $can_request->{$type} = 1;
                   6514:                         }
                   6515:                     }
                   6516:                 }
                   6517:             }
                   6518:         }
                   6519:     }
                   6520:     return $canreq;
                   6521: }
                   6522: 
1.341     www      6523: # ---------------------------------------------- Custom access rule evaluation
                   6524: 
                   6525: sub customaccess {
                   6526:     my ($priv,$uri)=@_;
1.807     albertel 6527:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6528:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6529:     $udom = &LONCAPA::clean_domain($udom);
                   6530:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6531:     my $access=0;
1.800     albertel 6532:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6533: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6534: 	if ($type eq 'user') {
                   6535: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6536: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6537: 		if ($tdom) {
                   6538: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6539: 		}
1.896     albertel 6540: 		if ($tuname) {
                   6541: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6542: 		}
                   6543: 		$access=($effect eq 'allow');
                   6544: 		last;
                   6545: 	    }
                   6546: 	} else {
                   6547: 	    if ($role) {
                   6548: 		if ($role ne $urole) { next; }
                   6549: 	    }
                   6550: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6551: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6552: 		if ($tdom) {
                   6553: 		    if ($tdom ne $udom) { next; }
                   6554: 		}
                   6555: 		if ($tcrs) {
                   6556: 		    if ($tcrs ne $ucrs) { next; }
                   6557: 		}
                   6558: 		if ($tsec) {
                   6559: 		    if ($tsec ne $usec) { next; }
                   6560: 		}
                   6561: 		$access=($effect eq 'allow');
                   6562: 		last;
                   6563: 	    }
                   6564: 	    if ($realm eq '' && $role eq '') {
                   6565: 		$access=($effect eq 'allow');
                   6566: 	    }
1.402     bowersj2 6567: 	}
1.341     www      6568:     }
                   6569:     return $access;
                   6570: }
                   6571: 
1.103     harris41 6572: # ------------------------------------------------- Check for a user privilege
1.12      www      6573: 
                   6574: sub allowed {
1.810     raeburn  6575:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6576:     my $ver_orguri=$uri;
1.439     www      6577:     $uri=&deversion($uri);
1.152     www      6578:     my $orguri=$uri;
1.52      www      6579:     $uri=&declutter($uri);
1.809     raeburn  6580: 
1.810     raeburn  6581:     if ($priv eq 'evb') {
                   6582: # Evade communication block restrictions for specified role in a course
                   6583:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6584:             return $1;
                   6585:         } else {
                   6586:             return;
                   6587:         }
                   6588:     }
                   6589: 
1.620     albertel 6590:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6591: # Free bre access to adm and meta resources
1.775     albertel 6592:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6593: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6594: 	&& ($priv eq 'bre')) {
1.14      www      6595: 	return 'F';
1.159     www      6596:     }
                   6597: 
1.545     banghart 6598: # Free bre access to user's own portfolio contents
1.714     raeburn  6599:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6600:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6601: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6602:         my %setters;
                   6603:         my ($startblock,$endblock) = 
                   6604:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6605:         if ($startblock && $endblock) {
                   6606:             return 'B';
                   6607:         } else {
                   6608:             return 'F';
                   6609:         }
1.545     banghart 6610:     }
                   6611: 
1.762     raeburn  6612: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6613:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6614:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6615:         if (exists($env{'request.course.id'})) {
                   6616:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6617:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6618:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6619:                 my $courseprivid=$env{'request.course.id'};
                   6620:                 $courseprivid=~s/\_/\//;
                   6621:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6622:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6623:                     return $1; 
1.762     raeburn  6624:                 } else {
                   6625:                     if ($env{'request.course.sec'}) {
                   6626:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6627:                     }
                   6628:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6629:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6630:                         return $2;
                   6631:                     }
1.714     raeburn  6632:                 }
                   6633:             }
                   6634:         }
                   6635:     }
                   6636: 
1.159     www      6637: # Free bre to public access
                   6638: 
                   6639:     if ($priv eq 'bre') {
1.238     www      6640:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6641: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6642:            return 'F'; 
                   6643:         }
1.238     www      6644:         if ($copyright eq 'priv') {
                   6645:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6646: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6647: 		return '';
                   6648:             }
                   6649:         }
                   6650:         if ($copyright eq 'domain') {
                   6651:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6652: 	    unless (($env{'user.domain'} eq $1) ||
                   6653:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6654: 		return '';
                   6655:             }
1.262     matthew  6656:         }
1.620     albertel 6657:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6658:             # Library role, so allow browsing of resources in this domain.
                   6659:             return 'F';
1.238     www      6660:         }
1.341     www      6661:         if ($copyright eq 'custom') {
                   6662: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6663:         }
1.14      www      6664:     }
1.264     matthew  6665:     # Domain coordinator is trying to create a course
1.620     albertel 6666:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6667:         # uri is the requested domain in this case.
                   6668:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6669:         # a role of dc for the domain in question.
1.620     albertel 6670:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6671:     }
1.29      www      6672: 
1.52      www      6673:     my $thisallowed='';
                   6674:     my $statecond=0;
                   6675:     my $courseprivid='';
                   6676: 
1.1039    raeburn  6677:     my $ownaccess;
1.1043    raeburn  6678:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6679:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6680:         if ($uri eq '') {
                   6681:             $ownaccess = 1;
                   6682:         } else {
                   6683:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6684:                 my $udom = $env{'user.domain'};
                   6685:                 my $uname = $env{'user.name'};
                   6686:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6687:                     $ownaccess = 1;
1.1040    raeburn  6688:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6689:                     unless ($uri =~ m{\.\./}) {
                   6690:                         $ownaccess = 1;
                   6691:                     }
                   6692:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6693:                     my $now = time;
                   6694:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6695:                         my $adom = $1;
                   6696:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6697:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6698:                                 my ($start,$end) = split('.',$env{$key});
                   6699:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6700:                                     $ownaccess = 1;
                   6701:                                     last;
                   6702:                                 }
                   6703:                             }
                   6704:                         }
                   6705:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6706:                         my $adom = $1;
                   6707:                         my $aname = $2;
1.1042    raeburn  6708:                         foreach my $role ('ca','aa') { 
                   6709:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6710:                                 my ($start,$end) =
                   6711:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6712:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6713:                                     $ownaccess = 1;
                   6714:                                     last;
                   6715:                                 }
1.1039    raeburn  6716:                             }
                   6717:                         }
                   6718:                     }
                   6719:                 }
                   6720:             }
                   6721:         }
                   6722:     }
                   6723: 
1.52      www      6724: # Course
                   6725: 
1.620     albertel 6726:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6727:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6728:             $thisallowed.=$1;
                   6729:         }
1.52      www      6730:     }
1.29      www      6731: 
1.52      www      6732: # Domain
                   6733: 
1.620     albertel 6734:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6735:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6736:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6737:             $thisallowed.=$1;
                   6738:         }
1.12      www      6739:     }
1.52      www      6740: 
1.1141    raeburn  6741: # User who is not author or co-author might still be able to edit
                   6742: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6743:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6744:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6745:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6746:             $thisallowed.=$1;
                   6747:         }
                   6748:     }
                   6749: 
1.52      www      6750: # Course: uri itself is a course
1.66      www      6751:     my $courseuri=$uri;
                   6752:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6753:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6754: 
1.620     albertel 6755:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6756:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6757:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6758:             $thisallowed.=$1;
                   6759:         }
1.12      www      6760:     }
1.29      www      6761: 
1.665     albertel 6762: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6763: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6764:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6765: 	$thisallowed='';
1.671     raeburn  6766:         my ($match)=&is_on_map($uri);
                   6767:         if ($match) {
                   6768:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6769:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6770:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6771:                 if (@blockers > 0) {
                   6772:                     $thisallowed = 'B';
                   6773:                 } else {
                   6774:                     $thisallowed.=$1;
                   6775:                 }
1.671     raeburn  6776:             }
                   6777:         } else {
1.705     albertel 6778:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6779:             if ($refuri) {
                   6780:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6781:                     $thisallowed='F';
1.671     raeburn  6782:                 } else {
                   6783:                     $refuri=&declutter($refuri);
                   6784:                     my ($match) = &is_on_map($refuri);
                   6785:                     if ($match) {
1.1162    raeburn  6786:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6787:                         if (@blockers > 0) {
                   6788:                             $thisallowed = 'B';
                   6789:                         } else {
                   6790:                             $thisallowed='F';
                   6791:                         }
1.671     raeburn  6792:                     }
1.669     raeburn  6793:                 }
1.671     raeburn  6794:             }
                   6795:         }
1.314     www      6796:     }
1.492     albertel 6797: 
1.766     albertel 6798:     if ($priv eq 'bre'
                   6799: 	&& $thisallowed ne 'F' 
                   6800: 	&& $thisallowed ne '2'
                   6801: 	&& &is_portfolio_url($uri)) {
                   6802: 	$thisallowed = &portfolio_access($uri);
                   6803:     }
1.1250    raeburn  6804: 
1.52      www      6805: # Full access at system, domain or course-wide level? Exit.
1.29      www      6806:     if ($thisallowed=~/F/) {
                   6807: 	return 'F';
                   6808:     }
                   6809: 
1.52      www      6810: # If this is generating or modifying users, exit with special codes
1.29      www      6811: 
1.643     www      6812:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6813: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6814: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6815: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6816: 	    unless ($auname) { return $thisallowed; }
                   6817: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6818: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6819: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6820: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6821: 	}
1.52      www      6822: 	return $thisallowed;
                   6823:     }
                   6824: #
1.103     harris41 6825: # Gathered so far: system, domain and course wide privileges
1.52      www      6826: #
                   6827: # Course: See if uri or referer is an individual resource that is part of 
                   6828: # the course
                   6829: 
1.620     albertel 6830:     if ($env{'request.course.id'}) {
1.232     www      6831: 
1.620     albertel 6832:        $courseprivid=$env{'request.course.id'};
                   6833:        if ($env{'request.course.sec'}) {
                   6834:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6835:        }
                   6836:        $courseprivid=~s/\_/\//;
                   6837:        my $checkreferer=1;
1.232     www      6838:        my ($match,$cond)=&is_on_map($uri);
                   6839:        if ($match) {
                   6840:            $statecond=$cond;
1.620     albertel 6841:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6842:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6843:                my $value = $1;
                   6844:                if ($priv eq 'bre') {
                   6845:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6846:                    if (@blockers > 0) {
                   6847:                        $thisallowed = 'B';
                   6848:                    } else {
                   6849:                        $thisallowed.=$value;
                   6850:                    }
                   6851:                } else {
                   6852:                    $thisallowed.=$value;
                   6853:                }
1.52      www      6854:                $checkreferer=0;
                   6855:            }
1.29      www      6856:        }
1.83      www      6857:        
1.148     www      6858:        if ($checkreferer) {
1.620     albertel 6859: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6860:             unless ($refuri) {
1.800     albertel 6861:                 foreach my $key (keys(%env)) {
                   6862: 		    if ($key=~/^httpref\..*\*/) {
                   6863: 			my $pattern=$key;
1.156     www      6864:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6865:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6866:                         $pattern=~s/\//\\\//g;
1.152     www      6867:                         if ($orguri=~/$pattern/) {
1.800     albertel 6868: 			    $refuri=$env{$key};
1.148     www      6869:                         }
                   6870:                     }
1.191     harris41 6871:                 }
1.148     www      6872:             }
1.232     www      6873: 
1.148     www      6874:          if ($refuri) { 
1.152     www      6875: 	  $refuri=&declutter($refuri);
1.232     www      6876:           my ($match,$cond)=&is_on_map($refuri);
                   6877:             if ($match) {
                   6878:               my $refstatecond=$cond;
1.620     albertel 6879:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6880:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6881:                   my $value = $1;
                   6882:                   if ($priv eq 'bre') {
                   6883:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6884:                       if (@blockers > 0) {
                   6885:                           $thisallowed = 'B';
                   6886:                       } else {
                   6887:                           $thisallowed.=$value;
                   6888:                       }
                   6889:                   } else {
                   6890:                       $thisallowed.=$value;
                   6891:                   }
1.53      www      6892:                   $uri=$refuri;
                   6893:                   $statecond=$refstatecond;
1.52      www      6894:               }
                   6895:           }
1.148     www      6896:         }
1.29      www      6897:        }
1.52      www      6898:    }
1.29      www      6899: 
1.52      www      6900: #
1.103     harris41 6901: # Gathered now: all privileges that could apply, and condition number
1.52      www      6902: # 
                   6903: #
                   6904: # Full or no access?
                   6905: #
1.29      www      6906: 
1.52      www      6907:     if ($thisallowed=~/F/) {
                   6908: 	return 'F';
                   6909:     }
1.29      www      6910: 
1.52      www      6911:     unless ($thisallowed) {
                   6912:         return '';
                   6913:     }
1.29      www      6914: 
1.52      www      6915: # Restrictions exist, deal with them
                   6916: #
                   6917: #   C:according to course preferences
                   6918: #   R:according to resource settings
                   6919: #   L:unless locked
                   6920: #   X:according to user session state
                   6921: #
                   6922: 
                   6923: # Possibly locked functionality, check all courses
1.54      www      6924: # Locks might take effect only after 10 minutes cache expiration for other
                   6925: # courses, and 2 minutes for current course
1.52      www      6926: 
                   6927:     my $envkey;
                   6928:     if ($thisallowed=~/L/) {
1.1000    raeburn  6929:         foreach $envkey (keys(%env)) {
1.54      www      6930:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6931:                my $courseid=$2;
                   6932:                my $roleid=$1.'.'.$2;
1.92      www      6933:                $courseid=~s/^\///;
1.54      www      6934:                my $expiretime=600;
1.620     albertel 6935:                if ($env{'request.role'} eq $roleid) {
1.54      www      6936: 		  $expiretime=120;
                   6937:                }
                   6938: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6939:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6940:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6941: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6942:                }
1.620     albertel 6943:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6944:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6945: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6946:                        &log($env{'user.domain'},$env{'user.name'},
                   6947:                             $env{'user.home'},
1.57      www      6948:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6949:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6950:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6951: 		       return '';
                   6952:                    }
                   6953:                }
1.620     albertel 6954:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6955:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6956: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6957:                        &log($env{'user.domain'},$env{'user.name'},
                   6958:                             $env{'user.home'},
1.57      www      6959:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6960:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6961:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6962: 		       return '';
                   6963:                    }
                   6964:                }
                   6965: 	   }
1.29      www      6966:        }
1.52      www      6967:     }
                   6968:    
                   6969: #
                   6970: # Rest of the restrictions depend on selected course
                   6971: #
                   6972: 
1.620     albertel 6973:     unless ($env{'request.course.id'}) {
1.766     albertel 6974: 	if ($thisallowed eq 'A') {
                   6975: 	    return 'A';
1.814     raeburn  6976:         } elsif ($thisallowed eq 'B') {
                   6977:             return 'B';
1.766     albertel 6978: 	} else {
                   6979: 	    return '1';
                   6980: 	}
1.52      www      6981:     }
1.29      www      6982: 
1.52      www      6983: #
                   6984: # Now user is definitely in a course
                   6985: #
1.53      www      6986: 
                   6987: 
                   6988: # Course preferences
                   6989: 
                   6990:    if ($thisallowed=~/C/) {
1.620     albertel 6991:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6992:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6993:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6994: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6995: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6996: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6997: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6998: 			$env{'request.course.id'});
                   6999: 	   }
1.237     www      7000:            return '';
                   7001:        }
                   7002: 
1.620     albertel 7003:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7004: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7005: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7006: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7007: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7008: 			$env{'request.course.id'});
                   7009: 	   }
1.54      www      7010:            return '';
                   7011:        }
1.53      www      7012:    }
                   7013: 
                   7014: # Resource preferences
                   7015: 
                   7016:    if ($thisallowed=~/R/) {
1.620     albertel 7017:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7018:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7019: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7020: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7021: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7022: 	   }
                   7023: 	   return '';
1.54      www      7024:        }
1.53      www      7025:    }
1.30      www      7026: 
1.246     www      7027: # Restricted by state or randomout?
1.30      www      7028: 
1.52      www      7029:    if ($thisallowed=~/X/) {
1.620     albertel 7030:       if ($env{'acc.randomout'}) {
1.579     albertel 7031: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7032:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7033:             return ''; 
                   7034:          }
1.247     www      7035:       }
                   7036:       if (&condval($statecond)) {
1.52      www      7037: 	 return '2';
                   7038:       } else {
                   7039:          return '';
                   7040:       }
                   7041:    }
1.30      www      7042: 
1.766     albertel 7043:     if ($thisallowed eq 'A') {
                   7044: 	return 'A';
1.814     raeburn  7045:     } elsif ($thisallowed eq 'B') {
                   7046:         return 'B';
1.766     albertel 7047:     }
1.52      www      7048:    return 'F';
1.232     www      7049: }
1.1162    raeburn  7050: 
1.1192    raeburn  7051: # ------------------------------------------- Check construction space access
                   7052: 
                   7053: sub constructaccess {
                   7054:     my ($url,$setpriv)=@_;
                   7055: 
                   7056: # We do not allow editing of previous versions of files
                   7057:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7058: 
                   7059: # Get username and domain from URL
                   7060:     my ($ownername,$ownerdomain,$ownerhome);
                   7061: 
                   7062:     ($ownerdomain,$ownername) =
                   7063:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7064: 
                   7065: # The URL does not really point to any authorspace, forget it
                   7066:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7067: 
                   7068: # Now we need to see if the user has access to the authorspace of
                   7069: # $ownername at $ownerdomain
                   7070: 
                   7071:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7072: # Real author for this?
                   7073:        $ownerhome = $env{'user.home'};
                   7074:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7075:           return ($ownername,$ownerdomain,$ownerhome);
                   7076:        }
                   7077:     } else {
                   7078: # Co-author for this?
                   7079:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7080:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7081:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7082:             return ($ownername,$ownerdomain,$ownerhome);
                   7083:         }
                   7084:     }
                   7085: 
                   7086: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7087: # we might as well leave
                   7088:    unless ($setpriv) { return ''; }
                   7089: 
                   7090: # Backdoor access?
                   7091:     my $allowed=&allowed('eco',$ownerdomain);
                   7092: # Nope
                   7093:     unless ($allowed) { return ''; }
                   7094: # Looks like we may have access, but could be locked by the owner of the construction space
                   7095:     if ($allowed eq 'U') {
                   7096:         my %blocked=&get('environment',['domcoord.author'],
                   7097:                          $ownerdomain,$ownername);
                   7098: # Is blocked by owner
                   7099:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7100:     }
                   7101:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7102: # Grant temporary access
                   7103:         my $then=$env{'user.login.time'};
1.1209    raeburn  7104:         my $update=$env{'user.update.time'};
1.1192    raeburn  7105:         if (!$update) { $update = $then; }
                   7106:         my $refresh=$env{'user.refresh.time'};
                   7107:         if (!$refresh) { $refresh = $update; }
                   7108:         my $now = time;
                   7109:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7110:                            $now,'ca','constructaccess');
                   7111:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7112:         return($ownername,$ownerdomain,$ownerhome);
                   7113:     }
                   7114: # No business here
                   7115:     return '';
                   7116: }
                   7117: 
1.1162    raeburn  7118: sub get_comm_blocks {
                   7119:     my ($cdom,$cnum) = @_;
                   7120:     if ($cdom eq '' || $cnum eq '') {
                   7121:         return unless ($env{'request.course.id'});
                   7122:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7123:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7124:     }
                   7125:     my %commblocks;
                   7126:     my $hashid=$cdom.'_'.$cnum;
                   7127:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7128:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7129:         %commblocks = %{$blocksref};
                   7130:     } else {
                   7131:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7132:         my $cachetime = 600;
                   7133:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7134:     }
                   7135:     return %commblocks;
                   7136: }
                   7137: 
                   7138: sub has_comm_blocking {
                   7139:     my ($priv,$symb,$uri,$blocks) = @_;
                   7140:     return unless ($env{'request.course.id'});
                   7141:     return unless ($priv eq 'bre');
                   7142:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7143:     my %commblocks;
                   7144:     if (ref($blocks) eq 'HASH') {
                   7145:         %commblocks = %{$blocks};
                   7146:     } else {
                   7147:         %commblocks = &get_comm_blocks();
                   7148:     }
                   7149:     return unless (keys(%commblocks) > 0);
                   7150:     if (!$symb) { $symb=&symbread($uri,1); }
                   7151:     my ($map,$resid,undef)=&decode_symb($symb);
                   7152:     my %tocheck = (
                   7153:                     maps      => $map,
                   7154:                     resources => $symb,
                   7155:                   );
                   7156:     my @blockers;
                   7157:     my $now = time;
1.1163    raeburn  7158:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7159:     foreach my $block (keys(%commblocks)) {
                   7160:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7161:             my ($start,$end) = ($1,$2);
                   7162:             if ($start <= $now && $end >= $now) {
                   7163:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7164:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7165:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7166:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7167:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7168:                                     push(@blockers,$block);
                   7169:                                 }
                   7170:                             }
                   7171:                         }
                   7172:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7173:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7174:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7175:                                     push(@blockers,$block);
                   7176:                                 }
                   7177:                             }
                   7178:                         }
                   7179:                     }
                   7180:                 }
                   7181:             }
                   7182:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7183:             my $item = $1;
1.1163    raeburn  7184:             my @to_test;
1.1162    raeburn  7185:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7186:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7187:                     my $check_interval;
                   7188:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7189:                         my @interval;
                   7190:                         my $type = 'map';
                   7191:                         if ($item eq 'course') {
                   7192:                             $type = 'course';
                   7193:                             @interval=&EXT("resource.0.interval");
                   7194:                         } else {
                   7195:                             if ($item =~ /___\d+___/) {
                   7196:                                 $type = 'resource';
                   7197:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7198:                                 if (ref($navmap)) {                        
                   7199:                                     my $res = $navmap->getBySymb($item); 
                   7200:                                     push(@to_test,$res);
                   7201:                                 }
1.1162    raeburn  7202:                             } else {
                   7203:                                 my $mapsymb = &symbread($item,1);
                   7204:                                 if ($mapsymb) {
                   7205:                                     if (ref($navmap)) {
                   7206:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7207:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7208:                                         foreach my $res (@to_test) {
1.1162    raeburn  7209:                                             my $symb = $res->symb();
                   7210:                                             next if ($symb eq $mapsymb);
                   7211:                                             if ($symb ne '') {
                   7212:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7213:                                                 last;
                   7214:                                             }
                   7215:                                         }
                   7216:                                     }
                   7217:                                 }
                   7218:                             }
                   7219:                         }
                   7220:                         if ($interval[0] =~ /\d+/) {
                   7221:                             my $first_access;
                   7222:                             if ($type eq 'resource') {
                   7223:                                 $first_access=&get_first_access($interval[1],$item);
                   7224:                             } elsif ($type eq 'map') {
                   7225:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7226:                             } else {
                   7227:                                 $first_access=&get_first_access($interval[1]);
                   7228:                             }
                   7229:                             if ($first_access) {
                   7230:                                 my $timesup = $first_access+$interval[0];
                   7231:                                 if ($timesup > $now) {
1.1163    raeburn  7232:                                     foreach my $res (@to_test) {
                   7233:                                         if ($res->is_problem()) {
                   7234:                                             if ($res->completable()) {
                   7235:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7236:                                                     push(@blockers,$block);
                   7237:                                                 }
                   7238:                                                 last;
                   7239:                                             }
                   7240:                                         }
1.1162    raeburn  7241:                                     }
                   7242:                                 }
                   7243:                             }
                   7244:                         }
                   7245:                     }
                   7246:                 }
                   7247:             }
                   7248:         }
                   7249:     }
                   7250:     return @blockers;
                   7251: }
                   7252: 
                   7253: sub check_docs_block {
                   7254:     my ($docsblock,$tocheck) =@_;
                   7255:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7256:         return;
                   7257:     }
                   7258:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7259:         if ($tocheck->{'maps'}) {
                   7260:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7261:                 return 1;
                   7262:             }
                   7263:         }
                   7264:     }
                   7265:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7266:         if ($tocheck->{'resources'}) {
                   7267:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7268:                 return 1;
                   7269:             }
                   7270:         }
                   7271:     }
                   7272:     return;
                   7273: }
                   7274: 
1.1133    foxr     7275: #
                   7276: #   Removes the versino from a URI and
                   7277: #   splits it in to its filename and path to the filename.
                   7278: #   Seems like File::Basename could have done this more clearly.
                   7279: #   Parameters:
                   7280: #      $uri   - input URI
                   7281: #   Returns:
                   7282: #     Two element list consisting of 
                   7283: #     $pathname  - the URI up to and excluding the trailing /
                   7284: #     $filename  - The part of the URI following the last /
                   7285: #  NOTE:
                   7286: #    Another realization of this is simply:
                   7287: #    use File::Basename;
                   7288: #    ...
                   7289: #    $uri = shift;
                   7290: #    $filename = basename($uri);
                   7291: #    $path     = dirname($uri);
                   7292: #    return ($filename, $path);
                   7293: #
                   7294: #     The implementation below is probably faster however.
                   7295: #
1.710     albertel 7296: sub split_uri_for_cond {
                   7297:     my $uri=&deversion(&declutter(shift));
                   7298:     my @uriparts=split(/\//,$uri);
                   7299:     my $filename=pop(@uriparts);
                   7300:     my $pathname=join('/',@uriparts);
                   7301:     return ($pathname,$filename);
                   7302: }
1.232     www      7303: # --------------------------------------------------- Is a resource on the map?
                   7304: 
                   7305: sub is_on_map {
1.710     albertel 7306:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7307:     #Trying to find the conditional for the file
1.620     albertel 7308:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7309: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7310:     if ($match) {
1.289     bowersj2 7311: 	return (1,$1);
                   7312:     } else {
1.434     www      7313: 	return (0,0);
1.289     bowersj2 7314:     }
1.12      www      7315: }
                   7316: 
1.427     www      7317: # --------------------------------------------------------- Get symb from alias
                   7318: 
                   7319: sub get_symb_from_alias {
                   7320:     my $symb=shift;
                   7321:     my ($map,$resid,$url)=&decode_symb($symb);
                   7322: # Already is a symb
                   7323:     if ($url) { return $symb; }
                   7324: # Must be an alias
                   7325:     my $aliassymb='';
                   7326:     my %bighash;
1.620     albertel 7327:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7328:                             &GDBM_READER(),0640)) {
                   7329:         my $rid=$bighash{'mapalias_'.$symb};
                   7330: 	if ($rid) {
                   7331: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7332: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7333: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7334: 	}
                   7335:         untie %bighash;
                   7336:     }
                   7337:     return $aliassymb;
                   7338: }
                   7339: 
1.12      www      7340: # ----------------------------------------------------------------- Define Role
                   7341: 
                   7342: sub definerole {
                   7343:   if (allowed('mcr','/')) {
                   7344:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7345:     foreach my $role (split(':',$sysrole)) {
                   7346: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7347:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7348:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7349: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7350:                return "refused:s:$crole&$cqual"; 
                   7351:             }
                   7352:         }
1.191     harris41 7353:     }
1.800     albertel 7354:     foreach my $role (split(':',$domrole)) {
                   7355: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7356:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7357:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7358: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7359:                return "refused:d:$crole&$cqual"; 
                   7360:             }
                   7361:         }
1.191     harris41 7362:     }
1.800     albertel 7363:     foreach my $role (split(':',$courole)) {
                   7364: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7365:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7366:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7367: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7368:                return "refused:c:$crole&$cqual"; 
                   7369:             }
                   7370:         }
1.191     harris41 7371:     }
1.620     albertel 7372:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7373:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7374: 	        "rolesdef_$rolename=".
                   7375:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7376:     return reply($command,$env{'user.home'});
1.12      www      7377:   } else {
                   7378:     return 'refused';
                   7379:   }
1.105     harris41 7380: }
                   7381: 
                   7382: # ---------------- Make a metadata query against the network of library servers
                   7383: 
                   7384: sub metadata_query {
1.1237    raeburn  7385:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7386:     my %rhash;
1.845     albertel 7387:     my %libserv = &all_library();
1.244     matthew  7388:     my @server_list = (defined($server_array) ? @$server_array
                   7389:                                               : keys(%libserv) );
                   7390:     for my $server (@server_list) {
1.1237    raeburn  7391:         my $domains = ''; 
                   7392:         if (ref($domains_hash) eq 'HASH') {
                   7393:             $domains = $domains_hash->{$server}; 
                   7394:         }
1.118     harris41 7395: 	unless ($custom or $customshow) {
1.1237    raeburn  7396: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7397: 	    $rhash{$server}=$reply;
                   7398: 	}
                   7399: 	else {
                   7400: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7401: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7402: 			     $server);
                   7403: 	    $rhash{$server}=$reply;
                   7404: 	}
1.112     harris41 7405:     }
1.118     harris41 7406:     return \%rhash;
1.240     www      7407: }
                   7408: 
                   7409: # ----------------------------------------- Send log queries and wait for reply
                   7410: 
                   7411: sub log_query {
                   7412:     my ($uname,$udom,$query,%filters)=@_;
                   7413:     my $uhome=&homeserver($uname,$udom);
                   7414:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7415:     my $uhost=&hostname($uhome);
1.800     albertel 7416:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7417:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7418:                        $uhome);
1.479     albertel 7419:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7420:     return get_query_reply($queryid);
                   7421: }
                   7422: 
1.818     raeburn  7423: # -------------------------- Update MySQL table for portfolio file
                   7424: 
                   7425: sub update_portfolio_table {
1.821     raeburn  7426:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7427:     if ($group ne '') {
                   7428:         $file_name =~s /^\Q$group\E//;
                   7429:     }
1.818     raeburn  7430:     my $homeserver = &homeserver($uname,$udom);
                   7431:     my $queryid=
1.821     raeburn  7432:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7433:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7434:     my $reply = &get_query_reply($queryid);
                   7435:     return $reply;
                   7436: }
                   7437: 
1.899     raeburn  7438: # -------------------------- Update MySQL allusers table
                   7439: 
                   7440: sub update_allusers_table {
                   7441:     my ($uname,$udom,$names) = @_;
                   7442:     my $homeserver = &homeserver($uname,$udom);
                   7443:     my $queryid=
                   7444:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7445:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7446:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7447:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7448:                'generation='.&escape($names->{'generation'}).'%%'.
                   7449:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7450:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7451:     return;
1.899     raeburn  7452: }
                   7453: 
1.508     raeburn  7454: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7455: 
                   7456: sub fetch_enrollment_query {
1.511     raeburn  7457:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7458:     my $homeserver;
1.547     raeburn  7459:     my $maxtries = 1;
1.508     raeburn  7460:     if ($context eq 'automated') {
                   7461:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7462:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7463:     } else {
                   7464:         $homeserver = &homeserver($cnum,$dom);
                   7465:     }
1.838     albertel 7466:     my $host=&hostname($homeserver);
1.506     raeburn  7467:     my $cmd = '';
1.1000    raeburn  7468:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7469:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7470:     }
                   7471:     $cmd =~ s/%%$//;
                   7472:     $cmd = &escape($cmd);
                   7473:     my $query = 'fetchenrollment';
1.620     albertel 7474:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7475:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7476:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7477:         return 'error: '.$queryid;
                   7478:     }
1.506     raeburn  7479:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7480:     my $tries = 1;
                   7481:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7482:         $reply = &get_query_reply($queryid);
                   7483:         $tries ++;
                   7484:     }
1.526     raeburn  7485:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7486:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7487:     } else {
1.901     albertel 7488:         my @responses = split(/:/,$reply);
1.515     raeburn  7489:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7490:             foreach my $line (@responses) {
                   7491:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7492:                 $$replyref{$key} = $value;
                   7493:             }
                   7494:         } else {
1.1117    foxr     7495:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7496:             foreach my $line (@responses) {
                   7497:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7498:                 $$replyref{$key} = $value;
                   7499:                 if ($value > 0) {
1.800     albertel 7500:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7501:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7502:                         my $destname = $pathname.'/'.$filename;
                   7503:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7504:                         if ($xml_classlist =~ /^error/) {
                   7505:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7506:                         } else {
1.506     raeburn  7507:                             if ( open(FILE,">$destname") ) {
                   7508:                                 print FILE &unescape($xml_classlist);
                   7509:                                 close(FILE);
1.526     raeburn  7510:                             } else {
                   7511:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7512:                             }
                   7513:                         }
                   7514:                     }
                   7515:                 }
                   7516:             }
                   7517:         }
                   7518:         return 'ok';
                   7519:     }
                   7520:     return 'error';
                   7521: }
                   7522: 
1.242     www      7523: sub get_query_reply {
                   7524:     my $queryid=shift;
1.1117    foxr     7525:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7526:     my $reply='';
                   7527:     for (1..100) {
                   7528: 	sleep 2;
                   7529:         if (-e $replyfile.'.end') {
1.448     albertel 7530: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7531: 		$reply = join('',<$fh>);
                   7532: 		close($fh);
1.240     www      7533: 	   } else { return 'error: reply_file_error'; }
1.242     www      7534:            return &unescape($reply);
                   7535: 	}
1.240     www      7536:     }
1.242     www      7537:     return 'timeout:'.$queryid;
1.240     www      7538: }
                   7539: 
                   7540: sub courselog_query {
1.241     www      7541: #
                   7542: # possible filters:
                   7543: # url: url or symb
                   7544: # username
                   7545: # domain
                   7546: # action: view, submit, grade
                   7547: # start: timestamp
                   7548: # end: timestamp
                   7549: #
1.240     www      7550:     my (%filters)=@_;
1.620     albertel 7551:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7552:     if ($filters{'url'}) {
                   7553: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7554:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7555:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7556:     }
1.620     albertel 7557:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7558:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7559:     return &log_query($cname,$cdom,'courselog',%filters);
                   7560: }
                   7561: 
                   7562: sub userlog_query {
1.858     raeburn  7563: #
                   7564: # possible filters:
                   7565: # action: log check role
                   7566: # start: timestamp
                   7567: # end: timestamp
                   7568: #
1.240     www      7569:     my ($uname,$udom,%filters)=@_;
                   7570:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7571: }
                   7572: 
1.506     raeburn  7573: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7574: 
                   7575: sub auto_run {
1.508     raeburn  7576:     my ($cnum,$cdom) = @_;
1.876     raeburn  7577:     my $response = 0;
                   7578:     my $settings;
                   7579:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7580:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7581:         $settings = $domconfig{'autoenroll'};
                   7582:         if ($settings->{'run'} eq '1') {
                   7583:             $response = 1;
                   7584:         }
                   7585:     } else {
1.934     raeburn  7586:         my $homeserver;
                   7587:         if (&is_course($cdom,$cnum)) {
                   7588:             $homeserver = &homeserver($cnum,$cdom);
                   7589:         } else {
                   7590:             $homeserver = &domain($cdom,'primary');
                   7591:         }
                   7592:         if ($homeserver ne 'no_host') {
                   7593:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7594:         }
1.876     raeburn  7595:     }
1.506     raeburn  7596:     return $response;
                   7597: }
1.776     albertel 7598: 
1.506     raeburn  7599: sub auto_get_sections {
1.508     raeburn  7600:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7601:     my $homeserver;
                   7602:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7603:         $homeserver = &homeserver($cnum,$cdom);
                   7604:     }
                   7605:     if (!defined($homeserver)) { 
                   7606:         if ($cdom =~ /^$match_domain$/) {
                   7607:             $homeserver = &domain($cdom,'primary');
                   7608:         }
                   7609:     }
                   7610:     my @secs;
                   7611:     if (defined($homeserver)) {
                   7612:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7613:         unless ($response eq 'refused') {
                   7614:             @secs = split(/:/,$response);
                   7615:         }
1.506     raeburn  7616:     }
                   7617:     return @secs;
                   7618: }
1.776     albertel 7619: 
1.506     raeburn  7620: sub auto_new_course {
1.1099    raeburn  7621:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7622:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7623:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7624:     return $response;
                   7625: }
1.776     albertel 7626: 
1.506     raeburn  7627: sub auto_validate_courseID {
1.508     raeburn  7628:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7629:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7630:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7631:     return $response;
                   7632: }
1.776     albertel 7633: 
1.1007    raeburn  7634: sub auto_validate_instcode {
1.1020    raeburn  7635:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7636:     my ($homeserver,$response);
                   7637:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7638:         $homeserver = &homeserver($cnum,$cdom);
                   7639:     }
                   7640:     if (!defined($homeserver)) {
                   7641:         if ($cdom =~ /^$match_domain$/) {
                   7642:             $homeserver = &domain($cdom,'primary');
                   7643:         }
                   7644:     }
1.1065    raeburn  7645:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7646:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7647:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7648:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7649: }
                   7650: 
1.506     raeburn  7651: sub auto_create_password {
1.873     raeburn  7652:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7653:     my ($homeserver,$response);
1.506     raeburn  7654:     my $create_passwd = 0;
                   7655:     my $authchk = '';
1.873     raeburn  7656:     if ($udom =~ /^$match_domain$/) {
                   7657:         $homeserver = &domain($udom,'primary');
                   7658:     }
                   7659:     if ($homeserver eq '') {
                   7660:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7661:             $homeserver = &homeserver($cnum,$cdom);
                   7662:         }
                   7663:     }
                   7664:     if ($homeserver eq '') {
                   7665:         $authchk = 'nodomain';
1.506     raeburn  7666:     } else {
1.873     raeburn  7667:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7668:         if ($response eq 'refused') {
                   7669:             $authchk = 'refused';
                   7670:         } else {
1.901     albertel 7671:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7672:         }
1.506     raeburn  7673:     }
                   7674:     return ($authparam,$create_passwd,$authchk);
                   7675: }
                   7676: 
1.706     raeburn  7677: sub auto_photo_permission {
                   7678:     my ($cnum,$cdom,$students) = @_;
                   7679:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7680:     my ($outcome,$perm_reqd,$conditions) = 
                   7681: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7682:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7683: 	return (undef,undef);
                   7684:     }
1.706     raeburn  7685:     return ($outcome,$perm_reqd,$conditions);
                   7686: }
                   7687: 
                   7688: sub auto_checkphotos {
                   7689:     my ($uname,$udom,$pid) = @_;
                   7690:     my $homeserver = &homeserver($uname,$udom);
                   7691:     my ($result,$resulttype);
                   7692:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7693: 				   &escape($uname).':'.&escape($pid),
                   7694: 				   $homeserver));
1.709     albertel 7695:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7696: 	return (undef,undef);
                   7697:     }
1.706     raeburn  7698:     if ($outcome) {
                   7699:         ($result,$resulttype) = split(/:/,$outcome);
                   7700:     } 
                   7701:     return ($result,$resulttype);
                   7702: }
                   7703: 
                   7704: sub auto_photochoice {
                   7705:     my ($cnum,$cdom) = @_;
                   7706:     my $homeserver = &homeserver($cnum,$cdom);
                   7707:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7708: 						       &escape($cdom),
                   7709: 						       $homeserver)));
1.709     albertel 7710:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7711: 	return (undef,undef);
                   7712:     }
1.706     raeburn  7713:     return ($update,$comment);
                   7714: }
                   7715: 
                   7716: sub auto_photoupdate {
                   7717:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7718:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7719:     my $host=&hostname($homeserver);
1.706     raeburn  7720:     my $cmd = '';
                   7721:     my $maxtries = 1;
1.800     albertel 7722:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7723:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7724:     }
                   7725:     $cmd =~ s/%%$//;
                   7726:     $cmd = &escape($cmd);
                   7727:     my $query = 'institutionalphotos';
                   7728:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7729:     unless ($queryid=~/^\Q$host\E\_/) {
                   7730:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7731:         return 'error: '.$queryid;
                   7732:     }
                   7733:     my $reply = &get_query_reply($queryid);
                   7734:     my $tries = 1;
                   7735:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7736:         $reply = &get_query_reply($queryid);
                   7737:         $tries ++;
                   7738:     }
                   7739:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7740:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7741:     } else {
                   7742:         my @responses = split(/:/,$reply);
                   7743:         my $outcome = shift(@responses); 
                   7744:         foreach my $item (@responses) {
                   7745:             my ($key,$value) = split(/=/,$item);
                   7746:             $$photo{$key} = $value;
                   7747:         }
                   7748:         return $outcome;
                   7749:     }
                   7750:     return 'error';
                   7751: }
                   7752: 
1.521     raeburn  7753: sub auto_instcode_format {
1.793     albertel 7754:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7755: 	$cat_order) = @_;
1.521     raeburn  7756:     my $courses = '';
1.772     raeburn  7757:     my @homeservers;
1.521     raeburn  7758:     if ($caller eq 'global') {
1.841     albertel 7759: 	my %servers = &get_servers($codedom,'library');
                   7760: 	foreach my $tryserver (keys(%servers)) {
                   7761: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7762: 		push(@homeservers,$tryserver);
                   7763: 	    }
1.584     raeburn  7764:         }
1.1022    raeburn  7765:     } elsif ($caller eq 'requests') {
                   7766:         if ($codedom =~ /^$match_domain$/) {
                   7767:             my $chome = &domain($codedom,'primary');
                   7768:             unless ($chome eq 'no_host') {
                   7769:                 push(@homeservers,$chome);
                   7770:             }
                   7771:         }
1.521     raeburn  7772:     } else {
1.772     raeburn  7773:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7774:     }
1.793     albertel 7775:     foreach my $code (keys(%{$instcodes})) {
                   7776:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7777:     }
                   7778:     chop($courses);
1.772     raeburn  7779:     my $ok_response = 0;
                   7780:     my $response;
                   7781:     while (@homeservers > 0 && $ok_response == 0) {
                   7782:         my $server = shift(@homeservers); 
                   7783:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7784:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7785:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7786: 		split(/:/,$response);
1.772     raeburn  7787:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7788:             push(@{$codetitles},&str2array($codetitles_str));
                   7789:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7790:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7791:             $ok_response = 1;
                   7792:         }
                   7793:     }
                   7794:     if ($ok_response) {
1.521     raeburn  7795:         return 'ok';
1.772     raeburn  7796:     } else {
                   7797:         return $response;
1.521     raeburn  7798:     }
                   7799: }
                   7800: 
1.792     raeburn  7801: sub auto_instcode_defaults {
                   7802:     my ($domain,$returnhash,$code_order) = @_;
                   7803:     my @homeservers;
1.841     albertel 7804: 
                   7805:     my %servers = &get_servers($domain,'library');
                   7806:     foreach my $tryserver (keys(%servers)) {
                   7807: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7808: 	    push(@homeservers,$tryserver);
                   7809: 	}
1.792     raeburn  7810:     }
1.841     albertel 7811: 
1.792     raeburn  7812:     my $response;
1.841     albertel 7813:     foreach my $server (@homeservers) {
1.792     raeburn  7814:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7815:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7816: 	
                   7817: 	foreach my $pair (split(/\&/,$response)) {
                   7818: 	    my ($name,$value)=split(/\=/,$pair);
                   7819: 	    if ($name eq 'code_order') {
                   7820: 		@{$code_order} = split(/\&/,&unescape($value));
                   7821: 	    } else {
                   7822: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7823: 	    }
                   7824: 	}
                   7825: 	return 'ok';
1.792     raeburn  7826:     }
1.841     albertel 7827: 
                   7828:     return $response;
1.1003    raeburn  7829: }
                   7830: 
                   7831: sub auto_possible_instcodes {
1.1007    raeburn  7832:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7833:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7834:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7835:         return;
                   7836:     }
1.1003    raeburn  7837:     my (@homeservers,$uhome);
                   7838:     if (defined(&domain($domain,'primary'))) {
                   7839:         $uhome=&domain($domain,'primary');
                   7840:         push(@homeservers,&domain($domain,'primary'));
                   7841:     } else {
                   7842:         my %servers = &get_servers($domain,'library');
                   7843:         foreach my $tryserver (keys(%servers)) {
                   7844:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7845:                 push(@homeservers,$tryserver);
                   7846:             }
                   7847:         }
                   7848:     }
                   7849:     my $response;
                   7850:     foreach my $server (@homeservers) {
                   7851:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7852:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7853:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7854:             split(':',$response);
                   7855:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7856:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7857:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7858:             my ($name,$value)=split('=',$item);
                   7859:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7860:         }
                   7861:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7862:             my ($name,$value)=split('=',$item);
                   7863:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7864:         }
                   7865:         return 'ok';
                   7866:     }
                   7867:     return $response;
                   7868: }
1.792     raeburn  7869: 
1.1010    raeburn  7870: sub auto_courserequest_checks {
                   7871:     my ($dom) = @_;
1.1020    raeburn  7872:     my ($homeserver,%validations);
                   7873:     if ($dom =~ /^$match_domain$/) {
                   7874:         $homeserver = &domain($dom,'primary');
                   7875:     }
                   7876:     unless ($homeserver eq 'no_host') {
                   7877:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7878:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7879:             my @items = split(/&/,$response);
                   7880:             foreach my $item (@items) {
                   7881:                 my ($key,$value) = split('=',$item);
                   7882:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7883:             }
                   7884:         }
                   7885:     }
1.1010    raeburn  7886:     return %validations; 
                   7887: }
                   7888: 
1.1020    raeburn  7889: sub auto_courserequest_validation {
1.1255    raeburn  7890:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  7891:     my ($homeserver,$response);
                   7892:     if ($dom =~ /^$match_domain$/) {
                   7893:         $homeserver = &domain($dom,'primary');
                   7894:     }
1.1255    raeburn  7895:     unless ($homeserver eq 'no_host') {
                   7896:         my $customdata;
                   7897:         if (ref($custominfo) eq 'HASH') {
                   7898:             $customdata = &freeze_escape($custominfo);
                   7899:         }
1.1020    raeburn  7900:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7901:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  7902:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   7903:                                     $customdata,$homeserver));
1.1020    raeburn  7904:     }
                   7905:     return $response;
                   7906: }
                   7907: 
1.777     albertel 7908: sub auto_validate_class_sec {
1.918     raeburn  7909:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7910:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7911:     my $ownerlist;
                   7912:     if (ref($owners) eq 'ARRAY') {
                   7913:         $ownerlist = join(',',@{$owners});
                   7914:     } else {
                   7915:         $ownerlist = $owners;
                   7916:     }
1.773     raeburn  7917:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7918:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7919:     return $response;
                   7920: }
                   7921: 
1.1248    raeburn  7922: sub auto_crsreq_update {
                   7923:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  7924:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  7925:     my ($homeserver,%crsreqresponse);
                   7926:     if ($cdom =~ /^$match_domain$/) {
                   7927:         $homeserver = &domain($cdom,'primary');
                   7928:     }
                   7929:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   7930:         my $info;
                   7931:         if (ref($inbound) eq 'HASH') {
                   7932:             $info = &freeze_escape($inbound);
                   7933:         }
                   7934:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   7935:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   7936:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  7937:                             &escape($title).':'.&escape($code).':'.
                   7938:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   7939:                             $homeserver);
1.1248    raeburn  7940:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7941:             my @items = split(/&/,$response);
                   7942:             foreach my $item (@items) {
                   7943:                 my ($key,$value) = split('=',$item);
                   7944:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   7945:             }
                   7946:         }
                   7947:     }
                   7948:     return \%crsreqresponse;
                   7949: }
                   7950: 
1.679     raeburn  7951: # ------------------------------------------------------- Course Group routines
                   7952: 
                   7953: sub get_coursegroups {
1.809     raeburn  7954:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7955:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7956: }
                   7957: 
1.679     raeburn  7958: sub modify_coursegroup {
                   7959:     my ($cdom,$cnum,$groupsettings) = @_;
                   7960:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7961: }
                   7962: 
1.809     raeburn  7963: sub toggle_coursegroup_status {
                   7964:     my ($cdom,$cnum,$group,$action) = @_;
                   7965:     my ($from_namespace,$to_namespace);
                   7966:     if ($action eq 'delete') {
                   7967:         $from_namespace = 'coursegroups';
                   7968:         $to_namespace = 'deleted_groups';
                   7969:     } else {
                   7970:         $from_namespace = 'deleted_groups';
                   7971:         $to_namespace = 'coursegroups';
                   7972:     }
                   7973:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7974:     if (my $tmp = &error(%curr_group)) {
                   7975:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7976:         return ('read error',$tmp);
                   7977:     } else {
                   7978:         my %savedsettings = %curr_group; 
1.809     raeburn  7979:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7980:         my $deloutcome;
                   7981:         if ($result eq 'ok') {
1.809     raeburn  7982:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7983:         } else {
                   7984:             return ('write error',$result);
                   7985:         }
                   7986:         if ($deloutcome eq 'ok') {
                   7987:             return 'ok';
                   7988:         } else {
                   7989:             return ('delete error',$deloutcome);
                   7990:         }
                   7991:     }
                   7992: }
                   7993: 
1.679     raeburn  7994: sub modify_group_roles {
1.957     raeburn  7995:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7996:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7997:     my $role = 'gr/'.&escape($userprivs);
                   7998:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7999:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8000:     if ($result eq 'ok') {
                   8001:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8002:     }
1.679     raeburn  8003:     return $result;
                   8004: }
                   8005: 
                   8006: sub modify_coursegroup_membership {
                   8007:     my ($cdom,$cnum,$membership) = @_;
                   8008:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8009:     return $result;
                   8010: }
                   8011: 
1.682     raeburn  8012: sub get_active_groups {
                   8013:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8014:     my $now = time;
                   8015:     my %groups = ();
                   8016:     foreach my $key (keys(%env)) {
1.811     albertel 8017:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8018:             my ($start,$end) = split(/\./,$env{$key});
                   8019:             if (($end!=0) && ($end<$now)) { next; }
                   8020:             if (($start!=0) && ($start>$now)) { next; }
                   8021:             if ($1 eq $cdom && $2 eq $cnum) {
                   8022:                 $groups{$3} = $env{$key} ;
                   8023:             }
                   8024:         }
                   8025:     }
                   8026:     return %groups;
                   8027: }
                   8028: 
1.683     raeburn  8029: sub get_group_membership {
                   8030:     my ($cdom,$cnum,$group) = @_;
                   8031:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8032: }
                   8033: 
                   8034: sub get_users_groups {
                   8035:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8036:     my @usersgroups;
1.683     raeburn  8037:     my $cachetime=1800;
                   8038: 
                   8039:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8040:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8041:     if (defined($cached)) {
1.734     albertel 8042:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8043:     } else {  
                   8044:         $grouplist = '';
1.816     raeburn  8045:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8046:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8047:         my $access_end = $env{'course.'.$courseid.
                   8048:                               '.default_enrollment_end_date'};
                   8049:         my $now = time;
                   8050:         foreach my $key (keys(%roleshash)) {
                   8051:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8052:                 my $group = $1;
                   8053:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8054:                     my $start = $2;
                   8055:                     my $end = $1;
                   8056:                     if ($start == -1) { next; } # deleted from group
                   8057:                     if (($start!=0) && ($start>$now)) { next; }
                   8058:                     if (($end!=0) && ($end<$now)) {
                   8059:                         if ($access_end && $access_end < $now) {
                   8060:                             if ($access_end - $end < 86400) {
                   8061:                                 push(@usersgroups,$group);
1.733     raeburn  8062:                             }
                   8063:                         }
1.817     raeburn  8064:                         next;
1.733     raeburn  8065:                     }
1.817     raeburn  8066:                     push(@usersgroups,$group);
1.683     raeburn  8067:                 }
                   8068:             }
                   8069:         }
1.817     raeburn  8070:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8071:         $grouplist = join(':',@usersgroups);
                   8072:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8073:     }
1.733     raeburn  8074:     return @usersgroups;
1.683     raeburn  8075: }
                   8076: 
                   8077: sub devalidate_getgroups_cache {
                   8078:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8079:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8080: 
1.683     raeburn  8081:     my $hashid="$udom:$uname:$courseid";
                   8082:     &devalidate_cache_new('getgroups',$hashid);
                   8083: }
                   8084: 
1.12      www      8085: # ------------------------------------------------------------------ Plain Text
                   8086: 
                   8087: sub plaintext {
1.988     raeburn  8088:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8089:     if ($short =~ m{^cr/}) {
1.758     albertel 8090: 	return (split('/',$short))[-1];
                   8091:     }
1.742     raeburn  8092:     if (!defined($cid)) {
                   8093:         $cid = $env{'request.course.id'};
                   8094:     }
                   8095:     my %rolenames = (
1.1008    raeburn  8096:                       Course    => 'std',
                   8097:                       Community => 'alt1',
1.742     raeburn  8098:                     );
1.1037    raeburn  8099:     if ($cid ne '') {
                   8100:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8101:             unless ($forcedefault) {
                   8102:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8103:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8104:                 return &Apache::lonlocal::mt($roletext);
                   8105:             }
                   8106:         }
                   8107:     }
                   8108:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8109:         (defined($rolenames{$type})) && 
                   8110:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8111:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8112:     } elsif ($cid ne '') {
                   8113:         my $crstype = $env{'course.'.$cid.'.type'};
                   8114:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8115:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8116:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8117:         }
1.742     raeburn  8118:     }
1.1037    raeburn  8119:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8120: }
                   8121: 
                   8122: # ----------------------------------------------------------------- Assign Role
                   8123: 
                   8124: sub assignrole {
1.957     raeburn  8125:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8126:         $context)=@_;
1.21      www      8127:     my $mrole;
                   8128:     if ($role =~ /^cr\//) {
1.393     www      8129:         my $cwosec=$url;
1.811     albertel 8130:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8131: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8132:            my $refused = 1;
                   8133:            if ($context eq 'requestcourses') {
                   8134:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8135:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8136:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8137:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8138:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8139:                            if ($crsenv{'internal.courseowner'} eq
                   8140:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8141:                                $refused = '';
                   8142:                            }
                   8143:                        }
                   8144:                    }
                   8145:                }
                   8146:            }
                   8147:            if ($refused) {
                   8148:                &logthis('Refused custom assignrole: '.
                   8149:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8150:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8151:                return 'refused';
                   8152:            }
1.104     www      8153:         }
1.21      www      8154:         $mrole='cr';
1.678     raeburn  8155:     } elsif ($role =~ /^gr\//) {
                   8156:         my $cwogrp=$url;
1.811     albertel 8157:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8158:         unless (&allowed('mdg',$cwogrp)) {
                   8159:             &logthis('Refused group assignrole: '.
                   8160:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8161:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8162:             return 'refused';
                   8163:         }
                   8164:         $mrole='gr';
1.21      www      8165:     } else {
1.82      www      8166:         my $cwosec=$url;
1.811     albertel 8167:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8168:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8169:             my $refused;
                   8170:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8171:                 if (!(&allowed('c'.$role,$url))) {
                   8172:                     $refused = 1;
                   8173:                 }
                   8174:             } else {
                   8175:                 $refused = 1;
                   8176:             }
1.947     raeburn  8177:             if ($refused) {
1.1045    raeburn  8178:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8179:                 if (!$selfenroll && $context eq 'course') {
                   8180:                     my %crsenv;
                   8181:                     if ($role eq 'cc' || $role eq 'co') {
                   8182:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8183:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8184:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8185:                                 if ($crsenv{'internal.courseowner'} eq 
                   8186:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8187:                                     $refused = '';
                   8188:                                 }
                   8189:                             }
                   8190:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8191:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8192:                                 if ($crsenv{'internal.courseowner'} eq 
                   8193:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8194:                                     $refused = '';
                   8195:                                 }
                   8196:                             }
                   8197:                         }
                   8198:                     }
                   8199:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8200:                     $refused = '';
1.1017    raeburn  8201:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8202:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8203:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8204:                         my $wrongcc;
                   8205:                         if ($cnum =~ /^$match_community$/) {
                   8206:                             $wrongcc = 1 if ($role eq 'cc');
                   8207:                         } else {
                   8208:                             $wrongcc = 1 if ($role eq 'co');
                   8209:                         }
                   8210:                         unless ($wrongcc) {
                   8211:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8212:                             if ($crsenv{'internal.courseowner'} eq 
                   8213:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8214:                                 $refused = '';
                   8215:                             }
1.1017    raeburn  8216:                         }
                   8217:                     }
1.1183    raeburn  8218:                 } elsif ($context eq 'requestauthor') {
                   8219:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8220:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8221:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8222:                             $refused = '';
                   8223:                         } else {
                   8224:                             my %domdefaults = &get_domain_defaults($udom);
                   8225:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8226:                                 my $checkbystatus;
                   8227:                                 if ($env{'user.adv'}) { 
                   8228:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8229:                                     if ($disposition eq 'automatic') {
                   8230:                                         $refused = '';
                   8231:                                     } elsif ($disposition eq '') {
                   8232:                                         $checkbystatus = 1;
                   8233:                                     } 
                   8234:                                 } else {
                   8235:                                     $checkbystatus = 1;
                   8236:                                 }
                   8237:                                 if ($checkbystatus) {
                   8238:                                     if ($env{'environment.inststatus'}) {
                   8239:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8240:                                         foreach my $type (@inststatuses) {
                   8241:                                             if (($type ne '') &&
                   8242:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8243:                                                 $refused = '';
                   8244:                                             }
                   8245:                                         }
                   8246:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8247:                                         $refused = '';
                   8248:                                     }
                   8249:                                 }
                   8250:                             }
                   8251:                         }
                   8252:                     }
1.1017    raeburn  8253:                 }
                   8254:                 if ($refused) {
1.947     raeburn  8255:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8256:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8257: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8258:                     return 'refused';
                   8259:                 }
1.932     raeburn  8260:             }
1.1131    raeburn  8261:         } elsif ($role eq 'au') {
                   8262:             if ($url ne '/'.$udom.'/') {
                   8263:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8264:                          ' to assign author role for '.$uname.':'.$udom.
                   8265:                          ' in domain: '.$url.' refused (wrong domain).');
                   8266:                 return 'refused';
                   8267:             }
1.104     www      8268:         }
1.21      www      8269:         $mrole=$role;
                   8270:     }
1.620     albertel 8271:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8272:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8273:     if ($end) { $command.='_'.$end; }
1.21      www      8274:     if ($start) {
                   8275: 	if ($end) { 
1.81      www      8276:            $command.='_'.$start; 
1.21      www      8277:         } else {
1.81      www      8278:            $command.='_0_'.$start;
1.21      www      8279:         }
                   8280:     }
1.739     raeburn  8281:     my $origstart = $start;
                   8282:     my $origend = $end;
1.957     raeburn  8283:     my $delflag;
1.357     www      8284: # actually delete
                   8285:     if ($deleteflag) {
1.373     www      8286: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8287: # modify command to delete the role
1.620     albertel 8288:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8289:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8290: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8291: # set start and finish to negative values for userrolelog
                   8292:            $start=-1;
                   8293:            $end=-1;
1.957     raeburn  8294:            $delflag = 1;
1.357     www      8295:         }
                   8296:     }
                   8297: # send command
1.349     www      8298:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8299: # log new user role if status is ok
1.349     www      8300:     if ($answer eq 'ok') {
1.663     raeburn  8301: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8302:         if (($role eq 'cc') || ($role eq 'in') ||
                   8303:             ($role eq 'ep') || ($role eq 'ad') ||
                   8304:             ($role eq 'ta') || ($role eq 'st') ||
                   8305:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8306:             ($role eq 'co')) {
1.1200    raeburn  8307: # for course roles, perform group memberships changes triggered by role change.
                   8308:             unless ($role =~ /^gr/) {
                   8309:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8310:                                                  $origstart,$selfenroll,$context);
                   8311:             }
1.1184    raeburn  8312:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8313:                            $selfenroll,$context);
                   8314:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8315:                  ($role eq 'au') || ($role eq 'dc')) {
                   8316:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8317:                            $context);
                   8318:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8319:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8320:                              $context); 
                   8321:         }
1.1053    raeburn  8322:         if ($role eq 'cc') {
                   8323:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8324:         }
1.349     www      8325:     }
                   8326:     return $answer;
1.169     harris41 8327: }
                   8328: 
1.1053    raeburn  8329: sub autoupdate_coowners {
                   8330:     my ($url,$end,$start,$uname,$udom) = @_;
                   8331:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8332:     if (($cdom ne '') && ($cnum ne '')) {
                   8333:         my $now = time;
                   8334:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8335:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8336:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8337:             my $instcode = $coursehash{'internal.coursecode'};
                   8338:             if ($instcode ne '') {
1.1056    raeburn  8339:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8340:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8341:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8342:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8343:                         if ($result eq 'valid') {
                   8344:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8345:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8346:                                     push(@newcoowners,$coowner);
                   8347:                                 }
                   8348:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8349:                                     push(@newcoowners,$uname.':'.$udom);
                   8350:                                 }
                   8351:                                 @newcoowners = sort(@newcoowners);
                   8352:                             } else {
                   8353:                                 push(@newcoowners,$uname.':'.$udom);
                   8354:                             }
                   8355:                         } else {
                   8356:                             if ($coursehash{'internal.co-owners'}) {
                   8357:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8358:                                     unless ($coowner eq $uname.':'.$udom) {
                   8359:                                         push(@newcoowners,$coowner);
                   8360:                                     }
                   8361:                                 }
                   8362:                                 unless (@newcoowners > 0) {
                   8363:                                     $delcoowners = 1;
                   8364:                                     $coowners = '';
                   8365:                                 }
                   8366:                             }
                   8367:                         }
                   8368:                         if (@newcoowners || $delcoowners) {
                   8369:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8370:                                             $delcoowners,@newcoowners);
                   8371:                         }
                   8372:                     }
                   8373:                 }
                   8374:             }
                   8375:         }
                   8376:     }
                   8377: }
                   8378: 
                   8379: sub store_coowners {
                   8380:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8381:     my $cid = $cdom.'_'.$cnum;
                   8382:     my ($coowners,$delresult,$putresult);
                   8383:     if (@newcoowners) {
                   8384:         $coowners = join(',',@newcoowners);
                   8385:         my %coownershash = (
                   8386:                             'internal.co-owners' => $coowners,
                   8387:                            );
                   8388:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8389:         if ($putresult eq 'ok') {
                   8390:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8391:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8392:             }
                   8393:         }
                   8394:     }
                   8395:     if ($delcoowners) {
                   8396:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8397:         if ($delresult eq 'ok') {
                   8398:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8399:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8400:             }
                   8401:         }
                   8402:     }
                   8403:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8404:         my %crsinfo =
                   8405:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8406:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8407:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8408:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8409:         }
                   8410:     }
                   8411: }
                   8412: 
1.169     harris41 8413: # -------------------------------------------------- Modify user authentication
1.197     www      8414: # Overrides without validation
                   8415: 
1.169     harris41 8416: sub modifyuserauth {
                   8417:     my ($udom,$uname,$umode,$upass)=@_;
                   8418:     my $uhome=&homeserver($uname,$udom);
1.197     www      8419:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8420:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8421:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8422:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8423:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8424: 		     &escape($upass),$uhome);
1.620     albertel 8425:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8426:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8427:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8428:     &log($udom,,$uname,$uhome,
1.620     albertel 8429:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8430:                                      $env{'user.name'}.', '.$umode.
1.197     www      8431:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8432:     unless ($reply eq 'ok') {
1.197     www      8433:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8434: 	return 'error: '.$reply;
                   8435:     }   
1.170     harris41 8436:     return 'ok';
1.80      www      8437: }
                   8438: 
1.81      www      8439: # --------------------------------------------------------------- Modify a user
1.80      www      8440: 
1.81      www      8441: sub modifyuser {
1.206     matthew  8442:     my ($udom,    $uname, $uid,
                   8443:         $umode,   $upass, $first,
                   8444:         $middle,  $last,  $gene,
1.1058    raeburn  8445:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8446:     $udom= &LONCAPA::clean_domain($udom);
                   8447:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8448:     my $showcandelete = 'none';
                   8449:     if (ref($candelete) eq 'ARRAY') {
                   8450:         if (@{$candelete} > 0) {
                   8451:             $showcandelete = join(', ',@{$candelete});
                   8452:         }
                   8453:     }
1.81      www      8454:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8455:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8456: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8457:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8458:                                      ' desiredhome not specified'). 
1.620     albertel 8459:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8460:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8461:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8462:     my $newuser;
                   8463:     if ($uhome eq 'no_host') {
                   8464:         $newuser = 1;
                   8465:     }
1.80      www      8466: # ----------------------------------------------------------------- Create User
1.406     albertel 8467:     if (($uhome eq 'no_host') && 
                   8468: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8469:         my $unhome='';
1.844     albertel 8470:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8471:             $unhome = $desiredhome;
1.620     albertel 8472: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8473: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8474:         } else { # load balancing routine for determining $unhome
1.81      www      8475:             my $loadm=10000000;
1.841     albertel 8476: 	    my %servers = &get_servers($udom,'library');
                   8477: 	    foreach my $tryserver (keys(%servers)) {
                   8478: 		my $answer=reply('load',$tryserver);
                   8479: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8480: 		    $loadm=$answer;
                   8481: 		    $unhome=$tryserver;
                   8482: 		}
1.80      www      8483: 	    }
                   8484:         }
                   8485:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8486: 	    return 'error: unable to find a home server for '.$uname.
                   8487:                    ' in domain '.$udom;
1.80      www      8488:         }
                   8489:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8490:                          &escape($upass),$unhome);
                   8491: 	unless ($reply eq 'ok') {
                   8492:             return 'error: '.$reply;
                   8493:         }   
1.230     stredwic 8494:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8495:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8496: 	    return 'error: unable verify users home machine.';
1.80      www      8497:         }
1.209     matthew  8498:     }   # End of creation of new user
1.80      www      8499: # ---------------------------------------------------------------------- Add ID
                   8500:     if ($uid) {
                   8501:        $uid=~tr/A-Z/a-z/;
                   8502:        my %uidhash=&idrget($udom,$uname);
1.196     www      8503:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8504:          && (!$forceid)) {
1.80      www      8505: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8506: 	      return 'error: user id "'.$uid.'" does not match '.
                   8507:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8508:           }
                   8509:        } else {
                   8510: 	  &idput($udom,($uname => $uid));
                   8511:        }
                   8512:     }
                   8513: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8514:     my @tmp=&get('environment',
1.899     raeburn  8515: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8516:                     'permanentemail','inststatus'],
1.134     albertel 8517: 		   $udom,$uname);
1.1075    raeburn  8518:     my (%names,%oldnames);
1.313     matthew  8519:     if ($tmp[0] =~ m/^error:.*/) { 
                   8520:         %names=(); 
                   8521:     } else {
                   8522:         %names = @tmp;
1.1075    raeburn  8523:         %oldnames = %names;
1.313     matthew  8524:     }
1.388     www      8525: #
1.1058    raeburn  8526: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8527: # of users did not contain them), do not overwrite existing values
                   8528: # unless field is in $candelete array ref.  
                   8529: #
                   8530: 
                   8531:     my @fields = ('firstname','middlename','lastname','generation',
                   8532:                   'permanentemail','id');
                   8533:     my %newvalues;
                   8534:     if (ref($candelete) eq 'ARRAY') {
                   8535:         foreach my $field (@fields) {
                   8536:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8537:                 if ($field eq 'firstname') {
                   8538:                     $names{$field} = $first;
                   8539:                 } elsif ($field eq 'middlename') {
                   8540:                     $names{$field} = $middle;
                   8541:                 } elsif ($field eq 'lastname') {
                   8542:                     $names{$field} = $last;
                   8543:                 } elsif ($field eq 'generation') { 
                   8544:                     $names{$field} = $gene;
                   8545:                 } elsif ($field eq 'permanentemail') {
                   8546:                     $names{$field} = $email;
                   8547:                 } elsif ($field eq 'id') {
                   8548:                     $names{$field}  = $uid;
                   8549:                 }
                   8550:             }
                   8551:         }
                   8552:     }
1.388     www      8553:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8554:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8555:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8556:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8557:     if ($email) {
                   8558:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8559:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8560:     }
1.899     raeburn  8561:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8562:     if (defined($inststatus)) {
                   8563:         $names{'inststatus'} = '';
                   8564:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8565:         if (ref($usertypes) eq 'HASH') {
                   8566:             my @okstatuses; 
                   8567:             foreach my $item (split(/:/,$inststatus)) {
                   8568:                 if (defined($usertypes->{$item})) {
                   8569:                     push(@okstatuses,$item);  
                   8570:                 }
                   8571:             }
                   8572:             if (@okstatuses) {
                   8573:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8574:             }
                   8575:         }
                   8576:     }
1.1075    raeburn  8577:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8578:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8579:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8580:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8581:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8582:     } else {
                   8583:         $logmsg .= ' during self creation';
                   8584:     }
1.1075    raeburn  8585:     my $changed;
                   8586:     if ($newuser) {
                   8587:         $changed = 1;
                   8588:     } else {
                   8589:         foreach my $field (@fields) {
                   8590:             if ($names{$field} ne $oldnames{$field}) {
                   8591:                 $changed = 1;
                   8592:                 last;
                   8593:             }
                   8594:         }
                   8595:     }
                   8596:     unless ($changed) {
                   8597:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8598:         &logthis($logmsg);
                   8599:         return 'ok';
                   8600:     }
                   8601:     my $reply = &put('environment', \%names, $udom,$uname);
                   8602:     if ($reply ne 'ok') { 
                   8603:         return 'error: '.$reply;
                   8604:     }
1.1087    raeburn  8605:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8606:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8607:     }
1.1075    raeburn  8608:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8609:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8610:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8611:     &logthis($logmsg);
1.134     albertel 8612:     return 'ok';
1.80      www      8613: }
                   8614: 
1.81      www      8615: # -------------------------------------------------------------- Modify student
1.80      www      8616: 
1.81      www      8617: sub modifystudent {
                   8618:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8619:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8620:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8621:     if (!$cid) {
1.620     albertel 8622: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8623: 	    return 'not_in_class';
                   8624: 	}
1.80      www      8625:     }
                   8626: # --------------------------------------------------------------- Make the user
1.81      www      8627:     my $reply=&modifyuser
1.209     matthew  8628: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8629:          $desiredhome,$email,$inststatus);
1.80      www      8630:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8631:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8632:     # student's environment
1.297     matthew  8633:     $uid = undef if (!$forceid);
1.455     albertel 8634:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8635:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8636:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8637:     return $reply;
                   8638: }
                   8639: 
                   8640: sub modify_student_enrollment {
1.1216    raeburn  8641:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8642:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8643:     my ($cdom,$cnum,$chome);
                   8644:     if (!$cid) {
1.620     albertel 8645: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8646: 	    return 'not_in_class';
                   8647: 	}
1.620     albertel 8648: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8649: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8650:     } else {
                   8651: 	($cdom,$cnum)=split(/_/,$cid);
                   8652:     }
1.620     albertel 8653:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8654:     if (!$chome) {
1.457     raeburn  8655: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8656:     }
1.455     albertel 8657:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8658:     # Make sure the user exists
1.81      www      8659:     my $uhome=&homeserver($uname,$udom);
                   8660:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8661: 	return 'error: no such user';
                   8662:     }
1.297     matthew  8663:     # Get student data if we were not given enough information
                   8664:     if (!defined($first)  || $first  eq '' || 
                   8665:         !defined($last)   || $last   eq '' || 
                   8666:         !defined($uid)    || $uid    eq '' || 
                   8667:         !defined($middle) || $middle eq '' || 
                   8668:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8669:         # They did not supply us with enough data to enroll the student, so
                   8670:         # we need to pick up more information.
1.297     matthew  8671:         my %tmp = &get('environment',
1.294     matthew  8672:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8673:                        ,$udom,$uname);
                   8674: 
1.800     albertel 8675:         #foreach my $key (keys(%tmp)) {
                   8676:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8677:         #}
1.294     matthew  8678:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8679:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8680:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8681:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8682:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8683:     }
1.556     albertel 8684:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8685:     my $user = "$uname:$udom";
                   8686:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8687:     my $reply=cput('classlist',
1.1148    raeburn  8688: 		   {$user => 
1.1216    raeburn  8689: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8690: 		   $cdom,$cnum);
1.1148    raeburn  8691:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8692:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8693:     } else { 
1.81      www      8694: 	return 'error: '.$reply;
                   8695:     }
1.297     matthew  8696:     # Add student role to user
1.83      www      8697:     my $uurl='/'.$cid;
1.81      www      8698:     $uurl=~s/\_/\//g;
                   8699:     if ($usec) {
                   8700: 	$uurl.='/'.$usec;
                   8701:     }
1.1148    raeburn  8702:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8703:                              $selfenroll,$context);
                   8704:     if ($result ne 'ok') {
                   8705:         if ($old_entry{$user} ne '') {
                   8706:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8707:         } else {
                   8708:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8709:         }
                   8710:     }
                   8711:     return $result; 
1.21      www      8712: }
                   8713: 
1.556     albertel 8714: sub format_name {
                   8715:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8716:     my $name;
                   8717:     if ($first ne 'lastname') {
                   8718: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8719:     } else {
                   8720: 	if ($lastname=~/\S/) {
                   8721: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8722: 	    $name=~s/\s+,/,/;
                   8723: 	} else {
                   8724: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8725: 	}
                   8726:     }
                   8727:     $name=~s/^\s+//;
                   8728:     $name=~s/\s+$//;
                   8729:     $name=~s/\s+/ /g;
                   8730:     return $name;
                   8731: }
                   8732: 
1.84      www      8733: # ------------------------------------------------- Write to course preferences
                   8734: 
                   8735: sub writecoursepref {
                   8736:     my ($courseid,%prefs)=@_;
                   8737:     $courseid=~s/^\///;
                   8738:     $courseid=~s/\_/\//g;
                   8739:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8740:     my $chome=homeserver($cnum,$cdomain);
                   8741:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8742: 	return 'error: no such course';
                   8743:     }
                   8744:     my $cstring='';
1.800     albertel 8745:     foreach my $pref (keys(%prefs)) {
                   8746: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8747:     }
1.84      www      8748:     $cstring=~s/\&$//;
                   8749:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8750: }
                   8751: 
                   8752: # ---------------------------------------------------------- Make/modify course
                   8753: 
                   8754: sub createcourse {
1.741     raeburn  8755:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8756:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8757:     $url=&declutter($url);
                   8758:     my $cid='';
1.1028    raeburn  8759:     if ($context eq 'requestcourses') {
                   8760:         my $can_create = 0;
                   8761:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8762:         if ($udom eq $ownerdom) {
                   8763:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8764:                                   $context)) {
                   8765:                 $can_create = 1;
                   8766:             }
                   8767:         } else {
                   8768:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8769:                                            $category);
                   8770:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8771:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8772:                 if (@curr > 0) {
                   8773:                     my @options = qw(approval validate autolimit);
                   8774:                     my $optregex = join('|',@options);
                   8775:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8776:                         $can_create = 1;
                   8777:                     }
                   8778:                 }
                   8779:             }
                   8780:         }
                   8781:         if ($can_create) {
                   8782:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8783:                 unless (&allowed('ccc',$udom)) {
                   8784:                     return 'refused'; 
                   8785:                 }
1.1017    raeburn  8786:             }
                   8787:         } else {
                   8788:             return 'refused';
                   8789:         }
1.1028    raeburn  8790:     } elsif (!&allowed('ccc',$udom)) {
                   8791:         return 'refused';
1.84      www      8792:     }
1.1011    raeburn  8793: # --------------------------------------------------------------- Get Unique ID
                   8794:     my $uname;
                   8795:     if ($cnum =~ /^$match_courseid$/) {
                   8796:         my $chome=&homeserver($cnum,$udom,'true');
                   8797:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8798:             $uname = $cnum;
                   8799:         } else {
1.1038    raeburn  8800:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8801:         }
                   8802:     } else {
1.1038    raeburn  8803:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8804:     }
                   8805:     return $uname if ($uname =~ /^error/);
                   8806: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8807:     if (!defined($course_server)) {
                   8808:         if (defined(&domain($udom,'primary'))) {
                   8809:             $course_server = &domain($udom,'primary');
                   8810:         } else {
                   8811:             $course_server = $env{'user.home'}; 
                   8812:         }
                   8813:     }
                   8814:     my %host_servers =
                   8815:         &Apache::lonnet::get_servers($udom,'library');
                   8816:     unless ($host_servers{$course_server}) {
                   8817:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8818:     }
1.84      www      8819: # ------------------------------------------------------------- Make the course
                   8820:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8821:                       $course_server);
1.84      www      8822:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8823:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8824:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8825: 	return 'error: no such course';
                   8826:     }
1.271     www      8827: # ----------------------------------------------------------------- Course made
1.516     raeburn  8828: # log existence
1.1029    raeburn  8829:     my $now = time;
1.918     raeburn  8830:     my $newcourse = {
                   8831:                     $udom.'_'.$uname => {
1.921     raeburn  8832:                                      description => $description,
                   8833:                                      inst_code   => $inst_code,
                   8834:                                      owner       => $course_owner,
                   8835:                                      type        => $crstype,
1.1029    raeburn  8836:                                      creator     => $env{'user.name'}.':'.
                   8837:                                                     $env{'user.domain'},
                   8838:                                      created     => $now,
                   8839:                                      context     => $context,
1.918     raeburn  8840:                                                 },
                   8841:                     };
1.921     raeburn  8842:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8843: # set toplevel url
1.271     www      8844:     my $topurl=$url;
                   8845:     unless ($nonstandard) {
                   8846: # ------------------------------------------ For standard courses, make top url
                   8847:         my $mapurl=&clutter($url);
1.278     www      8848:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8849:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8850: <map>
                   8851: <resource id="1" type="start"></resource>
                   8852: <resource id="2" src="$mapurl"></resource>
                   8853: <resource id="3" type="finish"></resource>
                   8854: <link index="1" from="1" to="2"></link>
                   8855: <link index="2" from="2" to="3"></link>
                   8856: </map>
                   8857: ENDINITMAP
                   8858:         $topurl=&declutter(
1.638     albertel 8859:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8860:                           );
                   8861:     }
                   8862: # ----------------------------------------------------------- Write preferences
1.84      www      8863:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8864:                      ('description'              => $description,
                   8865:                       'url'                      => $topurl,
                   8866:                       'internal.creator'         => $env{'user.name'}.':'.
                   8867:                                                     $env{'user.domain'},
                   8868:                       'internal.created'         => $now,
                   8869:                       'internal.creationcontext' => $context)
                   8870:                     );
1.84      www      8871:     return '/'.$udom.'/'.$uname;
                   8872: }
                   8873: 
1.1011    raeburn  8874: # ------------------------------------------------------------------- Create ID
                   8875: sub generate_coursenum {
1.1038    raeburn  8876:     my ($udom,$crstype) = @_;
1.1011    raeburn  8877:     my $domdesc = &domain($udom);
                   8878:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8879:     my $first;
                   8880:     if ($crstype eq 'Community') {
                   8881:         $first = '0';
                   8882:     } else {
                   8883:         $first = int(1+rand(9)); 
                   8884:     } 
                   8885:     my $uname=$first.
1.1011    raeburn  8886:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8887:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8888:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8889: # ----------------------------------------------- Make sure that does not exist
                   8890:     my $uhome=&homeserver($uname,$udom,'true');
                   8891:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8892:         if ($crstype eq 'Community') {
                   8893:             $first = '0';
                   8894:         } else {
                   8895:             $first = int(1+rand(9));
                   8896:         }
                   8897:         $uname=$first.
1.1011    raeburn  8898:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8899:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8900:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8901:         $uhome=&homeserver($uname,$udom,'true');
                   8902:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8903:             return 'error: unable to generate unique course-ID';
                   8904:         }
                   8905:     }
                   8906:     return $uname;
                   8907: }
                   8908: 
1.813     albertel 8909: sub is_course {
1.1167    droeschl 8910:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8911:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8912: 
                   8913:     return unless $cdom and $cnum;
                   8914: 
                   8915:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8916:         '.');
                   8917: 
1.1219    raeburn  8918:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8919:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8920: }
                   8921: 
1.1015    raeburn  8922: sub store_userdata {
                   8923:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8924:     my $result;
1.1016    raeburn  8925:     if ($datakey ne '') {
1.1013    raeburn  8926:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8927:             if ($udom eq '' || $uname eq '') {
                   8928:                 $udom = $env{'user.domain'};
                   8929:                 $uname = $env{'user.name'};
                   8930:             }
                   8931:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8932:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8933:                 $result = 'error: no_host';
                   8934:             } else {
                   8935:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8936:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8937: 
                   8938:                 my $namevalue='';
                   8939:                 foreach my $key (keys(%{$storehash})) {
                   8940:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8941:                 }
                   8942:                 $namevalue=~s/\&$//;
1.1224    raeburn  8943:                 unless ($namespace eq 'courserequests') {
                   8944:                     $datakey = &escape($datakey);
                   8945:                 }
1.1105    raeburn  8946:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8947:                                   $namevalue,$uhome);
1.1013    raeburn  8948:             }
                   8949:         } else {
                   8950:             $result = 'error: data to store was not a hash reference'; 
                   8951:         }
                   8952:     } else {
                   8953:         $result= 'error: invalid requestkey'; 
                   8954:     }
                   8955:     return $result;
                   8956: }
                   8957: 
1.21      www      8958: # ---------------------------------------------------------- Assign Custom Role
                   8959: 
                   8960: sub assigncustomrole {
1.957     raeburn  8961:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8962:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8963:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8964: }
                   8965: 
                   8966: # ----------------------------------------------------------------- Revoke Role
                   8967: 
                   8968: sub revokerole {
1.957     raeburn  8969:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8970:     my $now=time;
1.965     raeburn  8971:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8972: }
                   8973: 
                   8974: # ---------------------------------------------------------- Revoke Custom Role
                   8975: 
                   8976: sub revokecustomrole {
1.957     raeburn  8977:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8978:     my $now=time;
1.357     www      8979:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8980:            $deleteflag,$selfenroll,$context);
1.17      www      8981: }
                   8982: 
1.533     banghart 8983: # ------------------------------------------------------------ Disk usage
1.535     albertel 8984: sub diskusage {
1.955     raeburn  8985:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8986:     $directorypath =~ s/\/$//;
                   8987:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8988:                        .&escape($getpropath).':'.&escape($uname).':'
                   8989:                        .&escape($udom),homeserver($uname,$udom));
                   8990:     if ($listing eq 'unknown_cmd') {
                   8991:         if ($getpropath) {
                   8992:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8993:         }
                   8994:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8995:     }
1.514     albertel 8996:     return $listing;
1.512     banghart 8997: }
                   8998: 
1.566     banghart 8999: sub is_locked {
1.1096    raeburn  9000:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9001:     my @check;
                   9002:     my $is_locked;
1.1093    raeburn  9003:     push (@check,$file_name);
1.613     albertel 9004:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9005: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9006:     my ($tmp)=keys(%locked);
                   9007:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9008:     
1.566     banghart 9009:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9010:         $is_locked = 'false';
                   9011:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9012:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9013:                $is_locked = 'true';
1.1096    raeburn  9014:                if (ref($which) eq 'ARRAY') {
                   9015:                    push(@{$which},$entry);
                   9016:                } else {
                   9017:                    last;
                   9018:                }
1.745     raeburn  9019:            }
                   9020:        }
1.566     banghart 9021:     } else {
                   9022:         $is_locked = 'false';
                   9023:     }
1.1093    raeburn  9024:     return $is_locked;
1.566     banghart 9025: }
                   9026: 
1.759     albertel 9027: sub declutter_portfile {
                   9028:     my ($file) = @_;
1.833     albertel 9029:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9030:     return $file;
                   9031: }
                   9032: 
1.559     banghart 9033: # ------------------------------------------------------------- Mark as Read Only
                   9034: 
                   9035: sub mark_as_readonly {
                   9036:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9037:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9038:     my ($tmp)=keys(%current_permissions);
                   9039:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9040:     foreach my $file (@{$files}) {
1.759     albertel 9041: 	$file = &declutter_portfile($file);
1.561     banghart 9042:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9043:     }
1.613     albertel 9044:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9045:     return;
                   9046: }
                   9047: 
1.572     banghart 9048: # ------------------------------------------------------------Save Selected Files
                   9049: 
                   9050: sub save_selected_files {
                   9051:     my ($user, $path, @files) = @_;
                   9052:     my $filename = $user."savedfiles";
1.573     banghart 9053:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9054:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9055:     foreach my $file (@files) {
1.620     albertel 9056:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9057:     }
                   9058:     foreach my $file (@other_files) {
1.574     banghart 9059:         print (OUT $file."\n");
1.572     banghart 9060:     }
1.574     banghart 9061:     close (OUT);
1.572     banghart 9062:     return 'ok';
                   9063: }
                   9064: 
1.574     banghart 9065: sub clear_selected_files {
                   9066:     my ($user) = @_;
                   9067:     my $filename = $user."savedfiles";
1.1117    foxr     9068:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9069:     print (OUT undef);
                   9070:     close (OUT);
                   9071:     return ("ok");    
                   9072: }
                   9073: 
1.572     banghart 9074: sub files_in_path {
                   9075:     my ($user, $path) = @_;
                   9076:     my $filename = $user."savedfiles";
                   9077:     my %return_files;
1.1117    foxr     9078:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9079:     while (my $line_in = <IN>) {
1.574     banghart 9080:         chomp ($line_in);
                   9081:         my @paths_and_file = split (m!/!, $line_in);
                   9082:         my $file_part = pop (@paths_and_file);
                   9083:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9084:         $path_part.='/';
                   9085:         my $path_and_file = $path_part.$file_part;
                   9086:         if ($path_part eq $path) {
                   9087:             $return_files{$file_part}= 'selected';
                   9088:         }
                   9089:     }
1.574     banghart 9090:     close (IN);
                   9091:     return (\%return_files);
1.572     banghart 9092: }
                   9093: 
                   9094: # called in portfolio select mode, to show files selected NOT in current directory
                   9095: sub files_not_in_path {
                   9096:     my ($user, $path) = @_;
                   9097:     my $filename = $user."savedfiles";
                   9098:     my @return_files;
                   9099:     my $path_part;
1.1117    foxr     9100:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9101:     while (my $line = <IN>) {
1.572     banghart 9102:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9103:         my @paths_and_file = split(m|/|, $line);
                   9104:         my $file_part = pop(@paths_and_file);
                   9105:         chomp($file_part);
                   9106:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9107:         $path_part .= '/';
                   9108:         my $path_and_file = $path_part.$file_part;
                   9109:         if ($path_part ne $path) {
1.800     albertel 9110:             push(@return_files, ($path_and_file));
1.572     banghart 9111:         }
                   9112:     }
1.800     albertel 9113:     close(OUT);
1.574     banghart 9114:     return (@return_files);
1.572     banghart 9115: }
                   9116: 
1.745     raeburn  9117: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9118: 
1.745     raeburn  9119: sub get_portfile_permissions {
                   9120:     my ($domain,$user) = @_;
1.613     albertel 9121:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9122:     my ($tmp)=keys(%current_permissions);
                   9123:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9124:     return \%current_permissions;
                   9125: }
                   9126: 
                   9127: #---------------------------------------------Get portfolio file access controls
                   9128: 
1.749     raeburn  9129: sub get_access_controls {
1.745     raeburn  9130:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9131:     my %access;
                   9132:     my $real_file = $file;
                   9133:     $file =~ s/\.meta$//;
1.745     raeburn  9134:     if (defined($file)) {
1.749     raeburn  9135:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9136:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9137:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9138:             }
                   9139:         }
1.745     raeburn  9140:     } else {
1.749     raeburn  9141:         foreach my $key (keys(%{$current_permissions})) {
                   9142:             if ($key =~ /\0accesscontrol$/) {
                   9143:                 if (defined($group)) {
                   9144:                     if ($key !~ m-^\Q$group\E/-) {
                   9145:                         next;
                   9146:                     }
                   9147:                 }
                   9148:                 my ($fullpath) = split(/\0/,$key);
                   9149:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9150:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9151:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9152:                     }
                   9153:                 }
                   9154:             }
                   9155:         }
                   9156:     }
                   9157:     return %access;
                   9158: }
                   9159: 
                   9160: sub modify_access_controls {
                   9161:     my ($file_name,$changes,$domain,$user)=@_;
                   9162:     my ($outcome,$deloutcome);
                   9163:     my %store_permissions;
                   9164:     my %new_values;
                   9165:     my %new_control;
                   9166:     my %translation;
                   9167:     my @deletions = ();
                   9168:     my $now = time;
                   9169:     if (exists($$changes{'activate'})) {
                   9170:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9171:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9172:             my $numnew = scalar(@newitems);
                   9173:             for (my $i=0; $i<$numnew; $i++) {
                   9174:                 my $newkey = $newitems[$i];
                   9175:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9176:                 if ($newkey =~ /^\d+:/) { 
                   9177:                     $newkey =~ s/^(\d+)/$newid/;
                   9178:                     $translation{$1} = $newid;
                   9179:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9180:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9181:                     $translation{$1} = $newid;
                   9182:                 }
1.749     raeburn  9183:                 $new_values{$file_name."\0".$newkey} = 
                   9184:                                           $$changes{'activate'}{$newitems[$i]};
                   9185:                 $new_control{$newkey} = $now;
                   9186:             }
                   9187:         }
                   9188:     }
                   9189:     my %todelete;
                   9190:     my %changed_items;
                   9191:     foreach my $action ('delete','update') {
                   9192:         if (exists($$changes{$action})) {
                   9193:             if (ref($$changes{$action}) eq 'HASH') {
                   9194:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9195:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9196:                     if ($action eq 'delete') { 
                   9197:                         $todelete{$itemnum} = 1;
                   9198:                     } else {
                   9199:                         $changed_items{$itemnum} = $key;
                   9200:                     }
                   9201:                 }
1.745     raeburn  9202:             }
                   9203:         }
1.749     raeburn  9204:     }
                   9205:     # get lock on access controls for file.
                   9206:     my $lockhash = {
                   9207:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9208:                                                        ':'.$env{'user.domain'},
                   9209:                    }; 
                   9210:     my $tries = 0;
                   9211:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9212:    
                   9213:     while (($gotlock ne 'ok') && $tries <3) {
                   9214:         $tries ++;
                   9215:         sleep 1;
                   9216:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9217:     }
                   9218:     if ($gotlock eq 'ok') {
                   9219:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9220:         my ($tmp)=keys(%curr_permissions);
                   9221:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9222:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9223:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9224:             if (ref($curr_controls) eq 'HASH') {
                   9225:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9226:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9227:                     if (defined($todelete{$itemnum})) {
                   9228:                         push(@deletions,$file_name."\0".$control_item);
                   9229:                     } else {
                   9230:                         if (defined($changed_items{$itemnum})) {
                   9231:                             $new_control{$changed_items{$itemnum}} = $now;
                   9232:                             push(@deletions,$file_name."\0".$control_item);
                   9233:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9234:                         } else {
                   9235:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9236:                         }
                   9237:                     }
1.745     raeburn  9238:                 }
                   9239:             }
                   9240:         }
1.970     raeburn  9241:         my ($group);
                   9242:         if (&is_course($domain,$user)) {
                   9243:             ($group,my $file) = split(/\//,$file_name,2);
                   9244:         }
1.749     raeburn  9245:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9246:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9247:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9248:         #  remove lock
                   9249:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9250:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9251:         my $sqlresult =
1.970     raeburn  9252:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9253:                                     $group);
1.749     raeburn  9254:     } else {
                   9255:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9256:     }
1.749     raeburn  9257:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9258: }
                   9259: 
1.827     raeburn  9260: sub make_public_indefinitely {
                   9261:     my ($requrl) = @_;
                   9262:     my $now = time;
                   9263:     my $action = 'activate';
                   9264:     my $aclnum = 0;
                   9265:     if (&is_portfolio_url($requrl)) {
                   9266:         my (undef,$udom,$unum,$file_name,$group) =
                   9267:             &parse_portfolio_url($requrl);
                   9268:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9269:         my %access_controls = &get_access_controls($current_perms,
                   9270:                                                    $group,$file_name);
                   9271:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9272:             my ($num,$scope,$end,$start) = 
                   9273:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9274:             if ($scope eq 'public') {
                   9275:                 if ($start <= $now && $end == 0) {
                   9276:                     $action = 'none';
                   9277:                 } else {
                   9278:                     $action = 'update';
                   9279:                     $aclnum = $num;
                   9280:                 }
                   9281:                 last;
                   9282:             }
                   9283:         }
                   9284:         if ($action eq 'none') {
                   9285:              return 'ok';
                   9286:         } else {
                   9287:             my %changes;
                   9288:             my $newend = 0;
                   9289:             my $newstart = $now;
                   9290:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9291:             $changes{$action}{$newkey} = {
                   9292:                 type => 'public',
                   9293:                 time => {
                   9294:                     start => $newstart,
                   9295:                     end   => $newend,
                   9296:                 },
                   9297:             };
                   9298:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9299:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9300:             return $outcome;
                   9301:         }
                   9302:     } else {
                   9303:         return 'invalid';
                   9304:     }
                   9305: }
                   9306: 
1.745     raeburn  9307: #------------------------------------------------------Get Marked as Read Only
                   9308: 
                   9309: sub get_marked_as_readonly {
                   9310:     my ($domain,$user,$what,$group) = @_;
                   9311:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9312:     my @readonly_files;
1.629     banghart 9313:     my $cmp1=$what;
                   9314:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9315:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9316:         if (defined($group)) {
                   9317:             if ($file_name !~ m-^\Q$group\E/-) {
                   9318:                 next;
                   9319:             }
                   9320:         }
1.561     banghart 9321:         if (ref($value) eq "ARRAY"){
                   9322:             foreach my $stored_what (@{$value}) {
1.629     banghart 9323:                 my $cmp2=$stored_what;
1.759     albertel 9324:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9325:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9326:                 }
1.629     banghart 9327:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9328:                     push(@readonly_files, $file_name);
1.745     raeburn  9329:                     last;
1.563     banghart 9330:                 } elsif (!defined($what)) {
                   9331:                     push(@readonly_files, $file_name);
1.745     raeburn  9332:                     last;
1.561     banghart 9333:                 }
                   9334:             }
1.745     raeburn  9335:         }
1.561     banghart 9336:     }
                   9337:     return @readonly_files;
                   9338: }
1.577     banghart 9339: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9340: 
1.577     banghart 9341: sub get_marked_as_readonly_hash {
1.745     raeburn  9342:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9343:     my %readonly_files;
1.745     raeburn  9344:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9345:         if (defined($group)) {
                   9346:             if ($file_name !~ m-^\Q$group\E/-) {
                   9347:                 next;
                   9348:             }
                   9349:         }
1.577     banghart 9350:         if (ref($value) eq "ARRAY"){
                   9351:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9352:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9353:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9354:                         if ($lock_descriptor eq 'graded') {
                   9355:                             $readonly_files{$file_name} = 'graded';
                   9356:                         } elsif ($lock_descriptor eq 'handback') {
                   9357:                             $readonly_files{$file_name} = 'handback';
                   9358:                         } else {
                   9359:                             if (!exists($readonly_files{$file_name})) {
                   9360:                                 $readonly_files{$file_name} = 'locked';
                   9361:                             }
                   9362:                         }
1.745     raeburn  9363:                     }
1.750     banghart 9364:                 } 
1.577     banghart 9365:             }
                   9366:         } 
                   9367:     }
                   9368:     return %readonly_files;
                   9369: }
1.559     banghart 9370: # ------------------------------------------------------------ Unmark as Read Only
                   9371: 
                   9372: sub unmark_as_readonly {
1.629     banghart 9373:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9374:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9375:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9376:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9377:     my $symb_crs = $what;
                   9378:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9379:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9380:     my ($tmp)=keys(%current_permissions);
                   9381:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9382:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9383:     foreach my $file (@readonly_files) {
1.759     albertel 9384: 	my $clean_file = &declutter_portfile($file);
                   9385: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9386: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9387:         my @new_locks;
                   9388:         my @del_keys;
                   9389:         if (ref($current_locks) eq "ARRAY"){
                   9390:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9391:                 my $compare=$locker;
1.749     raeburn  9392:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9393:                     $compare=join('',@{$locker});
1.746     raeburn  9394:                     if ($compare ne $symb_crs) {
                   9395:                         push(@new_locks, $locker);
                   9396:                     }
1.563     banghart 9397:                 }
                   9398:             }
1.650     albertel 9399:             if (scalar(@new_locks) > 0) {
1.563     banghart 9400:                 $current_permissions{$file} = \@new_locks;
                   9401:             } else {
                   9402:                 push(@del_keys, $file);
1.613     albertel 9403:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9404:                 delete($current_permissions{$file});
1.563     banghart 9405:             }
                   9406:         }
1.561     banghart 9407:     }
1.613     albertel 9408:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9409:     return;
                   9410: }
1.512     banghart 9411: 
1.17      www      9412: # ------------------------------------------------------------ Directory lister
                   9413: 
                   9414: sub dirlist {
1.955     raeburn  9415:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9416:     $uri=~s/^\///;
                   9417:     $uri=~s/\/$//;
1.253     stredwic 9418:     my ($udom, $uname);
1.955     raeburn  9419:     if ($getuserdir) {
1.253     stredwic 9420:         $udom = $userdomain;
                   9421:         $uname = $username;
1.955     raeburn  9422:     } else {
                   9423:         (undef,$udom,$uname)=split(/\//,$uri);
                   9424:         if(defined($userdomain)) {
                   9425:             $udom = $userdomain;
                   9426:         }
                   9427:         if(defined($username)) {
                   9428:             $uname = $username;
                   9429:         }
1.253     stredwic 9430:     }
1.955     raeburn  9431:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9432: 
1.955     raeburn  9433:     $dirRoot = $perlvar{'lonDocRoot'};
                   9434:     if (defined($getpropath)) {
                   9435:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9436:         $dirRoot =~ s/\/$//;
1.955     raeburn  9437:     } elsif (defined($getuserdir)) {
                   9438:         my $subdir=$uname.'__';
                   9439:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9440:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9441:                    ."/$udom/$subdir/$uname";
                   9442:     } elsif (defined($alternateRoot)) {
                   9443:         $dirRoot = $alternateRoot;
1.751     banghart 9444:     }
1.253     stredwic 9445: 
                   9446:     if($udom) {
                   9447:         if($uname) {
1.1135    raeburn  9448:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9449:             if ($uhome eq 'no_host') {
                   9450:                 return ([],'no_host');
                   9451:             }
1.955     raeburn  9452:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9453:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9454:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9455:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9456:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9457:             } else {
                   9458:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9459:             }
1.605     matthew  9460:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9461:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9462:                 @listing_results = split(/:/,$listing);
                   9463:             } else {
                   9464:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9465:             }
1.1135    raeburn  9466:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9467:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9468:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9469:                 return ([],$listing);
                   9470:             } else {
                   9471:                 return (\@listing_results);
1.1135    raeburn  9472:             }
1.955     raeburn  9473:         } elsif(!$alternateRoot) {
1.1136    raeburn  9474:             my (%allusers,%listerror);
1.841     albertel 9475: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9476:  	    foreach my $tryserver (keys(%servers)) {
                   9477:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9478:                                   &escape($udom),$tryserver);
                   9479:                 if ($listing eq 'unknown_cmd') {
                   9480: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9481: 				      $udom, $tryserver);
                   9482:                 } else {
                   9483:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9484:                 }
1.841     albertel 9485: 		if ($listing eq 'unknown_cmd') {
                   9486: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9487: 				      $udom, $tryserver);
                   9488: 		    @listing_results = split(/:/,$listing);
                   9489: 		} else {
                   9490: 		    @listing_results =
                   9491: 			map { &unescape($_); } split(/:/,$listing);
                   9492: 		}
1.1136    raeburn  9493:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9494:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9495:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9496:                     $listerror{$tryserver} = $listing;
                   9497:                 } else {
1.841     albertel 9498: 		    foreach my $line (@listing_results) {
                   9499: 			my ($entry) = split(/&/,$line,2);
                   9500: 			$allusers{$entry} = 1;
                   9501: 		    }
                   9502: 		}
1.253     stredwic 9503:             }
1.1136    raeburn  9504:             my @alluserslist=();
1.800     albertel 9505:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9506:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9507:             }
1.1136    raeburn  9508:             return (\@alluserslist);
1.253     stredwic 9509:         } else {
1.1136    raeburn  9510:             return ([],'missing username');
1.253     stredwic 9511:         }
1.955     raeburn  9512:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9513:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9514:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9515:         return (\@all_domains);
1.955     raeburn  9516:     } else {
1.1136    raeburn  9517:         return ([],'missing domain');
1.275     stredwic 9518:     }
                   9519: }
                   9520: 
                   9521: # --------------------------------------------- GetFileTimestamp
                   9522: # This function utilizes dirlist and returns the date stamp for
                   9523: # when it was last modified.  It will also return an error of -1
                   9524: # if an error occurs
                   9525: 
                   9526: sub GetFileTimestamp {
1.955     raeburn  9527:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9528:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9529:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9530:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9531:                                     undef,$getuserdir);
                   9532:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9533:         return -1;
                   9534:     }
                   9535:     if (ref($fileref) eq 'ARRAY') {
                   9536:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9537:         # @stats contains first the filename, then the stat output
                   9538:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9539:     } else {
                   9540:         return -1;
1.253     stredwic 9541:     }
1.26      www      9542: }
                   9543: 
1.712     albertel 9544: sub stat_file {
                   9545:     my ($uri) = @_;
1.787     albertel 9546:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9547: 
1.955     raeburn  9548:     my ($udom,$uname,$file);
1.712     albertel 9549:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9550: 	($udom,$uname,$file) =
1.811     albertel 9551: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9552: 	$file = 'userfiles/'.$file;
                   9553:     }
                   9554:     if ($uri =~ m-^/res/-) {
                   9555: 	($udom,$uname) = 
1.807     albertel 9556: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9557: 	$file = $uri;
                   9558:     }
                   9559: 
                   9560:     if (!$udom || !$uname || !$file) {
                   9561: 	# unable to handle the uri
                   9562: 	return ();
                   9563:     }
1.956     raeburn  9564:     my $getpropath;
                   9565:     if ($file =~ /^userfiles\//) {
                   9566:         $getpropath = 1;
                   9567:     }
1.1136    raeburn  9568:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9569:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9570:         return ();
                   9571:     } else {
                   9572:         if (ref($listref) eq 'ARRAY') {
                   9573:             my @stats = split('&',$listref->[0]);
                   9574: 	    shift(@stats); #filename is first
                   9575: 	    return @stats;
                   9576:         }
1.712     albertel 9577:     }
                   9578:     return ();
                   9579: }
                   9580: 
1.26      www      9581: # -------------------------------------------------------- Value of a Condition
                   9582: 
1.713     albertel 9583: # gets the value of a specific preevaluated condition
                   9584: #    stored in the string  $env{user.state.<cid>}
                   9585: # or looks up a condition reference in the bighash and if if hasn't
                   9586: # already been evaluated recurses into docondval to get the value of
                   9587: # the condition, then memoizing it to 
                   9588: #   $env{user.state.<cid>.<condition>}
1.40      www      9589: sub directcondval {
                   9590:     my $number=shift;
1.620     albertel 9591:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9592: 	&Apache::lonuserstate::evalstate();
                   9593:     }
1.713     albertel 9594:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9595: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9596:     } elsif ($number =~ /^_/) {
                   9597: 	my $sub_condition;
                   9598: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9599: 		&GDBM_READER(),0640)) {
                   9600: 	    $sub_condition=$bighash{'conditions'.$number};
                   9601: 	    untie(%bighash);
                   9602: 	}
                   9603: 	my $value = &docondval($sub_condition);
1.949     raeburn  9604: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9605: 	return $value;
                   9606:     }
1.620     albertel 9607:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9608:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9609:     } else {
                   9610:        return 2;
                   9611:     }
                   9612: }
                   9613: 
1.713     albertel 9614: # get the collection of conditions for this resource
1.26      www      9615: sub condval {
                   9616:     my $condidx=shift;
1.54      www      9617:     my $allpathcond='';
1.713     albertel 9618:     foreach my $cond (split(/\|/,$condidx)) {
                   9619: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9620: 	    $allpathcond.=
                   9621: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9622: 	}
1.191     harris41 9623:     }
1.54      www      9624:     $allpathcond=~s/\|$//;
1.713     albertel 9625:     return &docondval($allpathcond);
                   9626: }
                   9627: 
                   9628: #evaluates an expression of conditions
                   9629: sub docondval {
                   9630:     my ($allpathcond) = @_;
                   9631:     my $result=0;
                   9632:     if ($env{'request.course.id'}
                   9633: 	&& defined($allpathcond)) {
                   9634: 	my $operand='|';
                   9635: 	my @stack;
                   9636: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9637: 	    if ($chunk eq '(') {
                   9638: 		push @stack,($operand,$result);
                   9639: 	    } elsif ($chunk eq ')') {
                   9640: 		my $before=pop @stack;
                   9641: 		if (pop @stack eq '&') {
                   9642: 		    $result=$result>$before?$before:$result;
                   9643: 		} else {
                   9644: 		    $result=$result>$before?$result:$before;
                   9645: 		}
                   9646: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9647: 		$operand=$chunk;
                   9648: 	    } else {
                   9649: 		my $new=directcondval($chunk);
                   9650: 		if ($operand eq '&') {
                   9651: 		    $result=$result>$new?$new:$result;
                   9652: 		} else {
                   9653: 		    $result=$result>$new?$result:$new;
                   9654: 		}
                   9655: 	    }
                   9656: 	}
1.26      www      9657:     }
                   9658:     return $result;
1.421     albertel 9659: }
                   9660: 
                   9661: # ---------------------------------------------------- Devalidate courseresdata
                   9662: 
                   9663: sub devalidatecourseresdata {
                   9664:     my ($coursenum,$coursedomain)=@_;
                   9665:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9666:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9667: }
                   9668: 
1.763     www      9669: 
1.200     www      9670: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9671: #
                   9672: #  Parameters:
                   9673: #      $coursenum    - Number of the course.
                   9674: #      $coursedomain - Domain at which the course was created.
                   9675: #  Returns:
                   9676: #     A hash of the course parameters along (I think) with timestamps
                   9677: #     and version info.
1.877     foxr     9678: 
1.624     albertel 9679: sub get_courseresdata {
                   9680:     my ($coursenum,$coursedomain)=@_;
1.200     www      9681:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9682:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9683:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9684:     my %dumpreply;
1.417     albertel 9685:     unless (defined($cached)) {
1.624     albertel 9686: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9687: 	$result=\%dumpreply;
1.251     albertel 9688: 	my ($tmp) = keys(%dumpreply);
                   9689: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9690: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9691: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9692: 	    return $tmp;
1.416     albertel 9693: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9694: 	    $result=undef;
1.599     albertel 9695: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9696: 	}
                   9697:     }
1.624     albertel 9698:     return $result;
                   9699: }
                   9700: 
1.633     albertel 9701: sub devalidateuserresdata {
                   9702:     my ($uname,$udom)=@_;
                   9703:     my $hashid="$udom:$uname";
                   9704:     &devalidate_cache_new('userres',$hashid);
                   9705: }
                   9706: 
1.624     albertel 9707: sub get_userresdata {
                   9708:     my ($uname,$udom)=@_;
                   9709:     #most student don\'t have any data set, check if there is some data
                   9710:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9711: 
                   9712:     my $hashid="$udom:$uname";
                   9713:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9714:     if (!defined($cached)) {
                   9715: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9716: 	$result=\%resourcedata;
                   9717: 	&do_cache_new('userres',$hashid,$result,600);
                   9718:     }
                   9719:     my ($tmp)=keys(%$result);
                   9720:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9721: 	return $result;
                   9722:     }
                   9723:     #error 2 occurs when the .db doesn't exist
                   9724:     if ($tmp!~/error: 2 /) {
1.672     albertel 9725: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9726: 		 " Trying to get resource data for ".
                   9727: 		 $uname." at ".$udom.": ".
                   9728: 		 $tmp."</font>");
                   9729:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9730: 	#&EXT_cache_set($udom,$uname);
                   9731: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9732: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9733:     }
                   9734:     return $tmp;
                   9735: }
1.879     foxr     9736: #----------------------------------------------- resdata - return resource data
                   9737: #  Purpose:
                   9738: #    Return resource data for either users or for a course.
                   9739: #  Parameters:
                   9740: #     $name      - Course/user name.
                   9741: #     $domain    - Name of the domain the user/course is registered on.
                   9742: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9743: #     @which     - Array of names of resources desired.
                   9744: #  Returns:
                   9745: #     The value of the first reasource in @which that is found in the
                   9746: #     resource hash.
                   9747: #  Exceptional Conditions:
                   9748: #     If the $type passed in is not valid (not the string 'course' or 
                   9749: #     'user', an undefined  reference is returned.
                   9750: #     If none of the resources are found, an undef is returned
1.624     albertel 9751: sub resdata {
                   9752:     my ($name,$domain,$type,@which)=@_;
                   9753:     my $result;
                   9754:     if ($type eq 'course') {
                   9755: 	$result=&get_courseresdata($name,$domain);
                   9756:     } elsif ($type eq 'user') {
                   9757: 	$result=&get_userresdata($name,$domain);
                   9758:     }
                   9759:     if (!ref($result)) { return $result; }    
1.251     albertel 9760:     foreach my $item (@which) {
1.927     albertel 9761: 	if (defined($result->{$item->[0]})) {
                   9762: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9763: 	}
1.250     albertel 9764:     }
1.291     albertel 9765:     return undef;
1.200     www      9766: }
                   9767: 
1.1236    raeburn  9768: sub get_numsuppfiles {
                   9769:     my ($cnum,$cdom,$ignorecache)=@_;
                   9770:     my $hashid=$cnum.':'.$cdom;
                   9771:     my ($suppcount,$cached);
                   9772:     unless ($ignorecache) {
                   9773:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9774:     }
                   9775:     unless (defined($cached)) {
                   9776:         my $chome=&homeserver($cnum,$cdom);
                   9777:         unless ($chome eq 'no_host') {
                   9778:             ($suppcount,my $errors) = (0,0);
                   9779:             my $suppmap = 'supplemental.sequence';
                   9780:             ($suppcount,$errors) = 
                   9781:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9782:         }
                   9783:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9784:     }
                   9785:     return $suppcount;
                   9786: }
                   9787: 
1.379     matthew  9788: #
                   9789: # EXT resource caching routines
                   9790: #
                   9791: 
                   9792: sub clear_EXT_cache_status {
1.383     albertel 9793:     &delenv('cache.EXT.');
1.379     matthew  9794: }
                   9795: 
                   9796: sub EXT_cache_status {
                   9797:     my ($target_domain,$target_user) = @_;
1.383     albertel 9798:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9799:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9800:         # We know already the user has no data
                   9801:         return 1;
                   9802:     } else {
                   9803:         return 0;
                   9804:     }
                   9805: }
                   9806: 
                   9807: sub EXT_cache_set {
                   9808:     my ($target_domain,$target_user) = @_;
1.383     albertel 9809:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9810:     #&appenv({$cachename => time});
1.379     matthew  9811: }
                   9812: 
1.28      www      9813: # --------------------------------------------------------- Value of a Variable
1.58      www      9814: sub EXT {
1.715     albertel 9815: 
1.1228    raeburn  9816:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9817:     unless ($varname) { return ''; }
1.218     albertel 9818:     #get real user name/domain, courseid and symb
                   9819:     my $courseid;
1.359     albertel 9820:     my $publicuser;
1.427     www      9821:     if ($symbparm) {
                   9822: 	$symbparm=&get_symb_from_alias($symbparm);
                   9823:     }
1.218     albertel 9824:     if (!($uname && $udom)) {
1.790     albertel 9825:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9826:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9827:     } else {
1.620     albertel 9828: 	$courseid=$env{'request.course.id'};
1.218     albertel 9829:     }
1.48      www      9830:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9831:     my $rest;
1.320     albertel 9832:     if (defined($therest[0])) {
1.48      www      9833:        $rest=join('.',@therest);
                   9834:     } else {
                   9835:        $rest='';
                   9836:     }
1.320     albertel 9837: 
1.57      www      9838:     my $qualifierrest=$qualifier;
                   9839:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9840:     my $spacequalifierrest=$space;
                   9841:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9842:     if ($realm eq 'user') {
1.48      www      9843: # --------------------------------------------------------------- user.resource
                   9844: 	if ($space eq 'resource') {
1.651     albertel 9845: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9846: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9847: 		 &&
1.744     albertel 9848: 		 ($symbparm eq &symbread()) ) {	
                   9849: 		# if we are in the middle of processing the resource the
                   9850: 		# get the value we are planning on committing
                   9851:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9852:                     return $Apache::lonhomework::results{$qualifierrest};
                   9853:                 } else {
                   9854:                     return $Apache::lonhomework::history{$qualifierrest};
                   9855:                 }
1.335     albertel 9856: 	    } else {
1.359     albertel 9857: 		my %restored;
1.620     albertel 9858: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9859: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9860: 		} else {
                   9861: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9862: 		}
1.335     albertel 9863: 		return $restored{$qualifierrest};
                   9864: 	    }
1.48      www      9865: # ----------------------------------------------------------------- user.access
                   9866:         } elsif ($space eq 'access') {
1.218     albertel 9867: 	    # FIXME - not supporting calls for a specific user
1.48      www      9868:             return &allowed($qualifier,$rest);
                   9869: # ------------------------------------------ user.preferences, user.environment
                   9870:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9871: 	    if (($uname eq $env{'user.name'}) &&
                   9872: 		($udom eq $env{'user.domain'})) {
                   9873: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9874: 	    } else {
1.359     albertel 9875: 		my %returnhash;
                   9876: 		if (!$publicuser) {
                   9877: 		    %returnhash=&userenvironment($udom,$uname,
                   9878: 						 $qualifierrest);
                   9879: 		}
1.218     albertel 9880: 		return $returnhash{$qualifierrest};
                   9881: 	    }
1.48      www      9882: # ----------------------------------------------------------------- user.course
                   9883:         } elsif ($space eq 'course') {
1.218     albertel 9884: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9885:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9886: # ------------------------------------------------------------------- user.role
                   9887:         } elsif ($space eq 'role') {
1.218     albertel 9888: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9889:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9890:             if ($qualifier eq 'value') {
                   9891: 		return $role;
                   9892:             } elsif ($qualifier eq 'extent') {
                   9893:                 return $where;
                   9894:             }
                   9895: # ----------------------------------------------------------------- user.domain
                   9896:         } elsif ($space eq 'domain') {
1.218     albertel 9897:             return $udom;
1.48      www      9898: # ------------------------------------------------------------------- user.name
                   9899:         } elsif ($space eq 'name') {
1.218     albertel 9900:             return $uname;
1.48      www      9901: # ---------------------------------------------------- Any other user namespace
1.29      www      9902:         } else {
1.359     albertel 9903: 	    my %reply;
                   9904: 	    if (!$publicuser) {
                   9905: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9906: 	    }
                   9907: 	    return $reply{$qualifierrest};
1.48      www      9908:         }
1.236     www      9909:     } elsif ($realm eq 'query') {
                   9910: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9911:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9912: 						[$spacequalifierrest]);
1.620     albertel 9913: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9914:    } elsif ($realm eq 'request') {
1.48      www      9915: # ------------------------------------------------------------- request.browser
                   9916:         if ($space eq 'browser') {
1.1145    bisitz   9917:             return $env{'browser.'.$qualifier};
1.57      www      9918: # ------------------------------------------------------------ request.filename
                   9919:         } else {
1.620     albertel 9920:             return $env{'request.'.$spacequalifierrest};
1.29      www      9921:         }
1.28      www      9922:     } elsif ($realm eq 'course') {
1.48      www      9923: # ---------------------------------------------------------- course.description
1.620     albertel 9924:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9925:     } elsif ($realm eq 'resource') {
1.165     www      9926: 
1.620     albertel 9927: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9928: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9929: 	}
1.693     albertel 9930: 
1.1232    raeburn  9931:         if ($qualifier eq '') {
                   9932: 	    if ($space eq 'title') {
                   9933: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9934: 	        return &gettitle($symbparm);
                   9935: 	    }
1.693     albertel 9936: 	
1.1232    raeburn  9937: 	    if ($space eq 'map') {
                   9938: 	        my ($map) = &decode_symb($symbparm);
                   9939: 	        return &symbread($map);
                   9940: 	    }
                   9941:             if ($space eq 'maptitle') {
                   9942:                 my ($map) = &decode_symb($symbparm);
                   9943:                 return &gettitle($map);
                   9944:             }
                   9945: 	    if ($space eq 'filename') {
                   9946: 	        if ($symbparm) {
                   9947: 		    return &clutter((&decode_symb($symbparm))[2]);
                   9948: 	        }
                   9949: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9950: 	    }
1.1232    raeburn  9951: 
1.1233    raeburn  9952:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   9953:                 if ($space eq 'visibleparts') {
                   9954:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9955:                     my $item;
                   9956:                     if (ref($navmap)) {
                   9957:                         my $res = $navmap->getBySymb($symbparm);
                   9958:                         my $parts = $res->parts();
                   9959:                         if (ref($parts) eq 'ARRAY') {
                   9960:                             $item = join(',',@{$parts});
                   9961:                         }
                   9962:                         undef($navmap);
1.1232    raeburn  9963:                     }
1.1233    raeburn  9964:                     return $item;
1.1232    raeburn  9965:                 }
                   9966:             }
                   9967:         }
1.693     albertel 9968: 
                   9969: 	my ($section, $group, @groups);
1.593     albertel 9970: 	my ($courselevelm,$courselevel);
1.1228    raeburn  9971:         if (($courseid eq '') && ($cid)) {
                   9972:             $courseid = $cid;
                   9973:         }
                   9974: 	if (($symbparm && $courseid) && 
                   9975: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      9976: 
1.218     albertel 9977: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9978: 
1.60      www      9979: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9980: 	    my $symbp=$symbparm;
1.735     albertel 9981: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9982: 
                   9983: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9984: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9985: 
1.620     albertel 9986: 	    if (($env{'user.name'} eq $uname) &&
                   9987: 		($env{'user.domain'} eq $udom)) {
                   9988: 		$section=$env{'request.course.sec'};
1.733     raeburn  9989:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9990:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9991: 	    } else {
1.539     albertel 9992: 		if (! defined($usection)) {
1.551     albertel 9993: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9994: 		} else {
                   9995: 		    $section = $usection;
                   9996: 		}
1.733     raeburn  9997:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9998: 	    }
                   9999: 
                   10000: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10001: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10002: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10003: 
1.593     albertel 10004: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10005: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10006: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10007: 
1.60      www      10008: # ----------------------------------------------------------- first, check user
1.624     albertel 10009: 
                   10010: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10011: 				       ([$courselevelr,'resource'],
                   10012: 					[$courselevelm,'map'     ],
                   10013: 					[$courselevel, 'course'  ]));
1.931     albertel 10014: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10015: 
1.594     albertel 10016: # ------------------------------------------------ second, check some of course
1.684     raeburn  10017:             my $coursereply;
1.691     raeburn  10018:             if (@groups > 0) {
                   10019:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10020:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10021:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10022:             }
1.96      www      10023: 
1.684     raeburn  10024: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10025: 				  $env{'course.'.$courseid.'.domain'},
                   10026: 				  'course',
                   10027: 				  ([$seclevelr,   'resource'],
                   10028: 				   [$seclevelm,   'map'     ],
                   10029: 				   [$seclevel,    'course'  ],
                   10030: 				   [$courselevelr,'resource']));
                   10031: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10032: 
1.60      www      10033: # ------------------------------------------------------ third, check map parms
1.218     albertel 10034: 	    my %parmhash=();
                   10035: 	    my $thisparm='';
                   10036: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10037: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10038: 		    &GDBM_READER(),0640)) {
1.218     albertel 10039: 		$thisparm=$parmhash{$symbparm};
                   10040: 		untie(%parmhash);
                   10041: 	    }
1.927     albertel 10042: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10043: 	}
1.594     albertel 10044: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10045: 
1.218     albertel 10046: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10047: 	my $filename;
                   10048: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10049: 	if ($symbparm) {
1.409     www      10050: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10051: 	} else {
1.620     albertel 10052: 	    $filename=$env{'request.filename'};
1.282     albertel 10053: 	}
                   10054: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10055: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10056: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10057: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10058: 
1.927     albertel 10059: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10060: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10061: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10062: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10063: 				     $env{'course.'.$courseid.'.domain'},
                   10064: 				     'course',
1.927     albertel 10065: 				     ([$courselevelm,'map'   ],
                   10066: 				      [$courselevel, 'course']));
                   10067: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10068: 	}
1.145     www      10069: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10070: 	unless ($space eq '0') {
1.336     albertel 10071: 	    my @parts=split(/_/,$space);
                   10072: 	    my $id=pop(@parts);
                   10073: 	    my $part=join('_',@parts);
                   10074: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10075: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10076: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10077: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10078: 	}
1.395     albertel 10079: 	if ($recurse) { return undef; }
                   10080: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10081: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10082: # ---------------------------------------------------- Any other user namespace
                   10083:     } elsif ($realm eq 'environment') {
                   10084: # ----------------------------------------------------------------- environment
1.620     albertel 10085: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10086: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10087: 	} else {
1.770     albertel 10088: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10089: 		return '';
                   10090: 	    }
1.219     albertel 10091: 	    my %returnhash=&userenvironment($udom,$uname,
                   10092: 					    $spacequalifierrest);
                   10093: 	    return $returnhash{$spacequalifierrest};
                   10094: 	}
1.28      www      10095:     } elsif ($realm eq 'system') {
1.48      www      10096: # ----------------------------------------------------------------- system.time
                   10097: 	if ($space eq 'time') {
                   10098: 	    return time;
                   10099:         }
1.696     albertel 10100:     } elsif ($realm eq 'server') {
                   10101: # ----------------------------------------------------------------- system.time
                   10102: 	if ($space eq 'name') {
                   10103: 	    return $ENV{'SERVER_NAME'};
                   10104:         }
1.28      www      10105:     }
1.48      www      10106:     return '';
1.61      www      10107: }
                   10108: 
1.927     albertel 10109: sub get_reply {
                   10110:     my ($reply_value) = @_;
1.940     raeburn  10111:     if (ref($reply_value) eq 'ARRAY') {
                   10112:         if (wantarray) {
                   10113: 	    return @$reply_value;
                   10114:         }
                   10115:         return $reply_value->[0];
                   10116:     } else {
                   10117:         return $reply_value;
1.927     albertel 10118:     }
                   10119: }
                   10120: 
1.691     raeburn  10121: sub check_group_parms {
                   10122:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10123:     my @groupitems = ();
                   10124:     my $resultitem;
1.927     albertel 10125:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10126:     foreach my $group (@{$groups}) {
                   10127:         foreach my $level (@levels) {
1.927     albertel 10128:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10129:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10130:         }
                   10131:     }
                   10132:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10133:                             $env{'course.'.$courseid.'.domain'},
                   10134:                                      'course',@groupitems);
                   10135:     return $coursereply;
                   10136: }
                   10137: 
                   10138: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10139:     my ($courseid,@groups) = @_;
                   10140:     @groups = sort(@groups);
1.691     raeburn  10141:     return @groups;
                   10142: }
                   10143: 
1.395     albertel 10144: sub packages_tab_default {
                   10145:     my ($uri,$varname)=@_;
                   10146:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10147: 
                   10148:     my (@extension,@specifics,$do_default);
                   10149:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10150: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10151: 	if ($pack_type eq 'default') {
                   10152: 	    $do_default=1;
                   10153: 	} elsif ($pack_type eq 'extension') {
                   10154: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10155: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10156: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10157: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10158: 	}
                   10159:     }
                   10160:     # first look for a package that matches the requested part id
                   10161:     foreach my $package (@specifics) {
                   10162: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10163: 	next if ($pack_part ne $part);
                   10164: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10165: 	    return $packagetab{"$pack_type&$name&default"};
                   10166: 	}
                   10167:     }
                   10168:     # look for any possible matching non extension_ package
                   10169:     foreach my $package (@specifics) {
                   10170: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10171: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10172: 	    return $packagetab{"$pack_type&$name&default"};
                   10173: 	}
1.585     albertel 10174: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10175: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10176: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10177: 	}
                   10178:     }
1.738     albertel 10179:     # look for any posible extension_ match
                   10180:     foreach my $package (@extension) {
                   10181: 	my ($package,$pack_type)=@{$package};
                   10182: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10183: 	    return $packagetab{"$pack_type&$name&default"};
                   10184: 	}
                   10185: 	if (defined($packagetab{$package."&$name&default"})) {
                   10186: 	    return $packagetab{$package."&$name&default"};
                   10187: 	}
                   10188:     }
                   10189:     # look for a global default setting
                   10190:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10191: 	return $packagetab{"default&$name&default"};
                   10192:     }
1.395     albertel 10193:     return undef;
                   10194: }
                   10195: 
1.334     albertel 10196: sub add_prefix_and_part {
                   10197:     my ($prefix,$part)=@_;
                   10198:     my $keyroot;
                   10199:     if (defined($prefix) && $prefix !~ /^__/) {
                   10200: 	# prefix that has a part already
                   10201: 	$keyroot=$prefix;
                   10202:     } elsif (defined($prefix)) {
                   10203: 	# prefix that is missing a part
                   10204: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10205:     } else {
                   10206: 	# no prefix at all
                   10207: 	if (defined($part)) { $keyroot='_'.$part; }
                   10208:     }
                   10209:     return $keyroot;
                   10210: }
                   10211: 
1.71      www      10212: # ---------------------------------------------------------------- Get metadata
                   10213: 
1.599     albertel 10214: my %metaentry;
1.1070    www      10215: my %importedpartids;
1.71      www      10216: sub metadata {
1.176     www      10217:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10218:     $uri=&declutter($uri);
1.288     albertel 10219:     # if it is a non metadata possible uri return quickly
1.529     albertel 10220:     if (($uri eq '') || 
                   10221: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10222: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10223:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10224: 	return undef;
                   10225:     }
1.1261    raeburn  10226:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10227: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10228: 	return undef;
1.288     albertel 10229:     }
1.73      www      10230:     my $filename=$uri;
                   10231:     $uri=~s/\.meta$//;
1.172     www      10232: #
                   10233: # Is the metadata already cached?
1.177     www      10234: # Look at timestamp of caching
1.172     www      10235: # Everything is cached by the main uri, libraries are never directly cached
                   10236: #
1.428     albertel 10237:     if (!defined($liburi)) {
1.599     albertel 10238: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10239: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10240:     }
                   10241:     {
1.1069    www      10242: # Imported parts would go here
1.1070    www      10243:         my %importedids=();
                   10244:         my @origfileimportpartids=();
1.1069    www      10245:         my $importedparts=0;
1.172     www      10246: #
                   10247: # Is this a recursive call for a library?
                   10248: #
1.599     albertel 10249: #	if (! exists($metacache{$uri})) {
                   10250: #	    $metacache{$uri}={};
                   10251: #	}
1.924     albertel 10252: 	my $cachetime = 60*60;
1.171     www      10253:         if ($liburi) {
                   10254: 	    $liburi=&declutter($liburi);
                   10255:             $filename=$liburi;
1.401     bowersj2 10256:         } else {
1.599     albertel 10257: 	    &devalidate_cache_new('meta',$uri);
                   10258: 	    undef(%metaentry);
1.401     bowersj2 10259: 	}
1.140     www      10260:         my %metathesekeys=();
1.73      www      10261:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10262: 	my $metastring;
1.1140    www      10263: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10264: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10265: 	    $metastring = 
1.929     albertel 10266: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10267: 					  ('grade_target' => 'meta'));
                   10268: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10269: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10270:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10271: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10272: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10273: 	    $metastring=&getfile($file);
1.489     albertel 10274: 	}
1.208     albertel 10275:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10276:         my $token;
1.140     www      10277:         undef %metathesekeys;
1.71      www      10278:         while ($token=$parser->get_token) {
1.339     albertel 10279: 	    if ($token->[0] eq 'S') {
                   10280: 		if (defined($token->[2]->{'package'})) {
1.172     www      10281: #
                   10282: # This is a package - get package info
                   10283: #
1.339     albertel 10284: 		    my $package=$token->[2]->{'package'};
                   10285: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10286: 		    if (defined($token->[2]->{'id'})) { 
                   10287: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10288: 		    }
1.599     albertel 10289: 		    if ($metaentry{':packages'}) {
                   10290: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10291: 		    } else {
1.599     albertel 10292: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10293: 		    }
1.736     albertel 10294: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10295: 			my $part=$keyroot;
                   10296: 			$part=~s/^\_//;
1.736     albertel 10297: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10298: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10299: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10300: 			    # ignore package.tab specified default values
                   10301:                             # here &package_tab_default() will fetch those
                   10302: 			    if ($subp eq 'default') { next; }
1.736     albertel 10303: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10304: 			    my $unikey;
                   10305: 			    if ($pack =~ /_0$/) {
                   10306: 				$unikey='parameter_0_'.$name;
                   10307: 				$part=0;
                   10308: 			    } else {
                   10309: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10310: 			    }
1.339     albertel 10311: 			    if ($subp eq 'display') {
                   10312: 				$value.=' [Part: '.$part.']';
                   10313: 			    }
1.599     albertel 10314: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10315: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10316: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10317: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10318: 			    }
1.599     albertel 10319: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10320: 				$metaentry{':'.$unikey}=
                   10321: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10322: 			    }
1.339     albertel 10323: 			}
                   10324: 		    }
                   10325: 		} else {
1.172     www      10326: #
                   10327: # This is not a package - some other kind of start tag
1.339     albertel 10328: #
                   10329: 		    my $entry=$token->[1];
1.1068    www      10330: 		    my $unikey='';
1.175     www      10331: 
1.339     albertel 10332: 		    if ($entry eq 'import') {
1.175     www      10333: #
                   10334: # Importing a library here
1.339     albertel 10335: #
1.1067    www      10336:                         my $location=$parser->get_text('/import');
                   10337:                         my $dir=$filename;
                   10338:                         $dir=~s|[^/]*$||;
                   10339:                         $location=&filelocation($dir,$location);
1.1069    www      10340:                        
1.1068    www      10341:                         my $importmode=$token->[2]->{'importmode'};
                   10342:                         if ($importmode eq 'problem') {
1.1069    www      10343: # Import as problem/response
1.1068    www      10344:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10345:                         } elsif ($importmode eq 'part') {
                   10346: # Import as part(s)
1.1069    www      10347:                            $importedparts=1;
                   10348: # We need to get the original file and the imported file to get the part order correct
                   10349: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10350: # Load and inspect original file
1.1070    www      10351:                            if ($#origfileimportpartids<0) {
                   10352:                               undef(%importedpartids);
                   10353:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10354:                               my $origfile=&getfile($origfilelocation);
                   10355:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10356:                            }
                   10357: 
1.1069    www      10358: # Load and inspect imported file
                   10359:                            my $impfile=&getfile($location);
                   10360:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10361:                            if ($#impfilepartids>=0) {
                   10362: # This problem had parts
1.1070    www      10363:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10364:                            } else {
                   10365: # Importing by turning a single problem into a problem part
                   10366: # It gets the import-tags ID as part-ID
                   10367:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10368:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10369:                            }
1.1068    www      10370:                         } else {
                   10371: # Normal import
                   10372:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10373:                            if (defined($token->[2]->{'id'})) {
                   10374:                               $unikey.='_'.$token->[2]->{'id'};
                   10375:                            }
1.1067    www      10376:                         }
                   10377: 
1.339     albertel 10378: 			if ($depthcount<20) {
1.736     albertel 10379: 			    my $metadata = 
                   10380: 				&metadata($uri,'keys', $location,$unikey,
                   10381: 					  $depthcount+1);
                   10382: 			    foreach my $meta (split(',',$metadata)) {
                   10383: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10384: 				$metathesekeys{$meta}=1;
1.339     albertel 10385: 			    }
1.1068    www      10386: 			
                   10387:                         }
1.1067    www      10388: 		    } else {
                   10389: #
                   10390: # Not importing, some other kind of non-package, non-library start tag
                   10391: # 
                   10392:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10393:                         if (defined($token->[2]->{'id'})) {
                   10394:                             $unikey.='_'.$token->[2]->{'id'};
                   10395:                         }
1.339     albertel 10396: 			if (defined($token->[2]->{'name'})) { 
                   10397: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10398: 			}
                   10399: 			$metathesekeys{$unikey}=1;
1.736     albertel 10400: 			foreach my $param (@{$token->[3]}) {
                   10401: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10402: 				$token->[2]->{$param};
1.339     albertel 10403: 			}
                   10404: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10405: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10406: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10407: 		 # only ws inside the tag, and not in default, so use default
                   10408: 		 # as value
1.599     albertel 10409: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10410: 			} elsif ( $internaltext =~ /\S/ ) {
                   10411: 		  # something interesting inside the tag
                   10412: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10413: 			} else {
1.908     albertel 10414: 		  # no interesting values, don't set a default
1.339     albertel 10415: 			}
1.172     www      10416: # end of not-a-package not-a-library import
1.339     albertel 10417: 		    }
1.172     www      10418: # end of not-a-package start tag
1.339     albertel 10419: 		}
1.172     www      10420: # the next is the end of "start tag"
1.339     albertel 10421: 	    }
                   10422: 	}
1.483     albertel 10423: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10424: 	$extension = lc($extension);
                   10425: 	if ($extension eq 'htm') { $extension='html'; }
                   10426: 
1.737     albertel 10427: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10428: 	    #no specific packages #how's our extension
                   10429: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10430: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10431: 					 \%metathesekeys);
                   10432: 	}
1.883     albertel 10433: 
                   10434: 	if (!exists($metaentry{':packages'})
                   10435: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10436: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10437: 		#no specific packages well let's get default then
                   10438: 		if ($key!~/^default&/) { next; }
1.488     albertel 10439: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10440: 					     \%metathesekeys);
                   10441: 	    }
                   10442: 	}
1.338     www      10443: # are there custom rights to evaluate
1.599     albertel 10444: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10445: 
1.338     www      10446:     #
                   10447:     # Importing a rights file here
1.339     albertel 10448:     #
                   10449: 	    unless ($depthcount) {
1.599     albertel 10450: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10451: 		my $dir=$filename;
                   10452: 		$dir=~s|[^/]*$||;
                   10453: 		$location=&filelocation($dir,$location);
1.736     albertel 10454: 		my $rights_metadata =
                   10455: 		    &metadata($uri,'keys',$location,'_rights',
                   10456: 			      $depthcount+1);
                   10457: 		foreach my $rights (split(',',$rights_metadata)) {
                   10458: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10459: 		    $metathesekeys{$rights}=1;
1.339     albertel 10460: 		}
                   10461: 	    }
                   10462: 	}
1.737     albertel 10463: 	# uniqifiy package listing
                   10464: 	my %seen;
                   10465: 	my @uniq_packages =
                   10466: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10467: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10468: 
1.1070    www      10469:         if ($importedparts) {
                   10470: # We had imported parts and need to rebuild partorder
                   10471:            $metaentry{':partorder'}='';
                   10472:            $metathesekeys{'partorder'}=1;
                   10473:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10474:                if ($origfileimportpartids[$index] eq 'part') {
                   10475: # original part, part of the problem
                   10476:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10477:                } else {
                   10478: # we have imported parts at this position
                   10479:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10480:                }
                   10481:            }
                   10482:            $metaentry{':partorder'}=~s/^\,//;
                   10483:         }
                   10484: 
1.737     albertel 10485: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10486: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10487: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10488: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10489: # this is the end of "was not already recently cached
1.71      www      10490:     }
1.599     albertel 10491:     return $metaentry{':'.$what};
1.261     albertel 10492: }
                   10493: 
1.488     albertel 10494: sub metadata_create_package_def {
1.483     albertel 10495:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10496:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10497:     if ($subp eq 'default') { next; }
                   10498:     
1.599     albertel 10499:     if (defined($metaentry{':packages'})) {
                   10500: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10501:     } else {
1.599     albertel 10502: 	$metaentry{':packages'}=$package;
1.483     albertel 10503:     }
                   10504:     my $value=$packagetab{$key};
                   10505:     my $unikey;
                   10506:     $unikey='parameter_0_'.$name;
1.599     albertel 10507:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10508:     $$metathesekeys{$unikey}=1;
1.599     albertel 10509:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10510: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10511:     }
1.599     albertel 10512:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10513: 	$metaentry{':'.$unikey}=
                   10514: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10515:     }
                   10516: }
                   10517: 
1.261     albertel 10518: sub metadata_generate_part0 {
                   10519:     my ($metadata,$metacache,$uri) = @_;
                   10520:     my %allnames;
1.737     albertel 10521:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10522: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10523: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10524: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10525: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10526: 	    $allnames{$name}=$part;
                   10527: 	  }
                   10528: 	}
                   10529:     }
                   10530:     foreach my $name (keys(%allnames)) {
                   10531:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10532:       my $key=":parameter_0_$name";
1.261     albertel 10533:       $$metacache{"$key.part"}='0';
                   10534:       $$metacache{"$key.name"}=$name;
1.428     albertel 10535:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10536: 					   $allnames{$name}.'_'.$name.
                   10537: 					   '.type'};
1.428     albertel 10538:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10539: 			     '.display'};
1.644     www      10540:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10541:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10542:       $$metacache{"$key.display"}=$olddis;
                   10543:     }
1.71      www      10544: }
                   10545: 
1.764     albertel 10546: # ------------------------------------------------------ Devalidate title cache
                   10547: 
                   10548: sub devalidate_title_cache {
                   10549:     my ($url)=@_;
                   10550:     if (!$env{'request.course.id'}) { return; }
                   10551:     my $symb=&symbread($url);
                   10552:     if (!$symb) { return; }
                   10553:     my $key=$env{'request.course.id'}."\0".$symb;
                   10554:     &devalidate_cache_new('title',$key);
                   10555: }
                   10556: 
1.1014    droeschl 10557: # ------------------------------------------------- Get the title of a course
                   10558: 
                   10559: sub current_course_title {
                   10560:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10561: }
1.301     www      10562: # ------------------------------------------------- Get the title of a resource
                   10563: 
                   10564: sub gettitle {
                   10565:     my $urlsymb=shift;
                   10566:     my $symb=&symbread($urlsymb);
1.534     albertel 10567:     if ($symb) {
1.620     albertel 10568: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10569: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10570: 	if (defined($cached)) { 
                   10571: 	    return $result;
                   10572: 	}
1.534     albertel 10573: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10574: 	my $title='';
1.907     albertel 10575: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10576: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10577: 	} else {
                   10578: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10579: 		    &GDBM_READER(),0640)) {
                   10580: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10581: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10582: 		untie(%bighash);
                   10583: 	    }
1.534     albertel 10584: 	}
                   10585: 	$title=~s/\&colon\;/\:/gs;
                   10586: 	if ($title) {
1.1159    www      10587: # Remember both $symb and $title for dynamic metadata
                   10588:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10589:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10590: # Cache this title and then return it
1.599     albertel 10591: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10592: 	}
                   10593: 	$urlsymb=$url;
                   10594:     }
                   10595:     my $title=&metadata($urlsymb,'title');
                   10596:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10597:     return $title;
1.301     www      10598: }
1.613     albertel 10599: 
1.614     albertel 10600: sub get_slot {
                   10601:     my ($which,$cnum,$cdom)=@_;
                   10602:     if (!$cnum || !$cdom) {
1.790     albertel 10603: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10604: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10605: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10606:     }
1.703     albertel 10607:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10608:     my %slotinfo;
                   10609:     if (exists($remembered{$key})) {
                   10610: 	$slotinfo{$which} = $remembered{$key};
                   10611:     } else {
                   10612: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10613: 	&Apache::lonhomework::showhash(%slotinfo);
                   10614: 	my ($tmp)=keys(%slotinfo);
                   10615: 	if ($tmp=~/^error:/) { return (); }
                   10616: 	$remembered{$key} = $slotinfo{$which};
                   10617:     }
1.616     albertel 10618:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10619: 	return %{$slotinfo{$which}};
                   10620:     }
                   10621:     return $slotinfo{$which};
1.614     albertel 10622: }
1.1150    raeburn  10623: 
                   10624: sub get_reservable_slots {
                   10625:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10626:     my $now = time;
                   10627:     my $reservable_info;
                   10628:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10629:     if (exists($remembered{$key})) {
                   10630:         $reservable_info = $remembered{$key};
                   10631:     } else {
                   10632:         my %resv;
                   10633:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10634:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10635:         $reservable_info = \%resv;
                   10636:         $remembered{$key} = $reservable_info;
                   10637:     }
                   10638:     return $reservable_info;
                   10639: }
                   10640: 
                   10641: sub get_course_slots {
                   10642:     my ($cnum,$cdom) = @_;
                   10643:     my $hashid=$cnum.':'.$cdom;
                   10644:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10645:     if (defined($cached)) {
                   10646:         if (ref($result) eq 'HASH') {
                   10647:             return %{$result};
                   10648:         }
                   10649:     } else {
                   10650:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10651:         my ($tmp) = keys(%slots);
                   10652:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10653:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10654:             return %slots;
                   10655:         }
                   10656:     }
                   10657:     return;
                   10658: }
                   10659: 
                   10660: sub devalidate_slots_cache {
                   10661:     my ($cnum,$cdom)=@_;
                   10662:     my $hashid=$cnum.':'.$cdom;
                   10663:     &devalidate_cache_new('allslots',$hashid);
                   10664: }
                   10665: 
1.1181    raeburn  10666: sub get_coursechange {
                   10667:     my ($cdom,$cnum) = @_;
                   10668:     if ($cdom eq '' || $cnum eq '') {
                   10669:         return unless ($env{'request.course.id'});
                   10670:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10671:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10672:     }
                   10673:     my $hashid=$cdom.'_'.$cnum;
                   10674:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10675:     if ((defined($cached)) && ($change ne '')) {
                   10676:         return $change;
                   10677:     } else {
                   10678:         my %crshash;
                   10679:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10680:         if ($crshash{'internal.contentchange'} eq '') {
                   10681:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10682:             if ($change eq '') {
                   10683:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10684:                 $change = $crshash{'internal.created'};
                   10685:             }
                   10686:         } else {
                   10687:             $change = $crshash{'internal.contentchange'};
                   10688:         }
                   10689:         my $cachetime = 600;
                   10690:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10691:     }
                   10692:     return $change;
                   10693: }
                   10694: 
                   10695: sub devalidate_coursechange_cache {
                   10696:     my ($cnum,$cdom)=@_;
                   10697:     my $hashid=$cnum.':'.$cdom;
                   10698:     &devalidate_cache_new('crschange',$hashid);
                   10699: }
                   10700: 
1.31      www      10701: # ------------------------------------------------- Update symbolic store links
                   10702: 
                   10703: sub symblist {
                   10704:     my ($mapname,%newhash)=@_;
1.438     www      10705:     $mapname=&deversion(&declutter($mapname));
1.31      www      10706:     my %hash;
1.620     albertel 10707:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10708:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10709:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10710: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10711: 		next if ($url eq 'last_known'
                   10712: 			 && $env{'form.no_update_last_known'});
                   10713: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10714: 						    $newhash{$url}->[1],
                   10715: 						    $newhash{$url}->[0]);
1.191     harris41 10716:             }
1.31      www      10717:             if (untie(%hash)) {
                   10718: 		return 'ok';
                   10719:             }
                   10720:         }
                   10721:     }
                   10722:     return 'error';
1.212     www      10723: }
                   10724: 
                   10725: # --------------------------------------------------------------- Verify a symb
                   10726: 
                   10727: sub symbverify {
1.1190    raeburn  10728:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10729:     my $thisfn=$thisurl;
1.439     www      10730:     $thisfn=&declutter($thisfn);
1.215     www      10731: # direct jump to resource in page or to a sequence - will construct own symbs
                   10732:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10733: # check URL part
1.409     www      10734:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10735: 
1.431     www      10736:     unless ($url eq $thisfn) { return 0; }
1.213     www      10737: 
1.216     www      10738:     $symb=&symbclean($symb);
1.510     www      10739:     $thisurl=&deversion($thisurl);
1.439     www      10740:     $thisfn=&deversion($thisfn);
1.213     www      10741: 
                   10742:     my %bighash;
                   10743:     my $okay=0;
1.431     www      10744: 
1.620     albertel 10745:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10746:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10747:         my $noclutter;
1.1032    raeburn  10748:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10749:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10750:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10751:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10752:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10753:                 $noclutter = 1;
                   10754:             }
                   10755:         }
                   10756:         my $ids;
                   10757:         if ($noclutter) {
                   10758:             $ids=$bighash{'ids_'.$thisurl};
                   10759:         } else {
                   10760:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10761:         }
1.1102    raeburn  10762:         unless ($ids) {
                   10763:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10764:             $ids=$bighash{$idkey};
1.216     www      10765:         }
                   10766:         if ($ids) {
                   10767: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10768:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10769:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10770:             }
1.800     albertel 10771: 	    foreach my $id (split(/\,/,$ids)) {
                   10772: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10773:                if (
                   10774:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10775:    eq $symb) {
                   10776:                    if (ref($encstate)) {
                   10777:                        $$encstate = $bighash{'encrypted_'.$id};
                   10778:                    }
1.620     albertel 10779: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10780: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10781:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10782: 		       $okay=1;
1.1202    raeburn  10783:                        last;
1.582     albertel 10784: 		   }
                   10785: 	       }
1.216     www      10786: 	   }
                   10787:         }
1.213     www      10788: 	untie(%bighash);
                   10789:     }
                   10790:     return $okay;
1.31      www      10791: }
                   10792: 
1.210     www      10793: # --------------------------------------------------------------- Clean-up symb
                   10794: 
                   10795: sub symbclean {
                   10796:     my $symb=shift;
1.568     albertel 10797:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10798: # remove version from map
                   10799:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10800: 
1.210     www      10801: # remove version from URL
                   10802:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10803: 
1.507     www      10804: # remove wrapper
                   10805: 
1.510     www      10806:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10807:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10808:     return $symb;
1.409     www      10809: }
                   10810: 
                   10811: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10812: 
                   10813: sub encode_symb {
                   10814:     my ($map,$resid,$url)=@_;
                   10815:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10816: }
1.409     www      10817: 
                   10818: sub decode_symb {
1.568     albertel 10819:     my $symb=shift;
                   10820:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10821:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10822:     return (&fixversion($map),$resid,&fixversion($url));
                   10823: }
                   10824: 
                   10825: sub fixversion {
                   10826:     my $fn=shift;
1.609     banghart 10827:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10828:     my %bighash;
                   10829:     my $uri=&clutter($fn);
1.620     albertel 10830:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10831: # is this cached?
1.599     albertel 10832:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10833:     if (defined($cached)) { return $result; }
                   10834: # unfortunately not cached, or expired
1.620     albertel 10835:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10836: 	    &GDBM_READER(),0640)) {
                   10837:  	if ($bighash{'version_'.$uri}) {
                   10838:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10839:  	    unless (($version eq 'mostrecent') || 
                   10840: 		    ($version==&getversion($uri))) {
1.440     www      10841:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10842:  	    }
                   10843:  	}
                   10844:  	untie %bighash;
1.413     www      10845:     }
1.599     albertel 10846:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10847: }
                   10848: 
                   10849: sub deversion {
                   10850:     my $url=shift;
                   10851:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10852:     return $url;
1.210     www      10853: }
                   10854: 
1.31      www      10855: # ------------------------------------------------------ Return symb list entry
                   10856: 
                   10857: sub symbread {
1.249     www      10858:     my ($thisfn,$donotrecurse)=@_;
1.1206    raeburn  10859:     my $cache_str;
                   10860:     if ($thisfn ne '') {
                   10861:         $cache_str='request.symbread.cached.'.$thisfn;
                   10862:         if ($env{$cache_str} ne '') {
1.1179    raeburn  10863:             return $env{$cache_str};
                   10864:         }
1.1206    raeburn  10865:     } else {
1.242     www      10866: # no filename provided? try from environment
1.620     albertel 10867:         if ($env{'request.symb'}) {
                   10868: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10869: 	}
1.620     albertel 10870: 	$thisfn=$env{'request.filename'};
1.44      www      10871:     }
1.569     albertel 10872:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10873: # is that filename actually a symb? Verify, clean, and return
                   10874:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10875: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10876: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10877: 	}
1.242     www      10878:     }
1.44      www      10879:     $thisfn=declutter($thisfn);
1.31      www      10880:     my %hash;
1.37      www      10881:     my %bighash;
                   10882:     my $syval='';
1.620     albertel 10883:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10884:         my $targetfn = $thisfn;
1.609     banghart 10885:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10886:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10887:         }
1.687     albertel 10888: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10889: 	    $targetfn=$1;
                   10890: 	}
1.620     albertel 10891:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10892:                       &GDBM_READER(),0640)) {
1.481     raeburn  10893: 	    $syval=$hash{$targetfn};
1.37      www      10894:             untie(%hash);
                   10895:         }
                   10896: # ---------------------------------------------------------- There was an entry
                   10897:         if ($syval) {
1.601     albertel 10898: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10899: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10900: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10901: 		    #return $env{$cache_str}='';
1.601     albertel 10902: 		#}    
                   10903: 		#$syval.=$1;
                   10904: 	    #}
1.37      www      10905:         } else {
                   10906: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10907:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10908:                             &GDBM_READER(),0640)) {
1.37      www      10909: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10910:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10911:               unless ($ids) { 
                   10912:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10913:               }
                   10914:               unless ($ids) {
                   10915: # alias?
                   10916: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10917:               }
1.37      www      10918:               if ($ids) {
                   10919: # ------------------------------------------------------------------- Has ID(s)
                   10920:                  my @possibilities=split(/\,/,$ids);
1.39      www      10921:                  if ($#possibilities==0) {
                   10922: # ----------------------------------------------- There is only one possibility
1.37      www      10923: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10924: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10925: 						    $resid,$thisfn);
1.249     www      10926:                  } elsif (!$donotrecurse) {
1.39      www      10927: # ------------------------------------------ There is more than one possibility
                   10928:                      my $realpossible=0;
1.800     albertel 10929:                      foreach my $id (@possibilities) {
                   10930: 			 my $file=$bighash{'src_'.$id};
1.39      www      10931:                          if (&allowed('bre',$file)) {
1.800     albertel 10932:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10933:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10934: 				$realpossible++;
1.626     albertel 10935:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10936: 						    $resid,$thisfn);
1.39      www      10937:                             }
                   10938: 			 }
1.191     harris41 10939:                      }
1.39      www      10940: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10941:                  } else {
                   10942:                      $syval='';
1.37      www      10943:                  }
                   10944: 	      }
                   10945:               untie(%bighash)
1.481     raeburn  10946:            }
1.31      www      10947:         }
1.62      www      10948:         if ($syval) {
1.620     albertel 10949: 	    return $env{$cache_str}=$syval;
1.62      www      10950:         }
1.31      www      10951:     }
1.949     raeburn  10952:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10953:     return $env{$cache_str}='';
1.31      www      10954: }
                   10955: 
                   10956: # ---------------------------------------------------------- Return random seed
                   10957: 
1.32      www      10958: sub numval {
                   10959:     my $txt=shift;
                   10960:     $txt=~tr/A-J/0-9/;
                   10961:     $txt=~tr/a-j/0-9/;
                   10962:     $txt=~tr/K-T/0-9/;
                   10963:     $txt=~tr/k-t/0-9/;
                   10964:     $txt=~tr/U-Z/0-5/;
                   10965:     $txt=~tr/u-z/0-5/;
                   10966:     $txt=~s/\D//g;
1.564     albertel 10967:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10968:     return int($txt);
1.368     albertel 10969: }
                   10970: 
1.484     albertel 10971: sub numval2 {
                   10972:     my $txt=shift;
                   10973:     $txt=~tr/A-J/0-9/;
                   10974:     $txt=~tr/a-j/0-9/;
                   10975:     $txt=~tr/K-T/0-9/;
                   10976:     $txt=~tr/k-t/0-9/;
                   10977:     $txt=~tr/U-Z/0-5/;
                   10978:     $txt=~tr/u-z/0-5/;
                   10979:     $txt=~s/\D//g;
                   10980:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10981:     my $total;
                   10982:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10983:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10984:     return int($total);
                   10985: }
                   10986: 
1.575     albertel 10987: sub numval3 {
                   10988:     use integer;
                   10989:     my $txt=shift;
                   10990:     $txt=~tr/A-J/0-9/;
                   10991:     $txt=~tr/a-j/0-9/;
                   10992:     $txt=~tr/K-T/0-9/;
                   10993:     $txt=~tr/k-t/0-9/;
                   10994:     $txt=~tr/U-Z/0-5/;
                   10995:     $txt=~tr/u-z/0-5/;
                   10996:     $txt=~s/\D//g;
                   10997:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10998:     my $total;
                   10999:     foreach my $val (@txts) { $total+=$val; }
                   11000:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11001:     return $total;
                   11002: }
                   11003: 
1.675     albertel 11004: sub digest {
                   11005:     my ($data)=@_;
                   11006:     my $digest=&Digest::MD5::md5($data);
                   11007:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11008:     my ($e,$f);
                   11009:     {
                   11010:         use integer;
                   11011:         $e=($a+$b);
                   11012:         $f=($c+$d);
                   11013:         if ($_64bit) {
                   11014:             $e=(($e<<32)>>32);
                   11015:             $f=(($f<<32)>>32);
                   11016:         }
                   11017:     }
                   11018:     if (wantarray) {
                   11019: 	return ($e,$f);
                   11020:     } else {
                   11021: 	my $g;
                   11022: 	{
                   11023: 	    use integer;
                   11024: 	    $g=($e+$f);
                   11025: 	    if ($_64bit) {
                   11026: 		$g=(($g<<32)>>32);
                   11027: 	    }
                   11028: 	}
                   11029: 	return $g;
                   11030:     }
                   11031: }
                   11032: 
1.368     albertel 11033: sub latest_rnd_algorithm_id {
1.675     albertel 11034:     return '64bit5';
1.366     albertel 11035: }
1.32      www      11036: 
1.503     albertel 11037: sub get_rand_alg {
                   11038:     my ($courseid)=@_;
1.790     albertel 11039:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11040:     if ($courseid) {
1.620     albertel 11041: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11042:     }
                   11043:     return &latest_rnd_algorithm_id();
                   11044: }
                   11045: 
1.562     albertel 11046: sub validCODE {
                   11047:     my ($CODE)=@_;
                   11048:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11049:     return 0;
                   11050: }
                   11051: 
1.491     albertel 11052: sub getCODE {
1.620     albertel 11053:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11054:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11055: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11056: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11057: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11058:     }
                   11059:     return undef;
                   11060: }
1.1133    foxr     11061: #
                   11062: #  Determines the random seed for a specific context:
                   11063: #
                   11064: # parameters:
                   11065: #   symb      - in course context the symb for the seed.
                   11066: #   course_id - The course id of the form domain_coursenum.
                   11067: #   domain    - Domain for the user.
                   11068: #   course    - Course for the user.
                   11069: #   cenv      - environment of the course.
                   11070: #
                   11071: # NOTE:
                   11072: #   All parameters are picked out of the environment if missing
                   11073: #   or not defined.
                   11074: #   If a symb cannot be determined the current time is used instead.
                   11075: #
                   11076: #  For a given well defined symb, courside, domain, username,
                   11077: #  and course environment, the seed is reproducible.
                   11078: #
1.31      www      11079: sub rndseed {
1.1133    foxr     11080:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11081:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11082:     if (!defined($symb)) {
1.366     albertel 11083: 	unless ($symb=$wsymb) { return time; }
                   11084:     }
1.1146    foxr     11085:     if (!defined $courseid) { 
                   11086: 	$courseid=$wcourseid; 
                   11087:     }
                   11088:     if (!defined $domain) { $domain=$wdomain; }
                   11089:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11090: 
                   11091:     my $which;
                   11092:     if (defined($cenv->{'rndseed'})) {
                   11093: 	$which = $cenv->{'rndseed'};
                   11094:     } else {
                   11095: 	$which =&get_rand_alg($courseid);
                   11096:     }
1.491     albertel 11097:     if (defined(&getCODE())) {
1.1133    foxr     11098: 
1.675     albertel 11099: 	if ($which eq '64bit5') {
                   11100: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11101: 	} elsif ($which eq '64bit4') {
1.575     albertel 11102: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11103: 	} else {
                   11104: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11105: 	}
1.675     albertel 11106:     } elsif ($which eq '64bit5') {
                   11107: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11108:     } elsif ($which eq '64bit4') {
                   11109: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11110:     } elsif ($which eq '64bit3') {
                   11111: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11112:     } elsif ($which eq '64bit2') {
                   11113: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11114:     } elsif ($which eq '64bit') {
                   11115: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11116:     }
                   11117:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11118: }
                   11119: 
                   11120: sub rndseed_32bit {
                   11121:     my ($symb,$courseid,$domain,$username)=@_;
                   11122:     {
                   11123: 	use integer;
                   11124: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11125: 	my $symbseed=numval($symb) << 22;
                   11126: 	my $namechck=unpack("%32C*",$username) << 17;
                   11127: 	my $nameseed=numval($username) << 12;
                   11128: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11129: 	my $courseseed=unpack("%32C*",$courseid);
                   11130: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11131: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11132: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11133: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11134: 	return $num;
                   11135:     }
                   11136: }
                   11137: 
                   11138: sub rndseed_64bit {
                   11139:     my ($symb,$courseid,$domain,$username)=@_;
                   11140:     {
                   11141: 	use integer;
                   11142: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11143: 	my $symbseed=numval($symb) << 10;
                   11144: 	my $namechck=unpack("%32S*",$username);
                   11145: 	
                   11146: 	my $nameseed=numval($username) << 21;
                   11147: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11148: 	my $courseseed=unpack("%32S*",$courseid);
                   11149: 	
                   11150: 	my $num1=$symbchck+$symbseed+$namechck;
                   11151: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11152: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11153: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11154: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11155: 	return "$num1,$num2";
1.155     albertel 11156:     }
1.366     albertel 11157: }
                   11158: 
1.443     albertel 11159: sub rndseed_64bit2 {
                   11160:     my ($symb,$courseid,$domain,$username)=@_;
                   11161:     {
                   11162: 	use integer;
                   11163: 	# strings need to be an even # of cahracters long, it it is odd the
                   11164:         # last characters gets thrown away
                   11165: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11166: 	my $symbseed=numval($symb) << 10;
                   11167: 	my $namechck=unpack("%32S*",$username.' ');
                   11168: 	
                   11169: 	my $nameseed=numval($username) << 21;
1.501     albertel 11170: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11171: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11172: 	
                   11173: 	my $num1=$symbchck+$symbseed+$namechck;
                   11174: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11175: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11176: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11177: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11178: 	return "$num1,$num2";
                   11179:     }
                   11180: }
                   11181: 
                   11182: sub rndseed_64bit3 {
                   11183:     my ($symb,$courseid,$domain,$username)=@_;
                   11184:     {
                   11185: 	use integer;
                   11186: 	# strings need to be an even # of cahracters long, it it is odd the
                   11187:         # last characters gets thrown away
                   11188: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11189: 	my $symbseed=numval2($symb) << 10;
                   11190: 	my $namechck=unpack("%32S*",$username.' ');
                   11191: 	
                   11192: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11193: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11194: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11195: 	
                   11196: 	my $num1=$symbchck+$symbseed+$namechck;
                   11197: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11198: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11199: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11200: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11201: 	
1.503     albertel 11202: 	return "$num1:$num2";
1.443     albertel 11203:     }
                   11204: }
                   11205: 
1.575     albertel 11206: sub rndseed_64bit4 {
                   11207:     my ($symb,$courseid,$domain,$username)=@_;
                   11208:     {
                   11209: 	use integer;
                   11210: 	# strings need to be an even # of cahracters long, it it is odd the
                   11211:         # last characters gets thrown away
                   11212: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11213: 	my $symbseed=numval3($symb) << 10;
                   11214: 	my $namechck=unpack("%32S*",$username.' ');
                   11215: 	
                   11216: 	my $nameseed=numval3($username) << 21;
                   11217: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11218: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11219: 	
                   11220: 	my $num1=$symbchck+$symbseed+$namechck;
                   11221: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11222: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11223: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11224: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11225: 	
1.575     albertel 11226: 	return "$num1:$num2";
                   11227:     }
                   11228: }
                   11229: 
1.675     albertel 11230: sub rndseed_64bit5 {
                   11231:     my ($symb,$courseid,$domain,$username)=@_;
                   11232:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11233:     return "$num1:$num2";
                   11234: }
                   11235: 
1.366     albertel 11236: sub rndseed_CODE_64bit {
                   11237:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11238:     {
1.366     albertel 11239: 	use integer;
1.443     albertel 11240: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11241: 	my $symbseed=numval2($symb);
1.491     albertel 11242: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11243: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11244: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11245: 	my $num1=$symbseed+$CODEchck;
                   11246: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11247: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11248: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11249: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11250: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11251: 	return "$num1:$num2";
1.366     albertel 11252:     }
                   11253: }
                   11254: 
1.575     albertel 11255: sub rndseed_CODE_64bit4 {
                   11256:     my ($symb,$courseid,$domain,$username)=@_;
                   11257:     {
                   11258: 	use integer;
                   11259: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11260: 	my $symbseed=numval3($symb);
                   11261: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11262: 	my $CODEseed=numval3(&getCODE());
                   11263: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11264: 	my $num1=$symbseed+$CODEchck;
                   11265: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11266: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11267: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11268: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11269: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11270: 	return "$num1:$num2";
                   11271:     }
                   11272: }
                   11273: 
1.675     albertel 11274: sub rndseed_CODE_64bit5 {
                   11275:     my ($symb,$courseid,$domain,$username)=@_;
                   11276:     my $code = &getCODE();
                   11277:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11278:     return "$num1:$num2";
                   11279: }
                   11280: 
1.366     albertel 11281: sub setup_random_from_rndseed {
                   11282:     my ($rndseed)=@_;
1.503     albertel 11283:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11284:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11285:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11286:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11287:         } else {
                   11288:             &Math::Random::random_set_seed($num1,$num2);
                   11289:         }
1.366     albertel 11290:     } else {
                   11291: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11292:     }
1.36      albertel 11293: }
                   11294: 
1.474     albertel 11295: sub latest_receipt_algorithm_id {
1.835     albertel 11296:     return 'receipt3';
1.474     albertel 11297: }
                   11298: 
1.480     www      11299: sub recunique {
                   11300:     my $fucourseid=shift;
                   11301:     my $unique;
1.835     albertel 11302:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11303: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11304: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11305:     } else {
                   11306: 	$unique=$perlvar{'lonReceipt'};
                   11307:     }
                   11308:     return unpack("%32C*",$unique);
                   11309: }
                   11310: 
                   11311: sub recprefix {
                   11312:     my $fucourseid=shift;
                   11313:     my $prefix;
1.835     albertel 11314:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11315: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11316: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11317:     } else {
                   11318: 	$prefix=$perlvar{'lonHostID'};
                   11319:     }
                   11320:     return unpack("%32C*",$prefix);
                   11321: }
                   11322: 
1.76      www      11323: sub ireceipt {
1.474     albertel 11324:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11325: 
                   11326:     my $return =&recprefix($fucourseid).'-';
                   11327: 
                   11328:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11329: 	$env{'request.state'} eq 'construct') {
                   11330: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11331: 	return $return;
                   11332:     }
                   11333: 
1.76      www      11334:     my $cuname=unpack("%32C*",$funame);
                   11335:     my $cudom=unpack("%32C*",$fudom);
                   11336:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11337:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11338:     my $cunique=&recunique($fucourseid);
1.474     albertel 11339:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11340:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11341: 
1.790     albertel 11342: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11343: 			       
                   11344: 	$return.= ($cunique%$cuname+
                   11345: 		   $cunique%$cudom+
                   11346: 		   $cusymb%$cuname+
                   11347: 		   $cusymb%$cudom+
                   11348: 		   $cucourseid%$cuname+
                   11349: 		   $cucourseid%$cudom+
                   11350: 		   $cpart%$cuname+
                   11351: 		   $cpart%$cudom);
                   11352:     } else {
                   11353: 	$return.= ($cunique%$cuname+
                   11354: 		   $cunique%$cudom+
                   11355: 		   $cusymb%$cuname+
                   11356: 		   $cusymb%$cudom+
                   11357: 		   $cucourseid%$cuname+
                   11358: 		   $cucourseid%$cudom);
                   11359:     }
                   11360:     return $return;
1.76      www      11361: }
                   11362: 
                   11363: sub receipt {
1.474     albertel 11364:     my ($part)=@_;
1.790     albertel 11365:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11366:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11367: }
1.260     ng       11368: 
1.790     albertel 11369: sub whichuser {
                   11370:     my ($passedsymb)=@_;
                   11371:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11372:     if (defined($env{'form.grade_symb'})) {
                   11373: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11374: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11375: 	if (!$allowed &&
                   11376: 	    exists($env{'request.course.sec'}) &&
                   11377: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11378: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11379: 			      '/'.$env{'request.course.sec'});
                   11380: 	}
                   11381: 	if ($allowed) {
                   11382: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11383: 	    $courseid=$tmp_courseid;
                   11384: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11385: 	    ($name)=&get_env_multiple('form.grade_username');
                   11386: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11387: 	}
                   11388:     }
                   11389:     if (!$passedsymb) {
                   11390: 	$symb=&symbread();
                   11391:     } else {
                   11392: 	$symb=$passedsymb;
                   11393:     }
                   11394:     $courseid=$env{'request.course.id'};
                   11395:     $domain=$env{'user.domain'};
                   11396:     $name=$env{'user.name'};
                   11397:     if ($name eq 'public' && $domain eq 'public') {
                   11398: 	if (!defined($env{'form.username'})) {
                   11399: 	    $env{'form.username'}.=time.rand(10000000);
                   11400: 	}
                   11401: 	$name.=$env{'form.username'};
                   11402:     }
                   11403:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11404: 
                   11405: }
                   11406: 
1.36      albertel 11407: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11408: # returns either the contents of the file or 
                   11409: # -1 if the file doesn't exist
1.481     raeburn  11410: #
                   11411: # if the target is a file that was uploaded via DOCS, 
                   11412: # a check will be made to see if a current copy exists on the local server,
                   11413: # if it does this will be served, otherwise a copy will be retrieved from
                   11414: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11415: # the local server.   
1.472     albertel 11416: 
1.36      albertel 11417: sub getfile {
1.538     albertel 11418:     my ($file) = @_;
1.609     banghart 11419:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11420:     &repcopy($file);
                   11421:     return &readfile($file);
                   11422: }
                   11423: 
                   11424: sub repcopy_userfile {
                   11425:     my ($file)=@_;
1.1142    raeburn  11426:     my $londocroot = $perlvar{'lonDocRoot'};
                   11427:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11428:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11429:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11430: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11431:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11432:     if (-e "$file") {
1.828     www      11433: # we already have a local copy, check it out
1.538     albertel 11434: 	my @fileinfo = stat($file);
1.828     www      11435: 	my $rtncode;
                   11436: 	my $info;
1.538     albertel 11437: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11438: 	if ($lwpresp ne 'ok') {
1.828     www      11439: # there is no such file anymore, even though we had a local copy
1.482     albertel 11440: 	    if ($rtncode eq '404') {
1.538     albertel 11441: 		unlink($file);
1.482     albertel 11442: 	    }
                   11443: 	    return -1;
                   11444: 	}
                   11445: 	if ($info < $fileinfo[9]) {
1.828     www      11446: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11447: 	    return 'ok';
1.828     www      11448: 	} else {
                   11449: # the file is outdated, get rid of it
                   11450: 	    unlink($file);
1.482     albertel 11451: 	}
1.828     www      11452:     }
                   11453: # one way or the other, at this point, we don't have the file
                   11454: # construct the correct path for the file
                   11455:     my @parts = ($cdom,$cnum); 
                   11456:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11457: 	push @parts, split(/\//,$1);
                   11458:     }
                   11459:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11460:     foreach my $part (@parts) {
                   11461: 	$path .= '/'.$part;
                   11462: 	if (!-e $path) {
                   11463: 	    mkdir($path,0770);
1.482     albertel 11464: 	}
                   11465:     }
1.828     www      11466: # now the path exists for sure
                   11467: # get a user agent
                   11468:     my $ua=new LWP::UserAgent;
                   11469:     my $transferfile=$file.'.in.transfer';
                   11470: # FIXME: this should flock
                   11471:     if (-e $transferfile) { return 'ok'; }
                   11472:     my $request;
                   11473:     $uri=~s/^\///;
1.980     raeburn  11474:     my $homeserver = &homeserver($cnum,$cdom);
                   11475:     my $protocol = $protocol{$homeserver};
                   11476:     $protocol = 'http' if ($protocol ne 'https');
                   11477:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11478:     my $response=$ua->request($request,$transferfile);
                   11479: # did it work?
                   11480:     if ($response->is_error()) {
                   11481: 	unlink($transferfile);
                   11482: 	&logthis("Userfile repcopy failed for $uri");
                   11483: 	return -1;
                   11484:     }
                   11485: # worked, rename the transfer file
                   11486:     rename($transferfile,$file);
1.607     raeburn  11487:     return 'ok';
1.481     raeburn  11488: }
                   11489: 
1.517     albertel 11490: sub tokenwrapper {
                   11491:     my $uri=shift;
1.980     raeburn  11492:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11493:     $uri=~s|^/||;
1.620     albertel 11494:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11495:     my $token=$1;
1.552     albertel 11496:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11497:     if ($udom && $uname && $file) {
                   11498: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11499:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11500:         my $homeserver = &homeserver($uname,$udom);
                   11501:         my $protocol = $protocol{$homeserver};
                   11502:         $protocol = 'http' if ($protocol ne 'https');
                   11503:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11504:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11505:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11506:     } else {
                   11507:         return '/adm/notfound.html';
                   11508:     }
                   11509: }
                   11510: 
1.828     www      11511: # call with reqtype HEAD: get last modification time
                   11512: # call with reqtype GET: get the file contents
                   11513: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11514: #
1.481     raeburn  11515: sub getuploaded {
                   11516:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11517:     $uri=~s/^\///;
1.980     raeburn  11518:     my $homeserver = &homeserver($cnum,$cdom);
                   11519:     my $protocol = $protocol{$homeserver};
                   11520:     $protocol = 'http' if ($protocol ne 'https');
                   11521:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11522:     my $ua=new LWP::UserAgent;
                   11523:     my $request=new HTTP::Request($reqtype,$uri);
                   11524:     my $response=$ua->request($request);
                   11525:     $$rtncode = $response->code;
1.482     albertel 11526:     if (! $response->is_success()) {
                   11527: 	return 'failed';
                   11528:     }      
                   11529:     if ($reqtype eq 'HEAD') {
1.486     www      11530: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11531:     } elsif ($reqtype eq 'GET') {
                   11532: 	$$info = $response->content;
1.472     albertel 11533:     }
1.482     albertel 11534:     return 'ok';
1.36      albertel 11535: }
                   11536: 
1.481     raeburn  11537: sub readfile {
                   11538:     my $file = shift;
                   11539:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11540:     my $fh;
                   11541:     open($fh,"<$file");
                   11542:     my $a='';
1.800     albertel 11543:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11544:     return $a;
                   11545: }
                   11546: 
1.36      albertel 11547: sub filelocation {
1.590     banghart 11548:     my ($dir,$file) = @_;
                   11549:     my $location;
                   11550:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11551: 
                   11552:     if ($file =~ m-^/adm/-) {
                   11553: 	$file=~s-^/adm/wrapper/-/-;
                   11554: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11555:     }
1.882     albertel 11556: 
1.1139    www      11557:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11558:         $location = $file;
1.609     banghart 11559:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11560:         my ($udom,$uname,$filename)=
1.811     albertel 11561:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11562:         my $home=&homeserver($uname,$udom);
                   11563:         my $is_me=0;
                   11564:         my @ids=&current_machine_ids();
                   11565:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11566:         if ($is_me) {
1.1117    foxr     11567:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11568:         } else {
                   11569:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11570:   	      $udom.'/'.$uname.'/'.$filename;
                   11571:         }
1.882     albertel 11572:     } elsif ($file =~ m-^/adm/-) {
                   11573: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11574:     } else {
                   11575:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11576:         $file=~s:^/(res|priv)/:/:;
                   11577:         my $space=$1;
1.590     banghart 11578:         if ( !( $file =~ m:^/:) ) {
                   11579:             $location = $dir. '/'.$file;
                   11580:         } else {
1.1142    raeburn  11581:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11582:         }
1.59      albertel 11583:     }
1.590     banghart 11584:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11585:     while ($location=~m{/\.\./}) {
                   11586: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11587: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11588: 	} else {
                   11589: 	    $location=~ s{/\.\./}{/}g;
                   11590: 	}
                   11591:     } #remove dir/..
1.590     banghart 11592:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11593:     return $location;
1.46      www      11594: }
1.36      albertel 11595: 
1.46      www      11596: sub hreflocation {
                   11597:     my ($dir,$file)=@_;
1.980     raeburn  11598:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11599: 	$file=filelocation($dir,$file);
1.700     albertel 11600:     } elsif ($file=~m-^/adm/-) {
                   11601: 	$file=~s-^/adm/wrapper/-/-;
                   11602: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11603:     }
                   11604:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11605: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11606:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11607: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11608: 	        {/uploaded/$1/$2/}x;
1.46      www      11609:     }
1.913     albertel 11610:     if ($file=~ m{^/userfiles/}) {
                   11611: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11612:     }
1.462     albertel 11613:     return $file;
1.465     albertel 11614: }
                   11615: 
1.1139    www      11616: 
                   11617: 
                   11618: 
                   11619: 
1.465     albertel 11620: sub current_machine_domains {
1.853     albertel 11621:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11622: }
                   11623: 
                   11624: sub machine_domains {
                   11625:     my ($hostname) = @_;
1.465     albertel 11626:     my @domains;
1.838     albertel 11627:     my %hostname = &all_hostnames();
1.465     albertel 11628:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11629: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11630: 	if ($hostname eq $name) {
1.844     albertel 11631: 	    push(@domains,&host_domain($id));
1.465     albertel 11632: 	}
                   11633:     }
                   11634:     return @domains;
                   11635: }
                   11636: 
                   11637: sub current_machine_ids {
1.853     albertel 11638:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11639: }
                   11640: 
                   11641: sub machine_ids {
                   11642:     my ($hostname) = @_;
                   11643:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11644:     my @ids;
1.888     albertel 11645:     my %name_to_host = &all_names();
1.889     albertel 11646:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11647: 	return @{ $name_to_host{$hostname} };
                   11648:     }
                   11649:     return;
1.31      www      11650: }
                   11651: 
1.824     raeburn  11652: sub additional_machine_domains {
                   11653:     my @domains;
                   11654:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11655:     while( my $line = <$fh>) {
                   11656:         $line =~ s/\s//g;
                   11657:         push(@domains,$line);
                   11658:     }
                   11659:     return @domains;
                   11660: }
                   11661: 
                   11662: sub default_login_domain {
                   11663:     my $domain = $perlvar{'lonDefDomain'};
                   11664:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11665:     foreach my $posdom (&current_machine_domains(),
                   11666:                         &additional_machine_domains()) {
                   11667:         if (lc($posdom) eq lc($testdomain)) {
                   11668:             $domain=$posdom;
                   11669:             last;
                   11670:         }
                   11671:     }
                   11672:     return $domain;
                   11673: }
                   11674: 
1.31      www      11675: # ------------------------------------------------------------- Declutters URLs
                   11676: 
                   11677: sub declutter {
                   11678:     my $thisfn=shift;
1.569     albertel 11679:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  11680:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   11681:         $thisfn=~s{^/home/httpd/html}{};
                   11682:     }
1.31      www      11683:     $thisfn=~s/^\///;
1.697     albertel 11684:     $thisfn=~s|^adm/wrapper/||;
                   11685:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11686:     $thisfn=~s/^res\///;
1.1172    bisitz   11687:     $thisfn=~s/^priv\///;
1.1032    raeburn  11688:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11689:         $thisfn=~s/\?.+$//;
                   11690:     }
1.268     www      11691:     return $thisfn;
                   11692: }
                   11693: 
                   11694: # ------------------------------------------------------------- Clutter up URLs
                   11695: 
                   11696: sub clutter {
                   11697:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11698:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11699: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11700:        $thisfn='/res'.$thisfn; 
                   11701:     }
1.1031    raeburn  11702:     if ($thisfn !~m|^/adm|) {
                   11703: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11704: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11705: 	} else {
                   11706: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11707: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11708: 	    if ($embstyle eq 'ssi'
                   11709: 		|| ($embstyle eq 'hdn')
                   11710: 		|| ($embstyle eq 'rat')
                   11711: 		|| ($embstyle eq 'prv')
                   11712: 		|| ($embstyle eq 'ign')) {
                   11713: 		#do nothing with these
                   11714: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11715: 		|| ($embstyle eq 'emb')
                   11716: 		|| ($embstyle eq 'wrp')) {
                   11717: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11718: 	    } elsif ($embstyle eq 'unk'
                   11719: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11720: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11721: 	    } else {
1.718     www      11722: #		&logthis("Got a blank emb style");
1.695     albertel 11723: 	    }
1.694     albertel 11724: 	}
                   11725:     }
1.31      www      11726:     return $thisfn;
1.12      www      11727: }
                   11728: 
1.787     albertel 11729: sub clutter_with_no_wrapper {
                   11730:     my $uri = &clutter(shift);
                   11731:     if ($uri =~ m-^/adm/-) {
                   11732: 	$uri =~ s-^/adm/wrapper/-/-;
                   11733: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11734:     }
                   11735:     return $uri;
                   11736: }
                   11737: 
1.557     albertel 11738: sub freeze_escape {
                   11739:     my ($value)=@_;
                   11740:     if (ref($value)) {
                   11741: 	$value=&nfreeze($value);
                   11742: 	return '__FROZEN__'.&escape($value);
                   11743:     }
                   11744:     return &escape($value);
                   11745: }
                   11746: 
1.11      www      11747: 
1.557     albertel 11748: sub thaw_unescape {
                   11749:     my ($value)=@_;
                   11750:     if ($value =~ /^__FROZEN__/) {
                   11751: 	substr($value,0,10,undef);
                   11752: 	$value=&unescape($value);
                   11753: 	return &thaw($value);
                   11754:     }
                   11755:     return &unescape($value);
                   11756: }
                   11757: 
1.436     albertel 11758: sub correct_line_ends {
                   11759:     my ($result)=@_;
                   11760:     $$result =~s/\r\n/\n/mg;
                   11761:     $$result =~s/\r/\n/mg;
1.415     albertel 11762: }
1.1       albertel 11763: # ================================================================ Main Program
                   11764: 
1.184     www      11765: sub goodbye {
1.204     albertel 11766:    &logthis("Starting Shut down");
1.443     albertel 11767: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11768:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11769: #converted
1.599     albertel 11770: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11771:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11772: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11773: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11774: #1.1 only
1.870     albertel 11775: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11776: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11777: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11778: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11779:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11780:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11781:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11782:    &flushcourselogs();
                   11783:    &logthis("Shutting down");
                   11784: }
                   11785: 
1.852     albertel 11786: sub get_dns {
1.1210    raeburn  11787:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11788:     if (!$ignore_cache) {
                   11789: 	my ($content,$cached)=
                   11790: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11791: 	if ($cached) {
1.1210    raeburn  11792: 	    &$func($content,$hashref);
1.869     albertel 11793: 	    return;
                   11794: 	}
                   11795:     }
                   11796: 
                   11797:     my %alldns;
1.852     albertel 11798:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11799:     foreach my $dns (<$config>) {
                   11800: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11801:         my $line = $1;
                   11802:         my ($host,$protocol) = split(/:/,$line);
                   11803:         if ($protocol ne 'https') {
                   11804:             $protocol = 'http';
                   11805:         }
                   11806: 	$alldns{$host} = $protocol;
1.869     albertel 11807:     }
                   11808:     while (%alldns) {
1.1263    raeburn  11809: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 11810: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11811:         $ua->timeout(30);
1.979     raeburn  11812: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11813: 	my $response=$ua->request($request);
1.979     raeburn  11814:         delete($alldns{$dns});
1.852     albertel 11815: 	next if ($response->is_error());
                   11816: 	my @content = split("\n",$response->content);
1.1210    raeburn  11817: 	unless ($nocache) {
1.1219    raeburn  11818: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  11819: 	}
                   11820: 	&$func(\@content,$hashref);
1.869     albertel 11821: 	return;
1.852     albertel 11822:     }
                   11823:     close($config);
1.871     albertel 11824:     my $which = (split('/',$url))[3];
                   11825:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11826:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11827:     my @content = <$config>;
1.1210    raeburn  11828:     &$func(\@content,$hashref);
                   11829:     return;
                   11830: }
                   11831: 
                   11832: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11833: sub parse_dns_checksums_tab {
1.1210    raeburn  11834:     my ($lines,$hashref) = @_;
1.1264  ! raeburn  11835:     my $lonhost = $perlvar{'lonHostID'};
        !          11836:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  11837:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264  ! raeburn  11838:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
        !          11839:     my $webconfdir = '/etc/httpd/conf';
        !          11840:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
        !          11841:         $webconfdir = '/etc/apache2';
        !          11842:     } elsif ($distro =~ /^sles(\d+)$/) {
        !          11843:         if ($1 >= 10) {
        !          11844:             $webconfdir = '/etc/apache2';
        !          11845:         }
        !          11846:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
        !          11847:         if ($1 >= 10.0) {
        !          11848:             $webconfdir = '/etc/apache2';
        !          11849:         }
        !          11850:     }
1.1210    raeburn  11851:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11852:     my (%chksum,%revnum);
                   11853:     if (ref($lines) eq 'ARRAY') {
                   11854:         chomp(@{$lines});
1.1238    raeburn  11855:         my $version = shift(@{$lines});
                   11856:         if ($version eq $release) {  
1.1210    raeburn  11857:             foreach my $line (@{$lines}) {
1.1238    raeburn  11858:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264  ! raeburn  11859:                 if ($file =~ m{^/etc/httpd/conf}) {
        !          11860:                     if ($webconfdir eq '/etc/apache2') {
        !          11861:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
        !          11862:                     }
        !          11863:                 }
1.1238    raeburn  11864:                 $chksum{$file} = $shasum;
                   11865:                 $revnum{$file} = $version;
1.1210    raeburn  11866:             }
                   11867:             if (ref($hashref) eq 'HASH') {
                   11868:                 %{$hashref} = (
                   11869:                                 sums     => \%chksum,
                   11870:                                 versions => \%revnum,
                   11871:                               );
                   11872:             }
                   11873:         }
                   11874:     }
1.869     albertel 11875:     return;
1.852     albertel 11876: }
1.1210    raeburn  11877: 
                   11878: sub fetch_dns_checksums {
1.1238    raeburn  11879:     my %checksums;
                   11880:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  11881:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  11882:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11883:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  11884:              \%checksums);
1.1210    raeburn  11885:     return \%checksums;
                   11886: }
                   11887: 
1.327     albertel 11888: # ------------------------------------------------------------ Read domain file
                   11889: {
1.852     albertel 11890:     my $loaded;
1.846     albertel 11891:     my %domain;
                   11892: 
1.852     albertel 11893:     sub parse_domain_tab {
                   11894: 	my ($lines) = @_;
                   11895: 	foreach my $line (@$lines) {
                   11896: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11897: 
1.846     albertel 11898: 	    chomp($line);
1.852     albertel 11899: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11900: 	    my %this_domain;
                   11901: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11902: 			       'lang_def', 'city', 'longi', 'lati',
                   11903: 			       'primary') {
                   11904: 		$this_domain{$field} = shift(@elements);
                   11905: 	    }
                   11906: 	    $domain{$name} = \%this_domain;
1.852     albertel 11907: 	}
                   11908:     }
1.864     albertel 11909: 
                   11910:     sub reset_domain_info {
                   11911: 	undef($loaded);
                   11912: 	undef(%domain);
                   11913:     }
                   11914: 
1.852     albertel 11915:     sub load_domain_tab {
1.869     albertel 11916: 	my ($ignore_cache) = @_;
                   11917: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11918: 	my $fh;
                   11919: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11920: 	    my @lines = <$fh>;
                   11921: 	    &parse_domain_tab(\@lines);
1.448     albertel 11922: 	}
1.852     albertel 11923: 	close($fh);
                   11924: 	$loaded = 1;
1.327     albertel 11925:     }
1.846     albertel 11926: 
                   11927:     sub domain {
1.852     albertel 11928: 	&load_domain_tab() if (!$loaded);
                   11929: 
1.846     albertel 11930: 	my ($name,$what) = @_;
                   11931: 	return if ( !exists($domain{$name}) );
                   11932: 
                   11933: 	if (!$what) {
                   11934: 	    return $domain{$name}{'description'};
                   11935: 	}
                   11936: 	return $domain{$name}{$what};
                   11937:     }
1.974     raeburn  11938: 
                   11939:     sub domain_info {
                   11940:         &load_domain_tab() if (!$loaded);
                   11941:         return %domain;
                   11942:     }
                   11943: 
1.327     albertel 11944: }
                   11945: 
                   11946: 
1.1       albertel 11947: # ------------------------------------------------------------- Read hosts file
                   11948: {
1.838     albertel 11949:     my %hostname;
1.844     albertel 11950:     my %hostdom;
1.845     albertel 11951:     my %libserv;
1.852     albertel 11952:     my $loaded;
1.888     albertel 11953:     my %name_to_host;
1.1074    raeburn  11954:     my %internetdom;
1.1107    raeburn  11955:     my %LC_dns_serv;
1.852     albertel 11956: 
                   11957:     sub parse_hosts_tab {
                   11958: 	my ($file) = @_;
                   11959: 	foreach my $configline (@$file) {
                   11960: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11961:             chomp($configline);
                   11962: 	    if ($configline =~ /^\^/) {
                   11963:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11964:                     $LC_dns_serv{$1} = 1;
                   11965:                 }
                   11966:                 next;
                   11967:             }
1.1074    raeburn  11968: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11969: 	    $name=~s/\s//g;
                   11970: 	    if ($id && $domain && $role && $name) {
                   11971: 		$hostname{$id}=$name;
1.888     albertel 11972: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11973: 		$hostdom{$id}=$domain;
                   11974: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11975:                 if (defined($protocol)) {
                   11976:                     if ($protocol eq 'https') {
                   11977:                         $protocol{$id} = $protocol;
                   11978:                     } else {
                   11979:                         $protocol{$id} = 'http'; 
                   11980:                     }
1.968     raeburn  11981:                 } else {
1.969     raeburn  11982:                     $protocol{$id} = 'http';
1.968     raeburn  11983:                 }
1.1074    raeburn  11984:                 if (defined($intdom)) {
                   11985:                     $internetdom{$id} = $intdom;
                   11986:                 }
1.852     albertel 11987: 	    }
                   11988: 	}
                   11989:     }
1.864     albertel 11990:     
                   11991:     sub reset_hosts_info {
1.897     albertel 11992: 	&purge_remembered();
1.864     albertel 11993: 	&reset_domain_info();
                   11994: 	&reset_hosts_ip_info();
1.892     albertel 11995: 	undef(%name_to_host);
1.864     albertel 11996: 	undef(%hostname);
                   11997: 	undef(%hostdom);
                   11998: 	undef(%libserv);
                   11999: 	undef($loaded);
                   12000:     }
1.1       albertel 12001: 
1.852     albertel 12002:     sub load_hosts_tab {
1.869     albertel 12003: 	my ($ignore_cache) = @_;
                   12004: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12005: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12006: 	my @config = <$config>;
                   12007: 	&parse_hosts_tab(\@config);
                   12008: 	close($config);
                   12009: 	$loaded=1;
1.1       albertel 12010:     }
1.852     albertel 12011: 
1.838     albertel 12012:     sub hostname {
1.852     albertel 12013: 	&load_hosts_tab() if (!$loaded);
                   12014: 
1.838     albertel 12015: 	my ($lonid) = @_;
                   12016: 	return $hostname{$lonid};
                   12017:     }
1.845     albertel 12018: 
1.838     albertel 12019:     sub all_hostnames {
1.852     albertel 12020: 	&load_hosts_tab() if (!$loaded);
                   12021: 
1.838     albertel 12022: 	return %hostname;
                   12023:     }
1.845     albertel 12024: 
1.888     albertel 12025:     sub all_names {
                   12026: 	&load_hosts_tab() if (!$loaded);
                   12027: 
                   12028: 	return %name_to_host;
                   12029:     }
                   12030: 
1.974     raeburn  12031:     sub all_host_domain {
                   12032:         &load_hosts_tab() if (!$loaded);
                   12033:         return %hostdom;
                   12034:     }
                   12035: 
1.845     albertel 12036:     sub is_library {
1.852     albertel 12037: 	&load_hosts_tab() if (!$loaded);
                   12038: 
1.845     albertel 12039: 	return exists($libserv{$_[0]});
                   12040:     }
                   12041: 
                   12042:     sub all_library {
1.852     albertel 12043: 	&load_hosts_tab() if (!$loaded);
                   12044: 
1.845     albertel 12045: 	return %libserv;
                   12046:     }
                   12047: 
1.1062    droeschl 12048:     sub unique_library {
                   12049: 	#2x reverse removes all hostnames that appear more than once
                   12050:         my %unique = reverse &all_library();
                   12051:         return reverse %unique;
                   12052:     }
                   12053: 
1.841     albertel 12054:     sub get_servers {
1.852     albertel 12055: 	&load_hosts_tab() if (!$loaded);
                   12056: 
1.841     albertel 12057: 	my ($domain,$type) = @_;
                   12058: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12059: 	                                          : %hostname;
                   12060: 	my %result;
1.842     albertel 12061: 	if (ref($domain) eq 'ARRAY') {
                   12062: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12063: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12064: 		    $result{$host} = $hostname;
                   12065: 		}
                   12066: 	    }
                   12067: 	} else {
                   12068: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12069: 		if ($hostdom{$host} eq $domain) {
                   12070: 		    $result{$host} = $hostname;
                   12071: 		}
1.841     albertel 12072: 	    }
                   12073: 	}
                   12074: 	return %result;
                   12075:     }
1.845     albertel 12076: 
1.1062    droeschl 12077:     sub get_unique_servers {
                   12078:         my %unique = reverse &get_servers(@_);
                   12079: 	return reverse %unique;
                   12080:     }
                   12081: 
1.844     albertel 12082:     sub host_domain {
1.852     albertel 12083: 	&load_hosts_tab() if (!$loaded);
                   12084: 
1.844     albertel 12085: 	my ($lonid) = @_;
                   12086: 	return $hostdom{$lonid};
                   12087:     }
                   12088: 
1.841     albertel 12089:     sub all_domains {
1.852     albertel 12090: 	&load_hosts_tab() if (!$loaded);
                   12091: 
1.841     albertel 12092: 	my %seen;
                   12093: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12094: 	return @uniq;
                   12095:     }
1.1074    raeburn  12096: 
                   12097:     sub internet_dom {
                   12098:         &load_hosts_tab() if (!$loaded);
                   12099: 
                   12100:         my ($lonid) = @_;
                   12101:         return $internetdom{$lonid};
                   12102:     }
1.1107    raeburn  12103: 
                   12104:     sub is_LC_dns {
                   12105:         &load_hosts_tab() if (!$loaded);
                   12106: 
                   12107:         my ($hostname) = @_;
                   12108:         return exists($LC_dns_serv{$hostname});
                   12109:     }
                   12110: 
1.1       albertel 12111: }
                   12112: 
1.847     albertel 12113: { 
                   12114:     my %iphost;
1.856     albertel 12115:     my %name_to_ip;
                   12116:     my %lonid_to_ip;
1.869     albertel 12117: 
1.847     albertel 12118:     sub get_hosts_from_ip {
                   12119: 	my ($ip) = @_;
                   12120: 	my %iphosts = &get_iphost();
                   12121: 	if (ref($iphosts{$ip})) {
                   12122: 	    return @{$iphosts{$ip}};
                   12123: 	}
                   12124: 	return;
1.839     albertel 12125:     }
1.864     albertel 12126:     
                   12127:     sub reset_hosts_ip_info {
                   12128: 	undef(%iphost);
                   12129: 	undef(%name_to_ip);
                   12130: 	undef(%lonid_to_ip);
                   12131:     }
1.856     albertel 12132: 
                   12133:     sub get_host_ip {
                   12134: 	my ($lonid) = @_;
                   12135: 	if (exists($lonid_to_ip{$lonid})) {
                   12136: 	    return $lonid_to_ip{$lonid};
                   12137: 	}
                   12138: 	my $name=&hostname($lonid);
                   12139:    	my $ip = gethostbyname($name);
                   12140: 	return if (!$ip || length($ip) ne 4);
                   12141: 	$ip=inet_ntoa($ip);
                   12142: 	$name_to_ip{$name}   = $ip;
                   12143: 	$lonid_to_ip{$lonid} = $ip;
                   12144: 	return $ip;
                   12145:     }
1.847     albertel 12146:     
                   12147:     sub get_iphost {
1.869     albertel 12148: 	my ($ignore_cache) = @_;
1.894     albertel 12149: 
1.869     albertel 12150: 	if (!$ignore_cache) {
                   12151: 	    if (%iphost) {
                   12152: 		return %iphost;
                   12153: 	    }
                   12154: 	    my ($ip_info,$cached)=
                   12155: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12156: 	    if ($cached) {
                   12157: 		%iphost      = %{$ip_info->[0]};
                   12158: 		%name_to_ip  = %{$ip_info->[1]};
                   12159: 		%lonid_to_ip = %{$ip_info->[2]};
                   12160: 		return %iphost;
                   12161: 	    }
                   12162: 	}
1.894     albertel 12163: 
                   12164: 	# get yesterday's info for fallback
                   12165: 	my %old_name_to_ip;
                   12166: 	my ($ip_info,$cached)=
                   12167: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12168: 	if ($cached) {
                   12169: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12170: 	}
                   12171: 
1.888     albertel 12172: 	my %name_to_host = &all_names();
                   12173: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12174: 	    my $ip;
                   12175: 	    if (!exists($name_to_ip{$name})) {
                   12176: 		$ip = gethostbyname($name);
                   12177: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12178: 		    if (defined($old_name_to_ip{$name})) {
                   12179: 			$ip = $old_name_to_ip{$name};
                   12180: 			&logthis("Can't find $name defaulting to old $ip");
                   12181: 		    } else {
                   12182: 			&logthis("Name $name no IP found");
                   12183: 			next;
                   12184: 		    }
                   12185: 		} else {
                   12186: 		    $ip=inet_ntoa($ip);
1.847     albertel 12187: 		}
                   12188: 		$name_to_ip{$name} = $ip;
                   12189: 	    } else {
                   12190: 		$ip = $name_to_ip{$name};
1.653     albertel 12191: 	    }
1.888     albertel 12192: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12193: 		$lonid_to_ip{$id} = $ip;
                   12194: 	    }
                   12195: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12196: 	}
1.1219    raeburn  12197: 	&do_cache_new('iphost','iphost',
                   12198: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12199: 		      48*60*60);
1.869     albertel 12200: 
1.847     albertel 12201: 	return %iphost;
1.598     albertel 12202:     }
                   12203: 
1.992     raeburn  12204:     #
                   12205:     #  Given a DNS returns the loncapa host name for that DNS 
                   12206:     # 
                   12207:     sub host_from_dns {
                   12208:         my ($dns) = @_;
                   12209:         my @hosts;
                   12210:         my $ip;
                   12211: 
1.993     raeburn  12212:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12213:             $ip = $name_to_ip{$dns};
                   12214:         }
                   12215:         if (!$ip) {
                   12216:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12217:             if (length($ip) == 4) { 
                   12218: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12219:             }
                   12220:         }
                   12221:         if ($ip) {
                   12222: 	    @hosts = get_hosts_from_ip($ip);
                   12223: 	    return $hosts[0];
                   12224:         }
                   12225:         return undef;
1.986     foxr     12226:     }
1.992     raeburn  12227: 
1.1074    raeburn  12228:     sub get_internet_names {
                   12229:         my ($lonid) = @_;
                   12230:         return if ($lonid eq '');
                   12231:         my ($idnref,$cached)=
                   12232:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12233:         if ($cached) {
                   12234:             return $idnref;
                   12235:         }
                   12236:         my $ip = &get_host_ip($lonid);
                   12237:         my @hosts = &get_hosts_from_ip($ip);
                   12238:         my %iphost = &get_iphost();
                   12239:         my (@idns,%seen);
                   12240:         foreach my $id (@hosts) {
                   12241:             my $dom = &host_domain($id);
                   12242:             my $prim_id = &domain($dom,'primary');
                   12243:             my $prim_ip = &get_host_ip($prim_id);
                   12244:             next if ($seen{$prim_ip});
                   12245:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12246:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12247:                     my $intdom = &internet_dom($id);
                   12248:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12249:                         push(@idns,$intdom);
                   12250:                     }
                   12251:                 }
                   12252:             }
                   12253:             $seen{$prim_ip} = 1;
                   12254:         }
1.1219    raeburn  12255:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12256:     }
                   12257: 
1.986     foxr     12258: }
                   12259: 
1.1079    raeburn  12260: sub all_loncaparevs {
1.1249    raeburn  12261:     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 2.11);
1.1079    raeburn  12262: }
                   12263: 
1.1227    raeburn  12264: # ---------------------------------------------------------- Read loncaparev table
                   12265: {
                   12266:     sub load_loncaparevs { 
                   12267:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12268:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12269:                 while (my $configline=<$config>) {
                   12270:                     chomp($configline);
                   12271:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12272:                     $loncaparevs{$hostid}=$loncaparev;
                   12273:                 }
                   12274:                 close($config);
                   12275:             }
                   12276:         }
                   12277:     }
                   12278: }
                   12279: 
                   12280: # ---------------------------------------------------------- Read serverhostID table
                   12281: {
                   12282:     sub load_serverhomeIDs {
                   12283:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12284:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12285:                 while (my $configline=<$config>) {
                   12286:                     chomp($configline);
                   12287:                     my ($name,$id)=split(/:/,$configline);
                   12288:                     $serverhomeIDs{$name}=$id;
                   12289:                 }
                   12290:                 close($config);
                   12291:             }
                   12292:         }
                   12293:     }
                   12294: }
                   12295: 
                   12296: 
1.862     albertel 12297: BEGIN {
                   12298: 
                   12299: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12300:     unless ($readit) {
                   12301: {
                   12302:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12303:     %perlvar = (%perlvar,%{$configvars});
                   12304: }
                   12305: 
                   12306: 
1.1       albertel 12307: # ------------------------------------------------------ Read spare server file
                   12308: {
1.448     albertel 12309:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12310: 
                   12311:     while (my $configline=<$config>) {
                   12312:        chomp($configline);
1.284     matthew  12313:        if ($configline) {
1.784     albertel 12314: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12315: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12316: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12317:        }
                   12318:     }
1.448     albertel 12319:     close($config);
1.1       albertel 12320: }
1.11      www      12321: # ------------------------------------------------------------ Read permissions
                   12322: {
1.448     albertel 12323:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12324: 
                   12325:     while (my $configline=<$config>) {
1.448     albertel 12326: 	chomp($configline);
                   12327: 	if ($configline) {
                   12328: 	    my ($role,$perm)=split(/ /,$configline);
                   12329: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12330: 	}
1.11      www      12331:     }
1.448     albertel 12332:     close($config);
1.11      www      12333: }
                   12334: 
                   12335: # -------------------------------------------- Read plain texts for permissions
                   12336: {
1.448     albertel 12337:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12338: 
                   12339:     while (my $configline=<$config>) {
1.448     albertel 12340: 	chomp($configline);
                   12341: 	if ($configline) {
1.742     raeburn  12342: 	    my ($short,@plain)=split(/:/,$configline);
                   12343:             %{$prp{$short}} = ();
                   12344: 	    if (@plain > 0) {
                   12345:                 $prp{$short}{'std'} = $plain[0];
                   12346:                 for (my $i=1; $i<@plain; $i++) {
                   12347:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12348:                 }
                   12349:             }
1.448     albertel 12350: 	}
1.135     www      12351:     }
1.448     albertel 12352:     close($config);
1.135     www      12353: }
                   12354: 
                   12355: # ---------------------------------------------------------- Read package table
                   12356: {
1.448     albertel 12357:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12358: 
                   12359:     while (my $configline=<$config>) {
1.483     albertel 12360: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12361: 	chomp($configline);
                   12362: 	my ($short,$plain)=split(/:/,$configline);
                   12363: 	my ($pack,$name)=split(/\&/,$short);
                   12364: 	if ($plain ne '') {
                   12365: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12366: 	    $packagetab{$short}=$plain; 
                   12367: 	}
1.11      www      12368:     }
1.448     albertel 12369:     close($config);
1.329     matthew  12370: }
                   12371: 
1.1073    raeburn  12372: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12373: 
                   12374: &load_loncaparevs();
1.1073    raeburn  12375: 
1.1074    raeburn  12376: # ---------------------------------------------------------- Read serverhostID table
                   12377: 
1.1227    raeburn  12378: &load_serverhomeIDs();
                   12379: 
                   12380: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12381: {
                   12382:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12383:     if (-e $file) {
                   12384:         my $parser = HTML::LCParser->new($file);
                   12385:         while (my $token = $parser->get_token()) {
                   12386:             if ($token->[0] eq 'S') {
                   12387:                 my $item = $token->[1];
                   12388:                 my $name = $token->[2]{'name'};
                   12389:                 my $value = $token->[2]{'value'};
                   12390:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12391:                     my $release = $parser->get_text();
                   12392:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12393:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12394:                 }
                   12395:             }
                   12396:         }
                   12397:     }
1.1073    raeburn  12398: }
                   12399: 
1.1138    raeburn  12400: # ---------------------------------------------------------- Read managers table
                   12401: {
                   12402:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12403:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12404:             while (my $configline=<$config>) {
                   12405:                 chomp($configline);
                   12406:                 next if ($configline =~ /^\#/);
                   12407:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12408:                     $managerstab{$configline} = 1;
                   12409:                 }
                   12410:             }
                   12411:             close($config);
                   12412:         }
                   12413:     }
                   12414: }
                   12415: 
1.329     matthew  12416: # ------------- set up temporary directory
                   12417: {
1.1117    foxr     12418:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12419: 
1.11      www      12420: }
                   12421: 
1.794     albertel 12422: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12423: 				'compress_threshold'=> 20_000,
                   12424:  			        });
1.185     www      12425: 
1.281     www      12426: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12427: $dumpcount=0;
1.958     www      12428: $locknum=0;
1.22      www      12429: 
1.163     harris41 12430: &logtouch();
1.672     albertel 12431: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12432: $readit=1;
1.564     albertel 12433:     {
                   12434: 	use integer;
                   12435: 	my $test=(2**32)+1;
1.568     albertel 12436: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12437: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12438:     }
1.195     www      12439: }
1.1       albertel 12440: }
1.179     www      12441: 
1.1       albertel 12442: 1;
1.191     harris41 12443: __END__
                   12444: 
1.243     albertel 12445: =pod
                   12446: 
1.191     harris41 12447: =head1 NAME
                   12448: 
1.243     albertel 12449: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12450: 
                   12451: =head1 SYNOPSIS
                   12452: 
1.243     albertel 12453: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12454: 
                   12455:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12456: 
1.243     albertel 12457: Common parameters:
                   12458: 
                   12459: =over 4
                   12460: 
                   12461: =item *
                   12462: 
                   12463: $uname : an internal username (if $cname expecting a course Id specifically)
                   12464: 
                   12465: =item *
                   12466: 
                   12467: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12468: 
                   12469: =item *
                   12470: 
                   12471: $symb : a resource instance identifier
                   12472: 
                   12473: =item *
                   12474: 
                   12475: $namespace : the name of a .db file that contains the data needed or
                   12476: being set.
                   12477: 
                   12478: =back
                   12479: 
1.394     bowersj2 12480: =head1 OVERVIEW
1.191     harris41 12481: 
1.394     bowersj2 12482: lonnet provides subroutines which interact with the
                   12483: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12484: about classes, users, and resources.
1.243     albertel 12485: 
                   12486: For many of these objects you can also use this to store data about
                   12487: them or modify them in various ways.
1.191     harris41 12488: 
1.394     bowersj2 12489: =head2 Symbs
1.191     harris41 12490: 
1.394     bowersj2 12491: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12492: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12493: map, the resource number of the resource in the map, and the URL of
                   12494: the resource itself. The latter is somewhat redundant, but might help
                   12495: if maps change.
                   12496: 
                   12497: An example is
                   12498: 
                   12499:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12500: 
                   12501: The respective map entry is
                   12502: 
                   12503:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12504:   title="Problem 2">
                   12505:  </resource>
                   12506: 
                   12507: Symbs are used by the random number generator, as well as to store and
                   12508: restore data specific to a certain instance of for example a problem.
                   12509: 
                   12510: =head2 Storing And Retrieving Data
                   12511: 
                   12512: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12513: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12514: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12515: is is the non-critical message twin of cstore. These functions are for
                   12516: handlers to store a perl hash to a user's permanent data space in an
                   12517: easy manner, and to retrieve it again on another call. It is expected
                   12518: that a handler would use this once at the beginning to retrieve data,
                   12519: and then again once at the end to send only the new data back.
                   12520: 
                   12521: The data is stored in the user's data directory on the user's
                   12522: homeserver under the ID of the course.
                   12523: 
                   12524: The hash that is returned by restore will have all of the previous
                   12525: value for all of the elements of the hash.
                   12526: 
                   12527: Example:
                   12528: 
                   12529:  #creating a hash
                   12530:  my %hash;
                   12531:  $hash{'foo'}='bar';
                   12532: 
                   12533:  #storing it
                   12534:  &Apache::lonnet::cstore(\%hash);
                   12535: 
                   12536:  #changing a value
                   12537:  $hash{'foo'}='notbar';
                   12538: 
                   12539:  #adding a new value
                   12540:  $hash{'bar'}='foo';
                   12541:  &Apache::lonnet::cstore(\%hash);
                   12542: 
                   12543:  #retrieving the hash
                   12544:  my %history=&Apache::lonnet::restore();
                   12545: 
                   12546:  #print the hash
                   12547:  foreach my $key (sort(keys(%history))) {
                   12548:    print("\%history{$key} = $history{$key}");
                   12549:  }
                   12550: 
                   12551: Will print out:
1.191     harris41 12552: 
1.394     bowersj2 12553:  %history{1:foo} = bar
                   12554:  %history{1:keys} = foo:timestamp
                   12555:  %history{1:timestamp} = 990455579
                   12556:  %history{2:bar} = foo
                   12557:  %history{2:foo} = notbar
                   12558:  %history{2:keys} = foo:bar:timestamp
                   12559:  %history{2:timestamp} = 990455580
                   12560:  %history{bar} = foo
                   12561:  %history{foo} = notbar
                   12562:  %history{timestamp} = 990455580
                   12563:  %history{version} = 2
                   12564: 
                   12565: Note that the special hash entries C<keys>, C<version> and
                   12566: C<timestamp> were added to the hash. C<version> will be equal to the
                   12567: total number of versions of the data that have been stored. The
                   12568: C<timestamp> attribute will be the UNIX time the hash was
                   12569: stored. C<keys> is available in every historical section to list which
                   12570: keys were added or changed at a specific historical revision of a
                   12571: hash.
                   12572: 
                   12573: B<Warning>: do not store the hash that restore returns directly. This
                   12574: will cause a mess since it will restore the historical keys as if the
                   12575: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12576: 
1.394     bowersj2 12577: Calling convention:
1.191     harris41 12578: 
1.1225    raeburn  12579:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12580:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12581: 
1.394     bowersj2 12582: For more detailed information, see lonnet specific documentation.
1.191     harris41 12583: 
1.394     bowersj2 12584: =head1 RETURN MESSAGES
1.191     harris41 12585: 
1.394     bowersj2 12586: =over 4
1.191     harris41 12587: 
1.394     bowersj2 12588: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12589: 
1.394     bowersj2 12590: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12591: when the connection is brought back up
1.191     harris41 12592: 
1.394     bowersj2 12593: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12594: for later delivery
1.191     harris41 12595: 
1.967     bisitz   12596: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12597: 
1.394     bowersj2 12598: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12599: that was requested
1.191     harris41 12600: 
1.243     albertel 12601: =back
1.191     harris41 12602: 
1.243     albertel 12603: =head1 PUBLIC SUBROUTINES
1.191     harris41 12604: 
1.243     albertel 12605: =head2 Session Environment Functions
1.191     harris41 12606: 
1.243     albertel 12607: =over 4
1.191     harris41 12608: 
1.394     bowersj2 12609: =item * 
                   12610: X<appenv()>
1.949     raeburn  12611: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12612: the user envirnoment file, and will be restored for each access this
1.620     albertel 12613: user makes during this session, also modifies the %env for the current
1.949     raeburn  12614: process. Optional rolesarrayref - if defined contains a reference to an array
                   12615: of roles which are exempt from the restriction on modifying user.role entries 
                   12616: in the user's environment.db and in %env.    
1.191     harris41 12617: 
                   12618: =item *
1.394     bowersj2 12619: X<delenv()>
1.987     raeburn  12620: B<delenv($delthis,$regexp)>: removes all items from the session
                   12621: environment file that begin with $delthis. If the 
                   12622: optional second arg - $regexp - is true, $delthis is treated as a 
                   12623: regular expression, otherwise \Q$delthis\E is used. 
                   12624: The values are also deleted from the current processes %env.
1.191     harris41 12625: 
1.795     albertel 12626: =item * get_env_multiple($name) 
                   12627: 
                   12628: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12629: values may be defined and end up as an array ref.
                   12630: 
                   12631: returns an array of values
                   12632: 
1.243     albertel 12633: =back
                   12634: 
                   12635: =head2 User Information
1.191     harris41 12636: 
1.243     albertel 12637: =over 4
1.191     harris41 12638: 
                   12639: =item *
1.394     bowersj2 12640: X<queryauthenticate()>
                   12641: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12642: authentication scheme
                   12643: 
                   12644: =item *
1.394     bowersj2 12645: X<authenticate()>
1.1073    raeburn  12646: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12647: authenticate user from domain's lib servers (first use the current
                   12648: one). C<$upass> should be the users password.
1.1073    raeburn  12649: $checkdefauth is optional (value is 1 if a check should be made to
                   12650:    authenticate user using default authentication method, and allow
                   12651:    account creation if username does not have account in the domain).
                   12652: $clientcancheckhost is optional (value is 1 if checking whether the
                   12653:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12654: 
                   12655: =item *
1.394     bowersj2 12656: X<homeserver()>
                   12657: B<homeserver($uname,$udom)>: find the server which has
                   12658: the user's directory and files (there must be only one), this caches
                   12659: the answer, and also caches if there is a borken connection.
1.191     harris41 12660: 
                   12661: =item *
1.394     bowersj2 12662: X<idget()>
                   12663: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12664: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12665: username, and only 1 username per ID in a specific domain) (returns
                   12666: hash: id=>name,id=>name)
1.191     harris41 12667: 
                   12668: =item *
1.394     bowersj2 12669: X<idrget()>
                   12670: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12671: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12672: 
                   12673: =item *
1.394     bowersj2 12674: X<idput()>
                   12675: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12676: 
                   12677: =item *
1.394     bowersj2 12678: X<rolesinit()>
1.1169    droeschl 12679: B<rolesinit($udom,$username)>: get user privileges.
                   12680: returns user role, first access and timer interval hashes
1.243     albertel 12681: 
                   12682: =item *
1.1171    droeschl 12683: X<privileged()>
                   12684: B<privileged($username,$domain)>: returns a true if user has a
                   12685: privileged and active role (i.e. su or dc), false otherwise.
                   12686: 
                   12687: =item *
1.551     albertel 12688: X<getsection()>
                   12689: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12690: course $cname, return section name/number or '' for "not in course"
                   12691: and '-1' for "no section"
                   12692: 
                   12693: =item *
1.394     bowersj2 12694: X<userenvironment()>
                   12695: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12696: passed in @what from the requested user's environment, returns a hash
                   12697: 
1.858     raeburn  12698: =item * 
                   12699: X<userlog_query()>
1.859     albertel 12700: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12701: activity.log file. %filters defines filters applied when parsing the
                   12702: log file. These can be start or end timestamps, or the type of action
                   12703: - log to look for Login or Logout events, check for Checkin or
                   12704: Checkout, role for role selection. The response is in the form
                   12705: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12706: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12707: 
1.243     albertel 12708: =back
                   12709: 
                   12710: =head2 User Roles
                   12711: 
                   12712: =over 4
                   12713: 
                   12714: =item *
                   12715: 
1.810     raeburn  12716: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12717:  F: full access
                   12718:  U,I,K: authentication modes (cxx only)
                   12719:  '': forbidden
                   12720:  1: user needs to choose course
                   12721:  2: browse allowed
1.766     albertel 12722:  A: passphrase authentication needed
1.243     albertel 12723: 
                   12724: =item *
                   12725: 
1.1192    raeburn  12726: constructaccess($url,$setpriv) : check for access to construction space URL
                   12727: 
                   12728: See if the owner domain and name in the URL match those in the
                   12729: expected environment.  If so, return three element list
                   12730: ($ownername,$ownerdomain,$ownerhome).
                   12731: 
                   12732: Otherwise return the null string.
                   12733: 
                   12734: If second argument 'setpriv' is true, it assigns the privileges,
                   12735: and returns the same three element list, unless the owner has
                   12736: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12737: in which case the null string is returned.
                   12738: 
                   12739: =item *
                   12740: 
1.243     albertel 12741: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12742: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12743: and course level
                   12744: 
                   12745: =item *
                   12746: 
1.988     raeburn  12747: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12748: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12749: $type is Course (default) or Community.
1.988     raeburn  12750: If $forcedefault evaluates to true, text returned will be default 
                   12751: text for $type. Otherwise, if this is a course, the text returned 
                   12752: will be a custom name for the role (if defined in the course's 
                   12753: environment).  If no custom name is defined the default is returned.
                   12754:    
1.832     raeburn  12755: =item *
                   12756: 
1.1219    raeburn  12757: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12758: All arguments are optional. Returns a hash of a roles, either for
                   12759: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12760: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12761: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12762: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12763: For each key, value is set to colon-separated start and end times for
                   12764: the role.  If no username and domain are specified, will default to
1.934     raeburn  12765: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12766: of role statuses (active, future or previous), roles 
                   12767: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12768: to restrict the list of roles reported. If no array ref is 
                   12769: provided for types, will default to return only active roles.
1.834     albertel 12770: 
1.1195    raeburn  12771: =item *
                   12772: 
                   12773: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12774: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12775: 
                   12776: Additional optional arguments are: $type (if role checking is to be restricted 
                   12777: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12778: available roles) or future (roles available in the future), and
                   12779: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  12780: have active Domain Coordinator role in course's domain or in additional
                   12781: domains (specified in 'Domains to check for privileged users' in course
                   12782: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12783: 
                   12784: =item *
                   12785: 
                   12786: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12787: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12788: $possdomains and $possroles are optional array refs -- to domains to check and
                   12789: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12790: users' roles.db to check for a dc or su role in any domain. This can be
                   12791: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12792: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12793: this then allows &privileged_by_domain() to be used, which caches the identity
                   12794: of privileged users, eliminating the need for repeated calls to &dump().
                   12795: 
                   12796: =item *
                   12797: 
                   12798: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12799: where the outer hash keys are domains specified in the $possdomains array ref,
                   12800: next inner hash keys are privileged roles specified in the $roles array ref,
                   12801: and the innermost hash contains key = value pairs for username:domain = end:start
                   12802: for active or future "privileged" users with that role in that domain. To avoid
                   12803: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12804: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  12805: 
1.243     albertel 12806: =back
                   12807: 
                   12808: =head2 User Modification
                   12809: 
                   12810: =over 4
                   12811: 
                   12812: =item *
                   12813: 
1.957     raeburn  12814: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12815: user for the level given by URL.  Optional start and end dates (leave empty
                   12816: string or zero for "no date")
1.191     harris41 12817: 
                   12818: =item *
                   12819: 
1.243     albertel 12820: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12821: change a users, password, possible return values are: ok,
                   12822: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12823: refused
1.191     harris41 12824: 
                   12825: =item *
                   12826: 
1.243     albertel 12827: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12828: 
                   12829: =item *
                   12830: 
1.1058    raeburn  12831: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12832:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12833: 
                   12834: will update user information (firstname,middlename,lastname,generation,
                   12835: permanentemail), and if forceid is true, student/employee ID also.
                   12836: A user's institutional affiliation(s) can also be updated.
                   12837: User information fields will not be overwritten with empty entries 
                   12838: unless the field is included in the $candelete array reference.
                   12839: This array is included when a single user is modified via "Manage Users",
                   12840: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12841: 
                   12842: =item *
                   12843: 
1.286     matthew  12844: modifystudent
                   12845: 
1.957     raeburn  12846: modify a student's enrollment and identification information.
1.1235    raeburn  12847: The course id is resolved based on the current user's environment.  
                   12848: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12849: associated with a course.
                   12850: 
1.297     matthew  12851: This call is essentially a wrapper for lonnet::modifyuser and
                   12852: lonnet::modify_student_enrollment
1.286     matthew  12853: 
                   12854: Inputs: 
                   12855: 
                   12856: =over 4
                   12857: 
1.957     raeburn  12858: =item B<$udom> Student's loncapa domain
1.286     matthew  12859: 
1.957     raeburn  12860: =item B<$uname> Student's loncapa login name
1.286     matthew  12861: 
1.964     bisitz   12862: =item B<$uid> Student/Employee ID
1.286     matthew  12863: 
1.957     raeburn  12864: =item B<$umode> Student's authentication mode
1.286     matthew  12865: 
1.957     raeburn  12866: =item B<$upass> Student's password
1.286     matthew  12867: 
1.957     raeburn  12868: =item B<$first> Student's first name
1.286     matthew  12869: 
1.957     raeburn  12870: =item B<$middle> Student's middle name
1.286     matthew  12871: 
1.957     raeburn  12872: =item B<$last> Student's last name
1.286     matthew  12873: 
1.957     raeburn  12874: =item B<$gene> Student's generation
1.286     matthew  12875: 
1.957     raeburn  12876: =item B<$usec> Student's section in course
1.286     matthew  12877: 
                   12878: =item B<$end> Unix time of the roles expiration
                   12879: 
                   12880: =item B<$start> Unix time of the roles start date
                   12881: 
                   12882: =item B<$forceid> If defined, allow $uid to be changed
                   12883: 
                   12884: =item B<$desiredhome> server to use as home server for student
                   12885: 
1.957     raeburn  12886: =item B<$email> Student's permanent e-mail address
                   12887: 
                   12888: =item B<$type> Type of enrollment (auto or manual)
                   12889: 
1.963     raeburn  12890: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12891: 
                   12892: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12893: 
1.963     raeburn  12894: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12895: 
1.963     raeburn  12896: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12897: 
1.1216    raeburn  12898: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12899: 
                   12900: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  12901: 
1.286     matthew  12902: =back
1.297     matthew  12903: 
                   12904: =item *
                   12905: 
                   12906: modify_student_enrollment
                   12907: 
1.1235    raeburn  12908: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12909: 'role.request.course' must be defined for this function to proceed.
                   12910: 
                   12911: Inputs:
                   12912: 
                   12913: =over 4
                   12914: 
1.1235    raeburn  12915: =item $udom, student's domain
1.297     matthew  12916: 
1.1235    raeburn  12917: =item $uname, student's name
1.297     matthew  12918: 
1.1235    raeburn  12919: =item $uid, student's user id
1.297     matthew  12920: 
1.1235    raeburn  12921: =item $first, student's first name
1.297     matthew  12922: 
                   12923: =item $middle
                   12924: 
                   12925: =item $last
                   12926: 
                   12927: =item $gene
                   12928: 
                   12929: =item $usec
                   12930: 
                   12931: =item $end
                   12932: 
                   12933: =item $start
                   12934: 
1.957     raeburn  12935: =item $type
                   12936: 
                   12937: =item $locktype
                   12938: 
                   12939: =item $cid
                   12940: 
                   12941: =item $selfenroll
                   12942: 
                   12943: =item $context
                   12944: 
1.1216    raeburn  12945: =item $credits, number of credits student will earn from this class
                   12946: 
1.297     matthew  12947: =back
                   12948: 
1.191     harris41 12949: 
                   12950: =item *
                   12951: 
1.243     albertel 12952: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12953: custom role; give a custom role to a user for the level given by URL.  Specify
                   12954: name and domain of role author, and role name
1.191     harris41 12955: 
                   12956: =item *
                   12957: 
1.243     albertel 12958: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12959: 
                   12960: =item *
                   12961: 
1.243     albertel 12962: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12963: 
                   12964: =back
                   12965: 
                   12966: =head2 Course Infomation
                   12967: 
                   12968: =over 4
1.191     harris41 12969: 
                   12970: =item *
                   12971: 
1.1118    foxr     12972: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12973: specified course id, including all environment settings for the
                   12974: course, the description of the course will be in the hash under the
                   12975: key 'description'
1.191     harris41 12976: 
1.1118    foxr     12977: $options is an optional parameter that if supplied is a hash reference that controls
                   12978: what how this function works.  It has the following key/values:
                   12979: 
                   12980: =over 4
                   12981: 
                   12982: =item freshen_cache
                   12983: 
                   12984: If defined, and the environment cache for the course is valid, it is 
                   12985: returned in the returned hash.
                   12986: 
                   12987: =item one_time
                   12988: 
                   12989: If defined, the last cache time is set to _now_
                   12990: 
                   12991: =item user
                   12992: 
                   12993: If defined, the supplied username is used instead of the current user.
                   12994: 
                   12995: 
                   12996: =back
                   12997: 
1.191     harris41 12998: =item *
                   12999: 
1.624     albertel 13000: resdata($name,$domain,$type,@which) : request for current parameter
                   13001: setting for a specific $type, where $type is either 'course' or 'user',
                   13002: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13003: answers for 10 minutes.
1.243     albertel 13004: 
1.877     foxr     13005: =item *
                   13006: 
                   13007: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13008: data base, returning a hash that is keyed by the resource name and has
                   13009: values that are the resource value.  I believe that the timestamps and
                   13010: versions are also returned.
                   13011: 
1.1236    raeburn  13012: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13013: supplemental content area. This routine caches the number of files for 
                   13014: 10 minutes.
                   13015: 
1.243     albertel 13016: =back
                   13017: 
                   13018: =head2 Course Modification
                   13019: 
                   13020: =over 4
1.191     harris41 13021: 
                   13022: =item *
                   13023: 
1.243     albertel 13024: writecoursepref($courseid,%prefs) : write preferences (environment
                   13025: database) for a course
1.191     harris41 13026: 
                   13027: =item *
                   13028: 
1.1011    raeburn  13029: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13030: 
                   13031: =item *
                   13032: 
1.1038    raeburn  13033: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13034: 
1.1167    droeschl 13035: =item *
                   13036: 
                   13037: is_course($courseid), is_course($cdom, $cnum)
                   13038: 
                   13039: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13040: two component version $cdom, $cnum. It checks if the specified course exists.
                   13041: 
                   13042: Returns:
                   13043:     undef if the course doesn't exist, otherwise
                   13044:     in scalar context the combined courseid.
                   13045:     in list context the two components of the course identifier, domain and 
                   13046:     courseid.    
                   13047: 
1.243     albertel 13048: =back
                   13049: 
                   13050: =head2 Resource Subroutines
                   13051: 
                   13052: =over 4
1.191     harris41 13053: 
                   13054: =item *
                   13055: 
1.243     albertel 13056: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13057: 
                   13058: =item *
                   13059: 
1.243     albertel 13060: repcopy($filename) : subscribes to the requested file, and attempts to
                   13061: replicate from the owning library server, Might return
1.607     raeburn  13062: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13063: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13064: resource. Expects the local filesystem pathname
                   13065: (/home/httpd/html/res/....)
                   13066: 
                   13067: =back
                   13068: 
                   13069: =head2 Resource Information
                   13070: 
                   13071: =over 4
1.191     harris41 13072: 
                   13073: =item *
                   13074: 
1.1228    raeburn  13075: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13076: and returns the value of a variety of different possible values,
                   13077: $varname should be a request string, and the other parameters can be
                   13078: used to specify who and what one is asking about. Ordinarily, $cid 
                   13079: does not need to be specified, as it is retrived from 
                   13080: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13081: within lonuserstate::loadmap() when initializing a course, before
                   13082: $env{'request.course.id'} has been set, so it needs to be provided
                   13083: in that one case.
1.243     albertel 13084: 
                   13085: Possible values for $varname are environment.lastname (or other item
                   13086: from the envirnment hash), user.name (or someother aspect about the
                   13087: user), resource.0.maxtries (or some other part and parameter of a
                   13088: resource)
1.204     albertel 13089: 
                   13090: =item *
                   13091: 
1.243     albertel 13092: directcondval($number) : get current value of a condition; reads from a state
                   13093: string
1.204     albertel 13094: 
                   13095: =item *
                   13096: 
1.243     albertel 13097: condval($condidx) : value of condition index based on state
1.204     albertel 13098: 
                   13099: =item *
                   13100: 
1.243     albertel 13101: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13102: resource's metadata, $what should be either a specific key, or either
                   13103: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13104: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13105: 
                   13106: this function automatically caches all requests
1.191     harris41 13107: 
                   13108: =item *
                   13109: 
1.243     albertel 13110: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13111: network of library servers; returns file handle of where SQL and regex results
                   13112: will be stored for query
1.191     harris41 13113: 
                   13114: =item *
                   13115: 
1.243     albertel 13116: symbread($filename) : return symbolic list entry (filename argument optional);
                   13117: returns the data handle
1.191     harris41 13118: 
                   13119: =item *
                   13120: 
1.1190    raeburn  13121: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13122: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13123: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13124: on failure, user must be in a course, as it assumes the existence of
                   13125: the course initial hash, and uses $env('request.course.id'}.  The third
                   13126: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13127: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13128: encrypted; otherwise it will be null.  
1.191     harris41 13129: 
                   13130: =item *
                   13131: 
1.243     albertel 13132: symbclean($symb) : removes versions numbers from a symb, returns the
                   13133: cleaned symb
1.191     harris41 13134: 
                   13135: =item *
                   13136: 
1.243     albertel 13137: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13138: course map, user must be in a course for it to work.
1.191     harris41 13139: 
                   13140: =item *
                   13141: 
1.243     albertel 13142: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13143: 
                   13144: =item *
                   13145: 
1.243     albertel 13146: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13147: a random seed, all arguments are optional, if they aren't sent it uses the
                   13148: environment to derive them. Note: if symb isn't sent and it can't get one
                   13149: from &symbread it will use the current time as its return value
1.191     harris41 13150: 
                   13151: =item *
                   13152: 
1.243     albertel 13153: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13154: unfakeable, receipt
1.191     harris41 13155: 
                   13156: =item *
                   13157: 
1.620     albertel 13158: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13159: 
                   13160: =item *
                   13161: 
1.243     albertel 13162: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13163: 
                   13164: =item *
                   13165: 
1.243     albertel 13166: 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 13167: 
                   13168: =item *
                   13169: 
1.243     albertel 13170: 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 13171: 
                   13172: =item *
                   13173: 
1.243     albertel 13174: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13175: 
                   13176: =item *
                   13177: 
1.243     albertel 13178: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13179: forcing spreadsheet to reevaluate the resource scores next time.
                   13180: 
1.1195    raeburn  13181: =item * 
                   13182: 
1.1196    raeburn  13183: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13184: when viewing in course context.
1.1195    raeburn  13185: 
1.1196    raeburn  13186:  input: six args -- filename (decluttered), course number, course domain,
                   13187:                     url, symb (if registered) and group (if this is a 
                   13188:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13189: 
1.1196    raeburn  13190:  output: array of five scalars --
1.1195    raeburn  13191:          $cfile -- url for file editing if editable on current server
                   13192:          $home -- homeserver of resource (i.e., for author if published,
                   13193:                                           or course if uploaded.).
                   13194:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13195:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13196:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13197: 
                   13198: =item *
                   13199: 
                   13200: is_course_upload($file,$cnum,$cdom)
                   13201: 
                   13202: Used in course context to determine if current file was uploaded to 
                   13203: the course (i.e., would be found in /userfiles/docs on the course's 
                   13204: homeserver.
                   13205: 
                   13206:   input: 3 args -- filename (decluttered), course number and course domain.
                   13207:   output: boolean -- 1 if file was uploaded.
                   13208: 
1.243     albertel 13209: =back
                   13210: 
                   13211: =head2 Storing/Retreiving Data
                   13212: 
                   13213: =over 4
1.191     harris41 13214: 
                   13215: =item *
                   13216: 
1.243     albertel 13217: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13218: for this url; hashref needs to be given and should be a \%hashname; the
                   13219: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13220: be derived from the env
1.191     harris41 13221: 
                   13222: =item *
                   13223: 
1.243     albertel 13224: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13225: uses critical subroutine
1.191     harris41 13226: 
                   13227: =item *
                   13228: 
1.243     albertel 13229: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13230: all args are optional
1.191     harris41 13231: 
                   13232: =item *
                   13233: 
1.717     albertel 13234: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13235: dumps the complete (or key matching regexp) namespace into a hash
                   13236: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13237: normally &store()ed into
                   13238: 
                   13239: $range should be either an integer '100' (give me the first 100
                   13240:                                            matching records)
                   13241:               or be  two integers sperated by a - with no spaces
                   13242:                  '30-50' (give me the 30th through the 50th matching
                   13243:                           records)
                   13244: 
                   13245: 
                   13246: =item *
                   13247: 
                   13248: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13249: replaces a &store() version of data with a replacement set of data
                   13250: for a particular resource in a namespace passed in the $storehash hash 
                   13251: reference
                   13252: 
                   13253: =item *
                   13254: 
1.243     albertel 13255: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13256: works very similar to store/cstore, but all data is stored in a
                   13257: temporary location and can be reset using tmpreset, $storehash should
                   13258: be a hash reference, returns nothing on success
1.191     harris41 13259: 
                   13260: =item *
                   13261: 
1.243     albertel 13262: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13263: similar to restore, but all data is stored in a temporary location and
                   13264: can be reset using tmpreset. Returns a hash of values on success,
                   13265: error string otherwise.
1.191     harris41 13266: 
                   13267: =item *
                   13268: 
1.243     albertel 13269: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13270: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13271: 
                   13272: =item *
                   13273: 
1.243     albertel 13274: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13275: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13276: 
                   13277: =item *
                   13278: 
1.243     albertel 13279: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13280: namesp ($udom and $uname are optional)
1.191     harris41 13281: 
                   13282: =item *
                   13283: 
1.702     albertel 13284: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13285: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13286: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13287: 
1.702     albertel 13288: $range should be either an integer '100' (give me the first 100
                   13289:                                            matching records)
                   13290:               or be  two integers sperated by a - with no spaces
                   13291:                  '30-50' (give me the 30th through the 50th matching
                   13292:                           records)
1.449     matthew  13293: =item *
                   13294: 
                   13295: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13296: $store can be a scalar, an array reference, or if the amount to be 
                   13297: incremented is > 1, a hash reference.
                   13298: 
                   13299: ($udom and $uname are optional)
1.191     harris41 13300: 
                   13301: =item *
                   13302: 
1.243     albertel 13303: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13304: ($udom and $uname are optional)
1.191     harris41 13305: 
                   13306: =item *
                   13307: 
1.243     albertel 13308: cput($namespace,$storehash,$udom,$uname) : critical put
                   13309: ($udom and $uname are optional)
1.191     harris41 13310: 
                   13311: =item *
                   13312: 
1.748     albertel 13313: newput($namespace,$storehash,$udom,$uname) :
                   13314: 
                   13315: Attempts to store the items in the $storehash, but only if they don't
                   13316: currently exist, if this succeeds you can be certain that you have 
                   13317: successfully created a new key value pair in the $namespace db.
                   13318: 
                   13319: 
                   13320: Args:
                   13321:  $namespace: name of database to store values to
                   13322:  $storehash: hashref to store to the db
                   13323:  $udom: (optional) domain of user containing the db
                   13324:  $uname: (optional) name of user caontaining the db
                   13325: 
                   13326: Returns:
                   13327:  'ok' -> succeeded in storing all keys of $storehash
                   13328:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13329:                         least <key> already existed in the db (other
                   13330:                         requested keys may also already exist)
1.967     bisitz   13331:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13332:  'con_lost' -> unable to contact request server
                   13333:  'refused' -> action was not allowed by remote machine
                   13334: 
                   13335: 
                   13336: =item *
                   13337: 
1.243     albertel 13338: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13339: reference filled in from namesp (encrypts the return communication)
                   13340: ($udom and $uname are optional)
1.191     harris41 13341: 
                   13342: =item *
                   13343: 
1.243     albertel 13344: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13345: critical subroutine
                   13346: 
1.806     raeburn  13347: =item *
                   13348: 
1.860     raeburn  13349: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13350: array reference filled in from namespace found in domain level on either
                   13351: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13352: 
                   13353: =item *
                   13354: 
1.860     raeburn  13355: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13356: domain level either on specified domain server ($uhome) or primary domain 
                   13357: server ($udom and $uhome are optional)
1.806     raeburn  13358: 
1.943     raeburn  13359: =item * 
                   13360: 
1.1240    raeburn  13361: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13362: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13363: the target domain.
                   13364: 
                   13365: May also include additional key => value pairs for the following groups:
                   13366: 
                   13367: =over
                   13368: 
                   13369: =item
                   13370: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13371: 
                   13372: =over
                   13373: 
                   13374: =item defaultquota, authorquota
                   13375: 
                   13376: =back
                   13377: 
                   13378: =item
                   13379: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13380: portfolio for users).
                   13381: 
                   13382: =over
                   13383: 
                   13384: =item
                   13385: aboutme, blog, webdav, portfolio
                   13386: 
                   13387: =back
                   13388: 
                   13389: =item
                   13390: requestcourses: ability to request courses, and how requests are processed.
                   13391: 
                   13392: =over
                   13393: 
                   13394: =item
1.1246    raeburn  13395: official, unofficial, community, textbook
1.1240    raeburn  13396: 
                   13397: =back
                   13398: 
                   13399: =item
                   13400: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13401: 
                   13402: =over
                   13403: 
                   13404: =item
1.1256    raeburn  13405: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  13406: 
                   13407: =back
                   13408: 
                   13409: =item
                   13410: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13411: for course's uploaded content.
                   13412: 
                   13413: =over
                   13414: 
                   13415: =item
1.1246    raeburn  13416: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   13417: communityquota, textbookquota
1.1240    raeburn  13418: 
                   13419: =back
                   13420: 
                   13421: =item
                   13422: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13423: on your servers.
                   13424: 
                   13425: =over
                   13426: 
                   13427: =item 
                   13428: remotesessions, hostedsessions
                   13429: 
                   13430: =back
                   13431: 
                   13432: =back
                   13433: 
                   13434: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13435: utility to create a configuration.db file on a domain's primary library server 
                   13436: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13437: -- corresponding values are authentication type (internal, krb4, krb5,
                   13438: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13439: will be available. Values are retrieved from cache (if current), unless the
                   13440: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13441: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13442: 
                   13443: Typical usage:
1.943     raeburn  13444: 
1.1240    raeburn  13445: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13446: 
1.243     albertel 13447: =back
                   13448: 
                   13449: =head2 Network Status Functions
                   13450: 
                   13451: =over 4
1.191     harris41 13452: 
                   13453: =item *
                   13454: 
1.1137    raeburn  13455: dirlist() : return directory list based on URI (first arg).
                   13456: 
                   13457: Inputs: 1 required, 5 optional.
                   13458: 
                   13459: =over
                   13460: 
                   13461: =item 
                   13462: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13463: 
                   13464: =item
                   13465: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13466: 
                   13467: =item
                   13468: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13469: 
                   13470: =item
                   13471: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13472: 
                   13473: =item
                   13474: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13475: 
                   13476: =item 
                   13477: $alternateRoot - path to prepend in place of path from $uri.
                   13478: 
                   13479: =back
                   13480: 
                   13481: Returns: Array of up to two items.
                   13482: 
                   13483: =over
                   13484: 
                   13485: a reference to an array of files/subdirectories
                   13486: 
                   13487: =over
                   13488: 
                   13489: Each element in the array of files/subdirectories is a & separated list of
                   13490: item name and the result of running stat on the item.  If dirlist was requested
                   13491: for a file instead of a directory, the item name will be ''. For a directory 
                   13492: listing, if the item is a metadata file, the element will end &N&M 
                   13493: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13494: default copyright set (1).  
                   13495: 
                   13496: =back
                   13497: 
                   13498: a scalar containing error condition (if encountered).
                   13499: 
                   13500: =over
                   13501: 
                   13502: =item 
                   13503: no_host (no homeserver identified for $username:$domain).
                   13504: 
                   13505: =item 
                   13506: no_such_host (server contacted for listing not identified as valid host).
                   13507: 
                   13508: =item 
                   13509: con_lost (connection to remote server failed).
                   13510: 
                   13511: =item 
                   13512: refused (invalid $username:$domain received on lond side).
                   13513: 
                   13514: =item 
                   13515: no_such_dir (directory at specified path on lond side does not exist). 
                   13516: 
                   13517: =item 
                   13518: empty (directory at specified path on lond side is empty).
                   13519: 
                   13520: =over
                   13521: 
                   13522: This is currently not encountered because the &ls3, &ls2, 
                   13523: &ls (_handler) routines on the lond side do not filter out
                   13524: . and .. from a directory listing. 
                   13525: 
                   13526: =back
                   13527: 
                   13528: =back
                   13529: 
                   13530: =back
1.191     harris41 13531: 
                   13532: =item *
                   13533: 
1.243     albertel 13534: spareserver() : find server with least workload from spare.tab
                   13535: 
1.986     foxr     13536: 
                   13537: =item *
                   13538: 
                   13539: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13540: if there is no corresponding loncapa host.
                   13541: 
1.243     albertel 13542: =back
                   13543: 
1.986     foxr     13544: 
1.243     albertel 13545: =head2 Apache Request
                   13546: 
                   13547: =over 4
1.191     harris41 13548: 
                   13549: =item *
                   13550: 
1.243     albertel 13551: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13552: localhost, posts hash
                   13553: 
                   13554: =back
                   13555: 
                   13556: =head2 Data to String to Data
                   13557: 
                   13558: =over 4
1.191     harris41 13559: 
                   13560: =item *
                   13561: 
1.243     albertel 13562: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13563: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13564: 
                   13565: =item *
                   13566: 
1.243     albertel 13567: hashref2str($hashref) : convert a hashref into a string complete with
                   13568: escaping and '=' and '&' separators, supports elements that are
                   13569: arrayrefs and hashrefs
1.191     harris41 13570: 
                   13571: =item *
                   13572: 
1.243     albertel 13573: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13574: with escaping and '&' separators, supports elements that are arrayrefs
                   13575: and hashrefs
1.191     harris41 13576: 
                   13577: =item *
                   13578: 
1.243     albertel 13579: str2hash($string) : convert string to hash using unescaping and
                   13580: splitting on '=' and '&', supports elements that are arrayrefs and
                   13581: hashrefs
1.191     harris41 13582: 
                   13583: =item *
                   13584: 
1.243     albertel 13585: str2array($string) : convert string to hash using unescaping and
                   13586: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13587: 
                   13588: =back
                   13589: 
                   13590: =head2 Logging Routines
                   13591: 
                   13592: 
                   13593: These routines allow one to make log messages in the lonnet.log and
                   13594: lonnet.perm logfiles.
1.191     harris41 13595: 
1.1119    foxr     13596: =over 4
                   13597: 
1.191     harris41 13598: =item *
                   13599: 
1.243     albertel 13600: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13601: 
                   13602: =item *
                   13603: 
1.243     albertel 13604: logthis() : append message to the normal lonnet.log file, it gets
                   13605: preiodically rolled over and deleted.
1.191     harris41 13606: 
                   13607: =item *
                   13608: 
1.243     albertel 13609: logperm() : append a permanent message to lonnet.perm.log, this log
                   13610: file never gets deleted by any automated portion of the system, only
                   13611: messages of critical importance should go in here.
                   13612: 
1.1119    foxr     13613: 
1.243     albertel 13614: =back
                   13615: 
                   13616: =head2 General File Helper Routines
                   13617: 
                   13618: =over 4
1.191     harris41 13619: 
                   13620: =item *
                   13621: 
1.481     raeburn  13622: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13623: (a) files in /uploaded
                   13624:   (i) If a local copy of the file exists - 
                   13625:       compares modification date of local copy with last-modified date for 
                   13626:       definitive version stored on home server for course. If local copy is 
                   13627:       stale, requests a new version from the home server and stores it. 
                   13628:       If the original has been removed from the home server, then local copy 
                   13629:       is unlinked.
                   13630:   (ii) If local copy does not exist -
                   13631:       requests the file from the home server and stores it. 
                   13632:   
                   13633:   If $caller is 'uploadrep':  
                   13634:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13635:     for request for files originally uploaded via DOCS. 
                   13636:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13637:   
                   13638:   Otherwise:
                   13639:      This indicates a call from the content generation phase of the request.
                   13640:      -  returns the entire contents of the file or -1.
                   13641:      
                   13642: (b) files in /res
                   13643:    - returns the entire contents of a file or -1; 
                   13644:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13645: 
1.712     albertel 13646: 
                   13647: =item *
                   13648: 
                   13649: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13650:                   reference
                   13651: 
                   13652: returns either a stat() list of data about the file or an empty list
                   13653: if the file doesn't exist or couldn't find out about it (connection
                   13654: problems or user unknown)
                   13655: 
1.191     harris41 13656: =item *
                   13657: 
1.243     albertel 13658: filelocation($dir,$file) : returns file system location of a file
                   13659: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13660: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13661: and a file of ../bob will become /a/bob)
1.191     harris41 13662: 
                   13663: =item *
                   13664: 
                   13665: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13666: filelocation except for hrefs
                   13667: 
                   13668: =item *
                   13669: 
1.1261    raeburn  13670: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   13671: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 13672: 
1.243     albertel 13673: =back
                   13674: 
1.608     albertel 13675: =head2 Usererfile file routines (/uploaded*)
                   13676: 
                   13677: =over 4
                   13678: 
                   13679: =item *
                   13680: 
                   13681: userfileupload(): main rotine for putting a file in a user or course's
                   13682:                   filespace, arguments are,
                   13683: 
1.620     albertel 13684:  formname - required - this is the name of the element in $env where the
1.608     albertel 13685:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13686:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13687:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13688:  context - if coursedoc, store the file in the course of the active role
                   13689:              of the current user; 
                   13690:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13691:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13692:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13693:          if undefined, it will be placed in "unknown"
                   13694: 
                   13695:  (This routine calls clean_filename() to remove any dangerous
                   13696:  characters from the filename, and then calls finuserfileupload() to
                   13697:  complete the transaction)
                   13698: 
                   13699:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13700:  and /adm/notfound.html if unsuccessful
                   13701: 
                   13702: =item *
                   13703: 
                   13704: clean_filename(): routine for cleaing a filename up for storage in
                   13705:                  userfile space, argument is:
                   13706: 
                   13707:  filename - proposed filename
                   13708: 
                   13709: returns: the new clean filename
                   13710: 
                   13711: =item *
                   13712: 
1.1090    raeburn  13713: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13714: userspace, probably shouldn't be called directly
                   13715: 
                   13716:   docuname: username or courseid of destination for the file
                   13717:   docudom: domain of user/course of destination for the file
                   13718:   formname: same as for userfileupload()
1.1090    raeburn  13719:   fname: filename (including subdirectories) for the file
                   13720:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13721:   allfiles: reference to hash used to store objects found by parser
                   13722:   codebase: reference to hash used for codebases of java objects found by parser
                   13723:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13724:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13725:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13726:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13727:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13728:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13729:   mimetype: reference to scalar to accommodate mime type determined
                   13730:             from File::MMagic if $parser = parse.
1.608     albertel 13731: 
                   13732:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13733:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13734:  was 'overwrite').
                   13735:  
1.608     albertel 13736: 
                   13737: =item *
                   13738: 
                   13739: renameuserfile(): renames an existing userfile to a new name
                   13740: 
                   13741:   Args:
                   13742:    docuname: username or courseid of destination for the file
                   13743:    docudom: domain of user/course of destination for the file
                   13744:    old: current file name (including any subdirs under userfiles)
                   13745:    new: desired file name (including any subdirs under userfiles)
                   13746: 
                   13747: =item *
                   13748: 
                   13749: mkdiruserfile(): creates a directory is a userfiles dir
                   13750: 
                   13751:   Args:
                   13752:    docuname: username or courseid of destination for the file
                   13753:    docudom: domain of user/course of destination for the file
                   13754:    dir: dir to create (including any subdirs under userfiles)
                   13755: 
                   13756: =item *
                   13757: 
                   13758: removeuserfile(): removes a file that exists in userfiles
                   13759: 
                   13760:   Args:
                   13761:    docuname: username or courseid of destination for the file
                   13762:    docudom: domain of user/course of destination for the file
                   13763:    fname: filname to delete (including any subdirs under userfiles)
                   13764: 
                   13765: =item *
                   13766: 
                   13767: removeuploadedurl(): convience function for removeuserfile()
                   13768: 
                   13769:   Args:
                   13770:    url:  a full /uploaded/... url to delete
                   13771: 
1.747     albertel 13772: =item * 
                   13773: 
                   13774: get_portfile_permissions():
                   13775:   Args:
                   13776:     domain: domain of user or course contain the portfolio files
                   13777:     user: name of user or num of course contain the portfolio files
                   13778:   Returns:
                   13779:     hashref of a dump of the proper file_permissions.db
                   13780:    
                   13781: 
                   13782: =item * 
                   13783: 
                   13784: get_access_controls():
                   13785: 
                   13786: Args:
                   13787:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13788:   group: (optional) the group you want the files associated with
                   13789:   file: (optional) the file you want access info on
                   13790: 
                   13791: Returns:
1.749     raeburn  13792:     a hash (keys are file names) of hashes containing
                   13793:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13794:         values are XML containing access control settings (see below) 
1.747     albertel 13795: 
                   13796: Internal notes:
                   13797: 
1.749     raeburn  13798:  access controls are stored in file_permissions.db as key=value pairs.
                   13799:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13800:         where scope -> public,guest,course,group,domains or users.
                   13801:               end -> UNIX time for end of access (0 -> no end date)
                   13802:               start -> UNIX time for start of access
                   13803: 
                   13804:     value -> XML description of access control
                   13805:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13806:             <start></start>
                   13807:             <end></end>
                   13808: 
                   13809:             <password></password>  for scope type = guest
                   13810: 
                   13811:             <domain></domain>     for scope type = course or group
                   13812:             <number></number>
                   13813:             <roles id="">
                   13814:              <role></role>
                   13815:              <access></access>
                   13816:              <section></section>
                   13817:              <group></group>
                   13818:             </roles>
                   13819: 
                   13820:             <dom></dom>         for scope type = domains
                   13821: 
                   13822:             <users>             for scope type = users
                   13823:              <user>
                   13824:               <uname></uname>
                   13825:               <udom></udom>
                   13826:              </user>
                   13827:             </users>
                   13828:            </scope> 
                   13829:               
                   13830:  Access data is also aggregated for each file in an additional key=value pair:
                   13831:  key -> path to file/file_name\0accesscontrol 
                   13832:  value -> reference to hash
                   13833:           hash contains key = value pairs
                   13834:           where key = uniqueID:scope_end_start
                   13835:                 value = UNIX time record was last updated
                   13836: 
                   13837:           Used to improve speed of look-ups of access controls for each file.  
                   13838:  
                   13839:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13840: 
1.1198    raeburn  13841: =item *
                   13842: 
1.749     raeburn  13843: modify_access_controls():
                   13844: 
                   13845: Modifies access controls for a portfolio file
                   13846: Args
                   13847: 1. file name
                   13848: 2. reference to hash of required changes,
                   13849: 3. domain
                   13850: 4. username
                   13851:   where domain,username are the domain of the portfolio owner 
                   13852:   (either a user or a course) 
                   13853: 
                   13854: Returns:
                   13855: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13856: 2. result of deletions ('ok' or 'error', with error message).
                   13857: 3. reference to hash of any new or updated access controls.
                   13858: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13859:    key = integer (inbound ID)
1.1198    raeburn  13860:    value = uniqueID
                   13861: 
                   13862: =item *
                   13863: 
                   13864: get_timebased_id():
                   13865: 
                   13866: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13867: course via the Course Editor (e.g., folders, composite pages, 
                   13868: group bulletin boards).
                   13869: 
                   13870: Args: (first three required; six others optional)
                   13871: 
                   13872: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13873:    docssequence, or name of group
                   13874: 
                   13875: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13876:    e.g., num, boardids
                   13877: 
                   13878: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   13879:    file will be named nohist_namespace.db
                   13880: 
                   13881: 4. cdom: domain of course; default is current course domain from %env
                   13882: 
                   13883: 5. cnum: course number; default is current course number from %env
                   13884: 
                   13885: 6. idtype: set to concat if an additional digit is to be appended to the 
                   13886:    unix timestamp to form the suffix, if the plain timestamp is already
                   13887:    in use.  Default is to not do this, but simply increment the unix 
                   13888:    timestamp by 1 until a unique key is obtained.
                   13889: 
                   13890: 7. who: holder of locking key; defaults to user:domain for user.
                   13891: 
                   13892: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   13893:    retrying); default is 3.
                   13894: 
                   13895: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   13896: 
                   13897: Returns:
                   13898: 
                   13899: 1. suffix obtained (numeric)
                   13900: 
                   13901: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13902: 
                   13903: 3. error: contains (localized) error message if an error occurred.
                   13904: 
1.747     albertel 13905: 
1.608     albertel 13906: =back
                   13907: 
1.243     albertel 13908: =head2 HTTP Helper Routines
                   13909: 
                   13910: =over 4
                   13911: 
1.191     harris41 13912: =item *
                   13913: 
                   13914: escape() : unpack non-word characters into CGI-compatible hex codes
                   13915: 
                   13916: =item *
                   13917: 
                   13918: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13919: 
1.243     albertel 13920: =back
                   13921: 
                   13922: =head1 PRIVATE SUBROUTINES
                   13923: 
                   13924: =head2 Underlying communication routines (Shouldn't call)
                   13925: 
                   13926: =over 4
                   13927: 
                   13928: =item *
                   13929: 
                   13930: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13931: 
                   13932: =item *
                   13933: 
                   13934: reply() : uses subreply to send a message to remote machine, logs all failures
                   13935: 
                   13936: =item *
                   13937: 
                   13938: critical() : passes a critical message to another server; if cannot
                   13939: get through then place message in connection buffer directory and
                   13940: returns con_delayed, if incapable of saving message, returns
                   13941: con_failed
                   13942: 
                   13943: =item *
                   13944: 
                   13945: reconlonc() : tries to reconnect lonc client processes.
                   13946: 
                   13947: =back
                   13948: 
                   13949: =head2 Resource Access Logging
                   13950: 
                   13951: =over 4
                   13952: 
                   13953: =item *
                   13954: 
                   13955: flushcourselogs() : flush (save) buffer logs and access logs
                   13956: 
                   13957: =item *
                   13958: 
                   13959: courselog($what) : save message for course in hash
                   13960: 
                   13961: =item *
                   13962: 
                   13963: courseacclog($what) : save message for course using &courselog().  Perform
                   13964: special processing for specific resource types (problems, exams, quizzes, etc).
                   13965: 
1.191     harris41 13966: =item *
                   13967: 
                   13968: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13969: as a PerlChildExitHandler
1.243     albertel 13970: 
                   13971: =back
                   13972: 
                   13973: =head2 Other
                   13974: 
                   13975: =over 4
                   13976: 
                   13977: =item *
                   13978: 
                   13979: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13980: 
                   13981: =back
                   13982: 
                   13983: =cut
1.877     foxr     13984: 

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