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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1253  ! raeburn     4: # $Id: lonnet.pm,v 1.1252 2014/03/09 15:39:04 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.1253  ! raeburn   964:     my ($udom,$checkloginvia,$required) = @_;
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.1151    raeburn   968:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   969:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   970:         my $loginvia;
                    971:         if ($checkloginvia) {
                    972:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   973:             if ($loginvia) {
                    974:                 my ($server,$path) = split(/:/,$loginvia);
                    975:                 ($login_host, $lowest_load) =
1.1253  ! raeburn   976:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   977:                 if ($login_host eq $server) {
                    978:                     $portal_path = $path;
1.1151    raeburn   979:                     $isredirect = 1;
1.1116    raeburn   980:                 }
                    981:             } else {
                    982:                 ($login_host, $lowest_load) =
1.1253  ! raeburn   983:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   984:                 if ($login_host eq $lonhost) {
                    985:                     $portal_path = '';
1.1151    raeburn   986:                     $isredirect = ''; 
1.1116    raeburn   987:                 }
                    988:             }
                    989:         } else {
1.1076    raeburn   990:             ($login_host, $lowest_load) =
1.1253  ! raeburn   991:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn   992:         }
                    993:     }
                    994:     if ($login_host ne '') {
1.1116    raeburn   995:         $hostname = &hostname($login_host);
1.1076    raeburn   996:     }
1.1151    raeburn   997:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   998: }
                    999: 
1.202     matthew  1000: # --------------------------------------------- Try to change a user's password
                   1001: 
                   1002: sub changepass {
1.799     raeburn  1003:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1004:     $currentpass = &escape($currentpass);
                   1005:     $newpass     = &escape($newpass);
1.1030    raeburn  1006:     my $lonhost = $perlvar{'lonHostID'};
                   1007:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1008: 		       $server);
                   1009:     if (! $answer) {
                   1010: 	&logthis("No reply on password change request to $server ".
                   1011: 		 "by $uname in domain $udom.");
                   1012:     } elsif ($answer =~ "^ok") {
                   1013:         &logthis("$uname in $udom successfully changed their password ".
                   1014: 		 "on $server.");
                   1015:     } elsif ($answer =~ "^pwchange_failure") {
                   1016: 	&logthis("$uname in $udom was unable to change their password ".
                   1017: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1018: 		 "or pwchange");
                   1019:     } elsif ($answer =~ "^non_authorized") {
                   1020:         &logthis("$uname in $udom did not get their password correct when ".
                   1021: 		 "attempting to change it on $server.");
                   1022:     } elsif ($answer =~ "^auth_mode_error") {
                   1023:         &logthis("$uname in $udom attempted to change their password despite ".
                   1024: 		 "not being locally or internally authenticated on $server.");
                   1025:     } elsif ($answer =~ "^unknown_user") {
                   1026:         &logthis("$uname in $udom attempted to change their password ".
                   1027: 		 "on $server but were unable to because $server is not ".
                   1028: 		 "their home server.");
                   1029:     } elsif ($answer =~ "^refused") {
                   1030: 	&logthis("$server refused to change $uname in $udom password because ".
                   1031: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1032:     } elsif ($answer =~ "invalid_client") {
                   1033:         &logthis("$server refused to change $uname in $udom password because ".
                   1034:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1035:     }
                   1036:     return $answer;
1.1       albertel 1037: }
                   1038: 
1.169     harris41 1039: # ----------------------- Try to determine user's current authentication scheme
                   1040: 
                   1041: sub queryauthenticate {
                   1042:     my ($uname,$udom)=@_;
1.456     albertel 1043:     my $uhome=&homeserver($uname,$udom);
                   1044:     if (!$uhome) {
                   1045: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1046: 	return 'no_host';
                   1047:     }
                   1048:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1049:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1050: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1051:     }
1.456     albertel 1052:     return $answer;
1.169     harris41 1053: }
                   1054: 
1.1       albertel 1055: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1056: 
1.1       albertel 1057: sub authenticate {
1.1073    raeburn  1058:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1059:     $upass=&escape($upass);
                   1060:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1061:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1062:     my $newhome;
1.836     www      1063:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1064: # Maybe the machine was offline and only re-appeared again recently?
                   1065:         &reconlonc();
                   1066: # One more
1.952     raeburn  1067: 	$uhome=&homeserver($uname,$udom,1);
                   1068:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1069:             if (defined(&domain($udom,'primary'))) {
                   1070:                 $newhome=&domain($udom,'primary');
                   1071:             }
                   1072:             if ($newhome ne '') {
                   1073:                 $uhome = $newhome;
                   1074:             }
                   1075:         }
1.836     www      1076: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1077: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1078: 	    return 'no_host';
                   1079:         }
1.1       albertel 1080:     }
1.1073    raeburn  1081:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1082:     if ($answer eq 'authorized') {
1.952     raeburn  1083:         if ($newhome) {
                   1084:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1085:             return 'no_account_on_host'; 
                   1086:         } else {
                   1087:             &logthis("User $uname at $udom authorized by $uhome");
                   1088:             return $uhome;
                   1089:         }
1.471     albertel 1090:     }
                   1091:     if ($answer eq 'non_authorized') {
                   1092: 	&logthis("User $uname at $udom rejected by $uhome");
                   1093: 	return 'no_host'; 
1.9       www      1094:     }
1.471     albertel 1095:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1096:     return 'no_host';
                   1097: }
                   1098: 
1.1073    raeburn  1099: sub can_host_session {
1.1074    raeburn  1100:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1101:     my $canhost = 1;
1.1074    raeburn  1102:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1103:     if (ref($remotesessions) eq 'HASH') {
                   1104:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1105:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1106:                 $canhost = 0;
                   1107:             } else {
                   1108:                 $canhost = 1;
                   1109:             }
                   1110:         }
                   1111:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1112:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1113:                 $canhost = 1;
                   1114:             } else {
                   1115:                 $canhost = 0;
                   1116:             }
                   1117:         }
                   1118:         if ($canhost) {
                   1119:             if ($remotesessions->{'version'} ne '') {
                   1120:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1121:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1122:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1123:                         my $major = $1;
                   1124:                         my $minor = $2;
                   1125:                         if (($major < $reqmajor ) ||
                   1126:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1127:                             $canhost = 0;
                   1128:                         }
                   1129:                     } else {
                   1130:                         $canhost = 0;
                   1131:                     }
                   1132:                 }
                   1133:             }
                   1134:         }
                   1135:     }
                   1136:     if ($canhost) {
                   1137:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1138:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1139:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1140:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1141:                 if (($uint_dom ne '') && 
                   1142:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1143:                     $canhost = 0;
                   1144:                 } else {
                   1145:                     $canhost = 1;
                   1146:                 }
                   1147:             }
                   1148:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1149:                 if (($uint_dom ne '') && 
                   1150:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1151:                     $canhost = 1;
                   1152:                 } else {
                   1153:                     $canhost = 0;
                   1154:                 }
                   1155:             }
                   1156:         }
                   1157:     }
                   1158:     return $canhost;
                   1159: }
                   1160: 
1.1083    raeburn  1161: sub spare_can_host {
                   1162:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1163:     my $canhost=1;
                   1164:     my @intdoms;
                   1165:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1166:     if (ref($internet_names) eq 'ARRAY') {
                   1167:         @intdoms = @{$internet_names};
                   1168:     }
                   1169:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1170:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1171:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1172:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1173:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1174:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1175:                                      $remotesessions,
                   1176:                                      $defdomdefaults{'hostedsessions'});
                   1177:     }
                   1178:     return $canhost;
                   1179: }
                   1180: 
1.1123    raeburn  1181: sub this_host_spares {
                   1182:     my ($dom) = @_;
1.1126    raeburn  1183:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1184:     my @hosts = &current_machine_ids();
                   1185:     foreach my $lonhost (@hosts) {
                   1186:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1187:             $dom_in_use = $dom;
                   1188:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1189:             last;
                   1190:         }
                   1191:     }
1.1126    raeburn  1192:     if ($dom_in_use ne '') {
                   1193:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1194:     }
                   1195:     if (ref($result) ne 'HASH') {
                   1196:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1197:         $dom_in_use = &host_domain($lonhost_in_use);
                   1198:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1199:         if (ref($result) ne 'HASH') {
                   1200:             $result = \%spareid;
                   1201:         }
                   1202:     }
                   1203:     return $result;
                   1204: }
                   1205: 
                   1206: sub spares_for_offload  {
                   1207:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1208:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1209:     if (defined($cached)) {
                   1210:         return $result;
                   1211:     } else {
1.1126    raeburn  1212:         my $cachetime = 60*60*24;
                   1213:         my %domconfig =
                   1214:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1215:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1216:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1217:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1218:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1219:                 }
                   1220:             }
                   1221:         }
                   1222:     }
1.1126    raeburn  1223:     return;
1.1123    raeburn  1224: }
                   1225: 
1.1129    raeburn  1226: sub get_lonbalancer_config {
                   1227:     my ($servers) = @_;
                   1228:     my ($currbalancer,$currtargets);
                   1229:     if (ref($servers) eq 'HASH') {
                   1230:         foreach my $server (keys(%{$servers})) {
                   1231:             my %what = (
                   1232:                          spareid => 1,
                   1233:                          perlvar => 1,
                   1234:                        );
                   1235:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1236:             if ($result eq 'ok') {
                   1237:                 if (ref($returnhash) eq 'HASH') {
                   1238:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1239:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1240:                             $currbalancer = $server;
                   1241:                             $currtargets = {};
                   1242:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1243:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1244:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1245:                                 }
                   1246:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1247:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1248:                                 }
                   1249:                             }
                   1250:                             last;
                   1251:                         }
                   1252:                     }
                   1253:                 }
                   1254:             }
                   1255:         }
                   1256:     }
                   1257:     return ($currbalancer,$currtargets);
                   1258: }
                   1259: 
                   1260: sub check_loadbalancing {
                   1261:     my ($uname,$udom) = @_;
1.1191    raeburn  1262:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1263:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1264:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1265:     my @hosts = &current_machine_ids();
1.1129    raeburn  1266:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1267:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1268:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1269:     my $serverhomedom = &host_domain($lonhost);
                   1270: 
                   1271:     my $cachetime = 60*60*24;
                   1272: 
                   1273:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1274:         $dom_in_use = $udom;
                   1275:         $homeintdom = 1;
                   1276:     } else {
                   1277:         $dom_in_use = $serverhomedom;
                   1278:     }
                   1279:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1280:     unless (defined($cached)) {
                   1281:         my %domconfig =
                   1282:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1283:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1284:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1285:         }
                   1286:     }
                   1287:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1288:         ($is_balancer,$currtargets,$currrules) = 
                   1289:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1290:         if ($is_balancer) {
                   1291:             if (ref($currrules) eq 'HASH') {
                   1292:                 if ($homeintdom) {
                   1293:                     if ($uname ne '') {
                   1294:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1295:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1296:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1297:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1298:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1299:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1300:                             }
                   1301:                         }
                   1302:                         if ($rule_in_effect eq '') {
                   1303:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1304:                             if ($userenv{'inststatus'} ne '') {
                   1305:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1306:                                 my ($othertitle,$usertypes,$types) =
                   1307:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1308:                                 if (ref($types) eq 'ARRAY') {
                   1309:                                     foreach my $type (@{$types}) {
                   1310:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1311:                                             if (exists($currrules->{$type})) {
                   1312:                                                 $rule_in_effect = $currrules->{$type};
                   1313:                                             }
                   1314:                                         }
                   1315:                                     }
                   1316:                                 }
                   1317:                             } else {
                   1318:                                 if (exists($currrules->{'default'})) {
                   1319:                                     $rule_in_effect = $currrules->{'default'};
                   1320:                                 }
                   1321:                             }
                   1322:                         }
                   1323:                     } else {
                   1324:                         if (exists($currrules->{'default'})) {
                   1325:                             $rule_in_effect = $currrules->{'default'};
                   1326:                         }
                   1327:                     }
                   1328:                 } else {
                   1329:                     if ($currrules->{'_LC_external'} ne '') {
                   1330:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1331:                     }
                   1332:                 }
                   1333:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1334:                                                        $uname,$udom);
                   1335:             }
                   1336:         }
                   1337:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1338:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1339:         unless (defined($cached)) {
                   1340:             my %domconfig =
                   1341:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1342:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1343:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1344:             }
                   1345:         }
                   1346:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1347:             ($is_balancer,$currtargets,$currrules) = 
                   1348:                 &check_balancer_result($result,@hosts);
                   1349:             if ($is_balancer) {
1.1129    raeburn  1350:                 if (ref($currrules) eq 'HASH') {
                   1351:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1352:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1353:                     }
                   1354:                 }
                   1355:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1356:                                                        $uname,$udom);
                   1357:             }
                   1358:         } else {
                   1359:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1360:                 $is_balancer = 1;
                   1361:                 $offloadto = &this_host_spares($dom_in_use);
                   1362:             }
                   1363:         }
                   1364:     } else {
                   1365:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1366:             $is_balancer = 1;
                   1367:             $offloadto = &this_host_spares($dom_in_use);
                   1368:         }
                   1369:     }
1.1176    raeburn  1370:     if ($is_balancer) {
                   1371:         my $lowest_load = 30000;
                   1372:         if (ref($offloadto) eq 'HASH') {
                   1373:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1374:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1375:                     ($otherserver,$lowest_load) =
                   1376:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1377:                 }
1.1129    raeburn  1378:             }
1.1176    raeburn  1379:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1380: 
1.1176    raeburn  1381:             if (!$found_server) {
                   1382:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1383:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1384:                         ($otherserver,$lowest_load) =
                   1385:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1386:                     }
                   1387:                 }
                   1388:             }
                   1389:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1390:             if (@{$offloadto} == 1) {
                   1391:                 $otherserver = $offloadto->[0];
                   1392:             } elsif (@{$offloadto} > 1) {
                   1393:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1394:                     ($otherserver,$lowest_load) =
                   1395:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1396:                 }
                   1397:             }
                   1398:         }
1.1176    raeburn  1399:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1400:             $is_balancer = 0;
                   1401:             if ($uname ne '' && $udom ne '') {
                   1402:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1403:                     
                   1404:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1405:                              'user.loadbalcheck.time' => time});
                   1406:                 }
1.1129    raeburn  1407:             }
                   1408:         }
                   1409:     }
                   1410:     return ($is_balancer,$otherserver);
                   1411: }
                   1412: 
1.1191    raeburn  1413: sub check_balancer_result {
                   1414:     my ($result,@hosts) = @_;
                   1415:     my ($is_balancer,$currtargets,$currrules);
                   1416:     if (ref($result) eq 'HASH') {
                   1417:         if ($result->{'lonhost'} ne '') {
                   1418:             my $currbalancer = $result->{'lonhost'};
                   1419:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1420:                 $is_balancer = 1;
                   1421:                 $currtargets = $result->{'targets'};
                   1422:                 $currrules = $result->{'rules'};
                   1423:             }
                   1424:         } else {
                   1425:             foreach my $key (keys(%{$result})) {
                   1426:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1427:                     (ref($result->{$key}) eq 'HASH')) {
                   1428:                     $is_balancer = 1;
                   1429:                     $currrules = $result->{$key}{'rules'};
                   1430:                     $currtargets = $result->{$key}{'targets'};
                   1431:                     last;
                   1432:                 }
                   1433:             }
                   1434:         }
                   1435:     }
                   1436:     return ($is_balancer,$currtargets,$currrules);
                   1437: }
                   1438: 
1.1129    raeburn  1439: sub get_loadbalancer_targets {
                   1440:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1441:     my $offloadto;
1.1175    raeburn  1442:     if ($rule_in_effect eq 'none') {
                   1443:         return [$perlvar{'lonHostID'}];
                   1444:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1445:         $offloadto = $currtargets;
                   1446:     } else {
                   1447:         if ($rule_in_effect eq 'homeserver') {
                   1448:             my $homeserver = &homeserver($uname,$udom);
                   1449:             if ($homeserver ne 'no_host') {
                   1450:                 $offloadto = [$homeserver];
                   1451:             }
                   1452:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1453:             my %domconfig =
                   1454:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1455:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1456:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1457:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1458:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1459:                     }
                   1460:                 }
                   1461:             } else {
1.1178    raeburn  1462:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1463:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1464:                 if (&hostname($remotebalancer) ne '') {
                   1465:                     $offloadto = [$remotebalancer];
                   1466:                 }
                   1467:             }
                   1468:         } elsif (&hostname($rule_in_effect) ne '') {
                   1469:             $offloadto = [$rule_in_effect];
                   1470:         }
                   1471:     }
                   1472:     return $offloadto;
                   1473: }
                   1474: 
1.1127    raeburn  1475: sub internet_dom_servers {
                   1476:     my ($dom) = @_;
                   1477:     my (%uniqservers,%servers);
                   1478:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1479:     my @machinedoms = &machine_domains($primaryserver);
                   1480:     foreach my $mdom (@machinedoms) {
                   1481:         my %currservers = %servers;
                   1482:         my %server = &get_servers($mdom);
                   1483:         %servers = (%currservers,%server);
                   1484:     }
                   1485:     my %by_hostname;
                   1486:     foreach my $id (keys(%servers)) {
                   1487:         push(@{$by_hostname{$servers{$id}}},$id);
                   1488:     }
                   1489:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1490:         if (@{$by_hostname{$hostname}} > 1) {
                   1491:             my $match = 0;
                   1492:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1493:                 if (&host_domain($id) eq $dom) {
                   1494:                     $uniqservers{$id} = $hostname;
                   1495:                     $match = 1;
                   1496:                 }
                   1497:             }
                   1498:             unless ($match) {
                   1499:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1500:             }
                   1501:         } else {
                   1502:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1503:         }
                   1504:     }
                   1505:     return %uniqservers;
                   1506: }
                   1507: 
1.1       albertel 1508: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1509: 
1.599     albertel 1510: my %homecache;
1.1       albertel 1511: sub homeserver {
1.230     stredwic 1512:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1513:     my $index="$uname:$udom";
1.426     albertel 1514: 
1.599     albertel 1515:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1516: 
                   1517:     my %servers = &get_servers($udom,'library');
                   1518:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1519:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1520: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1521: 
                   1522: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1523: 	if ($answer eq 'found') {
                   1524: 	    delete($badServerCache{$tryserver}); 
                   1525: 	    return $homecache{$index}=$tryserver;
                   1526: 	} elsif ($answer eq 'no_host') {
                   1527: 	    $badServerCache{$tryserver}=1;
                   1528: 	}
1.1       albertel 1529:     }    
                   1530:     return 'no_host';
1.70      www      1531: }
                   1532: 
                   1533: # ------------------------------------- Find the usernames behind a list of IDs
                   1534: 
                   1535: sub idget {
                   1536:     my ($udom,@ids)=@_;
                   1537:     my %returnhash=();
                   1538:     
1.841     albertel 1539:     my %servers = &get_servers($udom,'library');
                   1540:     foreach my $tryserver (keys(%servers)) {
                   1541: 	my $idlist=join('&',@ids);
                   1542: 	$idlist=~tr/A-Z/a-z/; 
                   1543: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1544: 	my @answer=();
                   1545: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1546: 	    @answer=split(/\&/,$reply);
                   1547: 	}                    ;
                   1548: 	my $i;
                   1549: 	for ($i=0;$i<=$#ids;$i++) {
                   1550: 	    if ($answer[$i]) {
                   1551: 		$returnhash{$ids[$i]}=$answer[$i];
                   1552: 	    } 
                   1553: 	}
                   1554:     } 
1.70      www      1555:     return %returnhash;
                   1556: }
                   1557: 
                   1558: # ------------------------------------- Find the IDs behind a list of usernames
                   1559: 
                   1560: sub idrget {
                   1561:     my ($udom,@unames)=@_;
                   1562:     my %returnhash=();
1.800     albertel 1563:     foreach my $uname (@unames) {
                   1564:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1565:     }
1.70      www      1566:     return %returnhash;
                   1567: }
                   1568: 
                   1569: # ------------------------------- Store away a list of names and associated IDs
                   1570: 
                   1571: sub idput {
                   1572:     my ($udom,%ids)=@_;
                   1573:     my %servers=();
1.800     albertel 1574:     foreach my $uname (keys(%ids)) {
                   1575: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1576:         my $uhom=&homeserver($uname,$udom);
1.70      www      1577:         if ($uhom ne 'no_host') {
1.800     albertel 1578:             my $id=&escape($ids{$uname});
1.70      www      1579:             $id=~tr/A-Z/a-z/;
1.800     albertel 1580:             my $esc_unam=&escape($uname);
1.70      www      1581: 	    if ($servers{$uhom}) {
1.800     albertel 1582: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1583:             } else {
1.800     albertel 1584:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1585:             }
                   1586:         }
1.191     harris41 1587:     }
1.800     albertel 1588:     foreach my $server (keys(%servers)) {
                   1589:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1590:     }
1.344     www      1591: }
                   1592: 
1.1231    raeburn  1593: # ---------------------------------------- Delete unwanted IDs from ids.db file 
                   1594: 
                   1595: sub iddel {
                   1596:     my ($udom,$idshashref,$uhome)=@_;
                   1597:     my %result=();
                   1598:     unless (ref($idshashref) eq 'HASH') {
                   1599:         return %result;
                   1600:     }
                   1601:     my %servers=();
                   1602:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1603:         my $uhom;
                   1604:         if ($uhome) {
                   1605:             $uhom = $uhome;
                   1606:         } else {
                   1607:             $uhom=&homeserver($uname,$udom);
                   1608:         }
                   1609:         if ($uhom ne 'no_host') {
                   1610:             if ($servers{$uhom}) {
                   1611:                 $servers{$uhom}.='&'.&escape($id);
                   1612:             } else {
                   1613:                 $servers{$uhom}=&escape($id);
                   1614:             }
                   1615:         }
                   1616:     }
                   1617:     foreach my $server (keys(%servers)) {
                   1618:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1619:     }
                   1620:     return %result;
                   1621: }
                   1622: 
1.1023    raeburn  1623: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1624: sub dump_dom {
1.1165    droeschl 1625:     my ($namespace, $udom, $regexp) = @_;
                   1626: 
                   1627:     $udom ||= $env{'user.domain'};
                   1628: 
                   1629:     return () unless $udom;
                   1630: 
                   1631:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1632: }
                   1633: 
1.1023    raeburn  1634: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1635: 
                   1636: sub get_dom {
1.860     raeburn  1637:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1638:     my $items='';
                   1639:     foreach my $item (@$storearr) {
                   1640:         $items.=&escape($item).'&';
                   1641:     }
                   1642:     $items=~s/\&$//;
1.860     raeburn  1643:     if (!$udom) {
                   1644:         $udom=$env{'user.domain'};
                   1645:         if (defined(&domain($udom,'primary'))) {
                   1646:             $uhome=&domain($udom,'primary');
                   1647:         } else {
1.874     albertel 1648:             undef($uhome);
1.860     raeburn  1649:         }
                   1650:     } else {
                   1651:         if (!$uhome) {
                   1652:             if (defined(&domain($udom,'primary'))) {
                   1653:                 $uhome=&domain($udom,'primary');
                   1654:             }
                   1655:         }
                   1656:     }
                   1657:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1658:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1659:         my %returnhash;
1.875     albertel 1660:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1661:             return %returnhash;
                   1662:         }
1.806     raeburn  1663:         my @pairs=split(/\&/,$rep);
                   1664:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1665:             return @pairs;
                   1666:         }
                   1667:         my $i=0;
                   1668:         foreach my $item (@$storearr) {
                   1669:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1670:             $i++;
                   1671:         }
                   1672:         return %returnhash;
                   1673:     } else {
1.880     banghart 1674:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1675:     }
                   1676: }
                   1677: 
                   1678: # -------------------------------------------- put items in domain db files 
                   1679: 
                   1680: sub put_dom {
1.860     raeburn  1681:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1682:     if (!$udom) {
                   1683:         $udom=$env{'user.domain'};
                   1684:         if (defined(&domain($udom,'primary'))) {
                   1685:             $uhome=&domain($udom,'primary');
                   1686:         } else {
1.874     albertel 1687:             undef($uhome);
1.860     raeburn  1688:         }
                   1689:     } else {
                   1690:         if (!$uhome) {
                   1691:             if (defined(&domain($udom,'primary'))) {
                   1692:                 $uhome=&domain($udom,'primary');
                   1693:             }
                   1694:         }
                   1695:     } 
                   1696:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1697:         my $items='';
                   1698:         foreach my $item (keys(%$storehash)) {
                   1699:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1700:         }
                   1701:         $items=~s/\&$//;
                   1702:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1703:     } else {
1.860     raeburn  1704:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1705:     }
                   1706: }
                   1707: 
1.1023    raeburn  1708: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1709: sub newput_dom {
1.1023    raeburn  1710:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1711:     my $result;
                   1712:     if (!$udom) {
                   1713:         $udom=$env{'user.domain'};
                   1714:     }
1.1023    raeburn  1715:     if ($udom) {
                   1716:         my $uname = &get_domainconfiguser($udom);
                   1717:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1718:     }
                   1719:     return $result;
                   1720: }
                   1721: 
1.1023    raeburn  1722: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1723: sub del_dom {
1.1023    raeburn  1724:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1725:     if (ref($storearr) eq 'ARRAY') {
                   1726:         if (!$udom) {
                   1727:             $udom=$env{'user.domain'};
                   1728:         }
1.1023    raeburn  1729:         if ($udom) {
                   1730:             my $uname = &get_domainconfiguser($udom); 
                   1731:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1732:         }
                   1733:     }
                   1734: }
                   1735: 
1.1023    raeburn  1736: # ----------------------------------construct domainconfig user for a domain 
                   1737: sub get_domainconfiguser {
                   1738:     my ($udom) = @_;
                   1739:     return $udom.'-domainconfig';
                   1740: }
                   1741: 
1.837     raeburn  1742: sub retrieve_inst_usertypes {
                   1743:     my ($udom) = @_;
                   1744:     my (%returnhash,@order);
1.989     raeburn  1745:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1746:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1747:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1748:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1749:         @order = @{$domdefs{'inststatusorder'}};
                   1750:     } else {
                   1751:         if (defined(&domain($udom,'primary'))) {
                   1752:             my $uhome=&domain($udom,'primary');
                   1753:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1754:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1755:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1756:                 return (\%returnhash,\@order);
                   1757:             }
                   1758:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1759:             my @pairs=split(/\&/,$hashitems);
                   1760:             foreach my $item (@pairs) {
                   1761:                 my ($key,$value)=split(/=/,$item,2);
                   1762:                 $key = &unescape($key);
                   1763:                 next if ($key =~ /^error: 2 /);
                   1764:                 $returnhash{$key}=&thaw_unescape($value);
                   1765:             }
                   1766:             my @esc_order = split(/\&/,$orderitems);
                   1767:             foreach my $item (@esc_order) {
                   1768:                 push(@order,&unescape($item));
                   1769:             }
                   1770:         } else {
                   1771:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1772:         }
                   1773:     }
                   1774:     return (\%returnhash,\@order);
                   1775: }
                   1776: 
1.868     raeburn  1777: sub is_domainimage {
                   1778:     my ($url) = @_;
                   1779:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1780:         if (&domain($1) ne '') {
                   1781:             return '1';
                   1782:         }
                   1783:     }
                   1784:     return;
                   1785: }
                   1786: 
1.899     raeburn  1787: sub inst_directory_query {
                   1788:     my ($srch) = @_;
                   1789:     my $udom = $srch->{'srchdomain'};
                   1790:     my %results;
                   1791:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1792:     my $outcome;
1.899     raeburn  1793:     if ($homeserver ne '') {
1.904     albertel 1794: 	my $queryid=&reply("querysend:instdirsearch:".
                   1795: 			   &escape($srch->{'srchby'}).':'.
                   1796: 			   &escape($srch->{'srchterm'}).':'.
                   1797: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1798: 	my $host=&hostname($homeserver);
                   1799: 	if ($queryid !~/^\Q$host\E\_/) {
                   1800: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1801: 	    return;
                   1802: 	}
                   1803: 	my $response = &get_query_reply($queryid);
                   1804: 	my $maxtries = 5;
                   1805: 	my $tries = 1;
                   1806: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1807: 	    $response = &get_query_reply($queryid);
                   1808: 	    $tries ++;
                   1809: 	}
                   1810: 
                   1811:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1812:             if ($response eq 'unavailable') {
                   1813:                 $outcome = $response;
                   1814:             } else {
                   1815:                 $outcome = 'ok';
                   1816:                 my @matches = split(/\n/,$response);
                   1817:                 foreach my $match (@matches) {
                   1818:                     my ($key,$value) = split(/=/,$match);
                   1819:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1820:                 }
1.899     raeburn  1821:             }
                   1822:         }
                   1823:     }
1.909     raeburn  1824:     return ($outcome,%results);
1.899     raeburn  1825: }
                   1826: 
                   1827: sub usersearch {
                   1828:     my ($srch) = @_;
                   1829:     my $dom = $srch->{'srchdomain'};
                   1830:     my %results;
                   1831:     my %libserv = &all_library();
                   1832:     my $query = 'usersearch';
                   1833:     foreach my $tryserver (keys(%libserv)) {
                   1834:         if (&host_domain($tryserver) eq $dom) {
                   1835:             my $host=&hostname($tryserver);
                   1836:             my $queryid=
1.911     raeburn  1837:                 &reply("querysend:".&escape($query).':'.
                   1838:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1839:                        &escape($srch->{'srchtype'}).':'.
                   1840:                        &escape($srch->{'srchterm'}),$tryserver);
                   1841:             if ($queryid !~/^\Q$host\E\_/) {
                   1842:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1843:                 next;
1.899     raeburn  1844:             }
                   1845:             my $reply = &get_query_reply($queryid);
                   1846:             my $maxtries = 1;
                   1847:             my $tries = 1;
                   1848:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1849:                 $reply = &get_query_reply($queryid);
                   1850:                 $tries ++;
                   1851:             }
                   1852:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1853:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1854:             } else {
1.911     raeburn  1855:                 my @matches;
                   1856:                 if ($reply =~ /\n/) {
                   1857:                     @matches = split(/\n/,$reply);
                   1858:                 } else {
                   1859:                     @matches = split(/\&/,$reply);
                   1860:                 }
1.899     raeburn  1861:                 foreach my $match (@matches) {
                   1862:                     my ($uname,$udom,%userhash);
1.911     raeburn  1863:                     foreach my $entry (split(/:/,$match)) {
                   1864:                         my ($key,$value) =
                   1865:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1866:                         $userhash{$key} = $value;
                   1867:                         if ($key eq 'username') {
                   1868:                             $uname = $value;
                   1869:                         } elsif ($key eq 'domain') {
                   1870:                             $udom = $value;
1.911     raeburn  1871:                         }
1.899     raeburn  1872:                     }
                   1873:                     $results{$uname.':'.$udom} = \%userhash;
                   1874:                 }
                   1875:             }
                   1876:         }
                   1877:     }
                   1878:     return %results;
                   1879: }
                   1880: 
1.912     raeburn  1881: sub get_instuser {
                   1882:     my ($udom,$uname,$id) = @_;
                   1883:     my $homeserver = &domain($udom,'primary');
                   1884:     my ($outcome,%results);
                   1885:     if ($homeserver ne '') {
                   1886:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1887:                            &escape($id).':'.&escape($udom),$homeserver);
                   1888:         my $host=&hostname($homeserver);
                   1889:         if ($queryid !~/^\Q$host\E\_/) {
                   1890:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1891:             return;
                   1892:         }
                   1893:         my $response = &get_query_reply($queryid);
                   1894:         my $maxtries = 5;
                   1895:         my $tries = 1;
                   1896:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1897:             $response = &get_query_reply($queryid);
                   1898:             $tries ++;
                   1899:         }
                   1900:         if (!&error($response) && $response ne 'refused') {
                   1901:             if ($response eq 'unavailable') {
                   1902:                 $outcome = $response;
                   1903:             } else {
                   1904:                 $outcome = 'ok';
                   1905:                 my @matches = split(/\n/,$response);
                   1906:                 foreach my $match (@matches) {
                   1907:                     my ($key,$value) = split(/=/,$match);
                   1908:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1909:                 }
                   1910:             }
                   1911:         }
                   1912:     }
                   1913:     my %userinfo;
                   1914:     if (ref($results{$uname}) eq 'HASH') {
                   1915:         %userinfo = %{$results{$uname}};
                   1916:     } 
                   1917:     return ($outcome,%userinfo);
                   1918: }
                   1919: 
                   1920: sub inst_rulecheck {
1.923     raeburn  1921:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1922:     my %returnhash;
                   1923:     if ($udom ne '') {
                   1924:         if (ref($rules) eq 'ARRAY') {
                   1925:             @{$rules} = map {&escape($_);} (@{$rules});
                   1926:             my $rulestr = join(':',@{$rules});
                   1927:             my $homeserver=&domain($udom,'primary');
                   1928:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1929:                 my $response;
                   1930:                 if ($item eq 'username') {                
                   1931:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1932:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1933:                                               $homeserver));
1.923     raeburn  1934:                 } elsif ($item eq 'id') {
                   1935:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1936:                                               ':'.&escape($id).':'.$rulestr,
                   1937:                                               $homeserver));
1.945     raeburn  1938:                 } elsif ($item eq 'selfcreate') {
                   1939:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1940:                                                &escape($udom).':'.&escape($uname).
                   1941:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1942:                 }
1.912     raeburn  1943:                 if ($response ne 'refused') {
                   1944:                     my @pairs=split(/\&/,$response);
                   1945:                     foreach my $item (@pairs) {
                   1946:                         my ($key,$value)=split(/=/,$item,2);
                   1947:                         $key = &unescape($key);
                   1948:                         next if ($key =~ /^error: 2 /);
                   1949:                         $returnhash{$key}=&thaw_unescape($value);
                   1950:                     }
                   1951:                 }
                   1952:             }
                   1953:         }
                   1954:     }
                   1955:     return %returnhash;
                   1956: }
                   1957: 
                   1958: sub inst_userrules {
1.923     raeburn  1959:     my ($udom,$check) = @_;
1.912     raeburn  1960:     my (%ruleshash,@ruleorder);
                   1961:     if ($udom ne '') {
                   1962:         my $homeserver=&domain($udom,'primary');
                   1963:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1964:             my $response;
                   1965:             if ($check eq 'id') {
                   1966:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1967:                                  $homeserver);
1.943     raeburn  1968:             } elsif ($check eq 'email') {
                   1969:                 $response=&reply('instemailrules:'.&escape($udom),
                   1970:                                  $homeserver);
1.923     raeburn  1971:             } else {
                   1972:                 $response=&reply('instuserrules:'.&escape($udom),
                   1973:                                  $homeserver);
                   1974:             }
1.912     raeburn  1975:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1976:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1977:                 ($response ne 'no_such_host')) {
                   1978:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1979:                 my @pairs=split(/\&/,$hashitems);
                   1980:                 foreach my $item (@pairs) {
                   1981:                     my ($key,$value)=split(/=/,$item,2);
                   1982:                     $key = &unescape($key);
                   1983:                     next if ($key =~ /^error: 2 /);
                   1984:                     $ruleshash{$key}=&thaw_unescape($value);
                   1985:                 }
                   1986:                 my @esc_order = split(/\&/,$orderitems);
                   1987:                 foreach my $item (@esc_order) {
                   1988:                     push(@ruleorder,&unescape($item));
                   1989:                 }
                   1990:             }
                   1991:         }
                   1992:     }
                   1993:     return (\%ruleshash,\@ruleorder);
                   1994: }
                   1995: 
1.976     raeburn  1996: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1997: 
                   1998: sub get_domain_defaults {
1.1240    raeburn  1999:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2000:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2001:     my $cachetime = 60*60*24;
1.1240    raeburn  2002:     unless ($ignore_cache) {
                   2003:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2004:         if (defined($cached)) {
                   2005:             if (ref($result) eq 'HASH') {
                   2006:                 return %{$result};
                   2007:             }
1.943     raeburn  2008:         }
                   2009:     }
                   2010:     my %domdefaults;
                   2011:     my %domconfig =
1.989     raeburn  2012:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2013:                                   'requestcourses','inststatus',
1.1183    raeburn  2014:                                   'coursedefaults','usersessions',
                   2015:                                   'requestauthor'],$domain);
1.943     raeburn  2016:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2017:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2018:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2019:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2020:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2021:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2022:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2023:     } else {
                   2024:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2025:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2026:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2027:     }
1.976     raeburn  2028:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2029:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2030:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2031:         } else {
                   2032:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2033:         }
1.1177    raeburn  2034:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2035:         foreach my $item (@usertools) {
                   2036:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2037:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2038:             }
                   2039:         }
1.1229    raeburn  2040:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2041:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2042:         }
1.976     raeburn  2043:     }
1.985     raeburn  2044:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246    raeburn  2045:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2046:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2047:         }
                   2048:     }
1.1183    raeburn  2049:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2050:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2051:     }
1.989     raeburn  2052:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2053:         foreach my $item ('inststatustypes','inststatusorder') {
                   2054:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2055:         }
                   2056:     }
1.1047    raeburn  2057:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2058:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216    raeburn  2059:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2060:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2061:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1246    raeburn  2062:             $domdefaults{'textbookcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'textbook'};
1.1216    raeburn  2063:         }
1.1230    raeburn  2064:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2065:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
                   2066:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
1.1246    raeburn  2067:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
                   2068:             $domdefaults{'textbookquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'textbook'};
1.1230    raeburn  2069:         }
1.1047    raeburn  2070:     }
1.1073    raeburn  2071:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2072:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2073:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2074:         }
                   2075:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2076:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2077:         }
                   2078:     }
1.1219    raeburn  2079:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2080:     return %domdefaults;
                   2081: }
                   2082: 
1.344     www      2083: # --------------------------------------------------- Assign a key to a student
                   2084: 
                   2085: sub assign_access_key {
1.364     www      2086: #
                   2087: # a valid key looks like uname:udom#comments
                   2088: # comments are being appended
                   2089: #
1.498     www      2090:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2091:     $kdom=
1.620     albertel 2092:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2093:     $knum=
1.620     albertel 2094:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2095:     $cdom=
1.620     albertel 2096:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2097:     $cnum=
1.620     albertel 2098:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2099:     $udom=$env{'user.name'} unless (defined($udom));
                   2100:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2101:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2102:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2103:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2104:                                                   # assigned to this person
                   2105:                                                   # - this should not happen,
1.345     www      2106:                                                   # unless something went wrong
                   2107:                                                   # the first time around
                   2108: # ready to assign
1.364     www      2109:         $logentry=$1.'; '.$logentry;
1.496     www      2110:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2111:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2112: # key now belongs to user
1.346     www      2113: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2114:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2115:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2116:                 return 'ok';
                   2117:             } else {
                   2118:                 return 
                   2119:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2120: 	    }
                   2121:         } else {
                   2122:             return 'error: Could not assign key, try again later.';
                   2123:         }
1.364     www      2124:     } elsif (!$existing{$ckey}) {
1.345     www      2125: # the key does not exist
                   2126: 	return 'error: The key does not exist';
                   2127:     } else {
                   2128: # the key is somebody else's
                   2129: 	return 'error: The key is already in use';
                   2130:     }
1.344     www      2131: }
                   2132: 
1.364     www      2133: # ------------------------------------------ put an additional comment on a key
                   2134: 
                   2135: sub comment_access_key {
                   2136: #
                   2137: # a valid key looks like uname:udom#comments
                   2138: # comments are being appended
                   2139: #
                   2140:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2141:     $cdom=
1.620     albertel 2142:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2143:     $cnum=
1.620     albertel 2144:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2145:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2146:     if ($existing{$ckey}) {
                   2147:         $existing{$ckey}.='; '.$logentry;
                   2148: # ready to assign
1.367     www      2149:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2150:                                                  $cdom,$cnum) eq 'ok') {
                   2151: 	    return 'ok';
                   2152:         } else {
                   2153: 	    return 'error: Count not store comment.';
                   2154:         }
                   2155:     } else {
                   2156: # the key does not exist
                   2157: 	return 'error: The key does not exist';
                   2158:     }
                   2159: }
                   2160: 
1.344     www      2161: # ------------------------------------------------------ Generate a set of keys
                   2162: 
                   2163: sub generate_access_keys {
1.364     www      2164:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2165:     $cdom=
1.620     albertel 2166:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2167:     $cnum=
1.620     albertel 2168:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2169:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2170:     unless (($cdom) && ($cnum)) { return 0; }
                   2171:     if ($number>10000) { return 0; }
                   2172:     sleep(2); # make sure don't get same seed twice
                   2173:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2174:     my $total=0;
                   2175:     for (my $i=1;$i<=$number;$i++) {
                   2176:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2177:                   sprintf("%lx",int(100000*rand)).'-'.
                   2178:                   sprintf("%lx",int(100000*rand));
                   2179:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2180:        $newkey=~s/0/h/g; # and also 0 and O
                   2181:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2182:        if ($existing{$newkey}) {
                   2183:            $i--;
                   2184:        } else {
1.364     www      2185: 	  if (&put('accesskeys',
                   2186:               { $newkey => '# generated '.localtime().
1.620     albertel 2187:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2188:                            '; '.$logentry },
                   2189: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2190:               $total++;
                   2191: 	  }
                   2192:        }
                   2193:     }
1.620     albertel 2194:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2195:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2196:     return $total;
                   2197: }
                   2198: 
                   2199: # ------------------------------------------------------- Validate an accesskey
                   2200: 
                   2201: sub validate_access_key {
                   2202:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2203:     $cdom=
1.620     albertel 2204:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2205:     $cnum=
1.620     albertel 2206:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2207:     $udom=$env{'user.domain'} unless (defined($udom));
                   2208:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2209:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2210:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2211: }
                   2212: 
                   2213: # ------------------------------------- Find the section of student in a course
1.652     albertel 2214: sub devalidate_getsection_cache {
                   2215:     my ($udom,$unam,$courseid)=@_;
                   2216:     my $hashid="$udom:$unam:$courseid";
                   2217:     &devalidate_cache_new('getsection',$hashid);
                   2218: }
1.298     matthew  2219: 
1.815     albertel 2220: sub courseid_to_courseurl {
                   2221:     my ($courseid) = @_;
                   2222:     #already url style courseid
                   2223:     return $courseid if ($courseid =~ m{^/});
                   2224: 
                   2225:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2226: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2227: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2228: 	return "/$cdom/$cnum";
                   2229:     }
                   2230: 
                   2231:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2232:     if (exists($courseinfo{'num'})) {
                   2233: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2234:     }
                   2235: 
                   2236:     return undef;
                   2237: }
                   2238: 
1.298     matthew  2239: sub getsection {
                   2240:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2241:     my $cachetime=1800;
1.551     albertel 2242: 
                   2243:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2244:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2245:     if (defined($cached)) { return $result; }
                   2246: 
1.298     matthew  2247:     my %Pending; 
                   2248:     my %Expired;
                   2249:     #
                   2250:     # Each role can either have not started yet (pending), be active, 
                   2251:     #    or have expired.
                   2252:     #
                   2253:     # If there is an active role, we are done.
                   2254:     #
                   2255:     # If there is more than one role which has not started yet, 
                   2256:     #     choose the one which will start sooner
                   2257:     # If there is one role which has not started yet, return it.
                   2258:     #
                   2259:     # If there is more than one expired role, choose the one which ended last.
                   2260:     # If there is a role which has expired, return it.
                   2261:     #
1.815     albertel 2262:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2263:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2264:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2265:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2266:         my $section=$1;
                   2267:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2268:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2269:         my $now=time;
1.548     albertel 2270:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2271:             $Expired{$end}=$section;
                   2272:             next;
                   2273:         }
1.548     albertel 2274:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2275:             $Pending{$start}=$section;
                   2276:             next;
                   2277:         }
1.599     albertel 2278:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2279:     }
                   2280:     #
                   2281:     # Presumedly there will be few matching roles from the above
                   2282:     # loop and the sorting time will be negligible.
                   2283:     if (scalar(keys(%Pending))) {
                   2284:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2285:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2286:     } 
                   2287:     if (scalar(keys(%Expired))) {
                   2288:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2289:         my $time = pop(@sorted);
1.599     albertel 2290:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2291:     }
1.599     albertel 2292:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2293: }
1.70      www      2294: 
1.599     albertel 2295: sub save_cache {
                   2296:     &purge_remembered();
1.722     albertel 2297:     #&Apache::loncommon::validate_page();
1.620     albertel 2298:     undef(%env);
1.780     albertel 2299:     undef($env_loaded);
1.599     albertel 2300: }
1.452     albertel 2301: 
1.599     albertel 2302: my $to_remember=-1;
                   2303: my %remembered;
                   2304: my %accessed;
                   2305: my $kicks=0;
                   2306: my $hits=0;
1.849     albertel 2307: sub make_key {
                   2308:     my ($name,$id) = @_;
1.872     albertel 2309:     if (length($id) > 65 
                   2310: 	&& length(&escape($id)) > 200) {
                   2311: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2312:     }
1.849     albertel 2313:     return &escape($name.':'.$id);
                   2314: }
                   2315: 
1.599     albertel 2316: sub devalidate_cache_new {
                   2317:     my ($name,$id,$debug) = @_;
                   2318:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2319:     $id=&make_key($name,$id);
1.599     albertel 2320:     $memcache->delete($id);
                   2321:     delete($remembered{$id});
                   2322:     delete($accessed{$id});
                   2323: }
                   2324: 
                   2325: sub is_cached_new {
                   2326:     my ($name,$id,$debug) = @_;
1.849     albertel 2327:     $id=&make_key($name,$id);
1.599     albertel 2328:     if (exists($remembered{$id})) {
1.1133    foxr     2329: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2330: 	$accessed{$id}=[&gettimeofday()];
                   2331: 	$hits++;
                   2332: 	return ($remembered{$id},1);
                   2333:     }
                   2334:     my $value = $memcache->get($id);
                   2335:     if (!(defined($value))) {
                   2336: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2337: 	return (undef,undef);
1.416     albertel 2338:     }
1.599     albertel 2339:     if ($value eq '__undef__') {
                   2340: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2341: 	$value=undef;
                   2342:     }
                   2343:     &make_room($id,$value,$debug);
                   2344:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2345:     return ($value,1);
                   2346: }
                   2347: 
                   2348: sub do_cache_new {
                   2349:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2350:     $id=&make_key($name,$id);
1.599     albertel 2351:     my $setvalue=$value;
                   2352:     if (!defined($setvalue)) {
                   2353: 	$setvalue='__undef__';
                   2354:     }
1.623     albertel 2355:     if (!defined($time) ) {
                   2356: 	$time=600;
                   2357:     }
1.599     albertel 2358:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2359:     my $result = $memcache->set($id,$setvalue,$time);
                   2360:     if (! $result) {
1.872     albertel 2361: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2362: 	$memcache->disconnect_all();
1.872     albertel 2363:     }
1.600     albertel 2364:     # need to make a copy of $value
1.919     albertel 2365:     &make_room($id,$value,$debug);
1.599     albertel 2366:     return $value;
                   2367: }
                   2368: 
                   2369: sub make_room {
                   2370:     my ($id,$value,$debug)=@_;
1.919     albertel 2371: 
                   2372:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2373:                                     : $value;
1.599     albertel 2374:     if ($to_remember<0) { return; }
                   2375:     $accessed{$id}=[&gettimeofday()];
                   2376:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2377:     my $to_kick;
                   2378:     my $max_time=0;
                   2379:     foreach my $other (keys(%accessed)) {
                   2380: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2381: 	    $to_kick=$other;
                   2382: 	    $max_time=&tv_interval($accessed{$other});
                   2383: 	}
                   2384:     }
                   2385:     delete($remembered{$to_kick});
                   2386:     delete($accessed{$to_kick});
                   2387:     $kicks++;
                   2388:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2389:     return;
                   2390: }
                   2391: 
1.599     albertel 2392: sub purge_remembered {
1.604     albertel 2393:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2394:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2395:     undef(%remembered);
                   2396:     undef(%accessed);
1.428     albertel 2397: }
1.70      www      2398: # ------------------------------------- Read an entry from a user's environment
                   2399: 
                   2400: sub userenvironment {
                   2401:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2402:     my $items;
                   2403:     foreach my $item (@what) {
                   2404:         $items.=&escape($item).'&';
                   2405:     }
                   2406:     $items=~s/\&$//;
1.70      www      2407:     my %returnhash=();
1.1009    raeburn  2408:     my $uhome = &homeserver($unam,$udom);
                   2409:     unless ($uhome eq 'no_host') {
                   2410:         my @answer=split(/\&/, 
                   2411:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2412:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2413:             return %returnhash;
                   2414:         }
1.1009    raeburn  2415:         my $i;
                   2416:         for ($i=0;$i<=$#what;$i++) {
                   2417: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2418:         }
1.70      www      2419:     }
                   2420:     return %returnhash;
1.1       albertel 2421: }
                   2422: 
1.617     albertel 2423: # ---------------------------------------------------------- Get a studentphoto
                   2424: sub studentphoto {
                   2425:     my ($udom,$unam,$ext) = @_;
                   2426:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2427:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2428:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2429:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2430:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2431:             } else {
                   2432:                 my ($result,$perm_reqd)=
1.707     albertel 2433: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2434:                 if ($result eq 'ok') {
                   2435:                     if (!($perm_reqd eq 'yes')) {
                   2436:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2437:                     }
                   2438:                 }
                   2439:             }
                   2440:         }
                   2441:     } else {
                   2442:         my ($result,$perm_reqd) = 
1.707     albertel 2443: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2444:         if ($result eq 'ok') {
                   2445:             if (!($perm_reqd eq 'yes')) {
                   2446:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2447:             }
                   2448:         }
                   2449:     }
                   2450:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2451: }
                   2452: 
                   2453: sub retrievestudentphoto {
                   2454:     my ($udom,$unam,$ext,$type) = @_;
                   2455:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2456:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2457:     if ($ret eq 'ok') {
                   2458:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2459:         if ($type eq 'thumbnail') {
                   2460:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2461:         }
                   2462:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2463:         return $tokenurl;
                   2464:     } else {
                   2465:         if ($type eq 'thumbnail') {
                   2466:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2467:         } else { 
                   2468:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2469:         }
1.617     albertel 2470:     }
                   2471: }
                   2472: 
1.263     www      2473: # -------------------------------------------------------------------- New chat
                   2474: 
                   2475: sub chatsend {
1.724     raeburn  2476:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2477:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2478:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2479:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2480:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2481: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2482: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2483: }
                   2484: 
                   2485: # ------------------------------------------ Find current version of a resource
                   2486: 
                   2487: sub getversion {
                   2488:     my $fname=&clutter(shift);
1.1189    raeburn  2489:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2490:     return &currentversion(&filelocation('',$fname));
                   2491: }
                   2492: 
                   2493: sub currentversion {
                   2494:     my $fname=shift;
                   2495:     my $author=$fname;
                   2496:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2497:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2498:     my $home=&homeserver($uname,$udom);
1.292     www      2499:     if ($home eq 'no_host') { 
                   2500:         return -1; 
                   2501:     }
1.1112    www      2502:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2503:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2504: 	return -1;
                   2505:     }
1.1112    www      2506:     return $answer;
1.263     www      2507: }
                   2508: 
1.1111    www      2509: #
                   2510: # Return special version number of resource if set by override, empty otherwise
                   2511: #
                   2512: sub usedversion {
                   2513:     my $fname=shift;
                   2514:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2515:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2516:     if ($urlversion) { return $urlversion; }
                   2517:     return '';
                   2518: }
                   2519: 
1.1       albertel 2520: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2521: 
1.1       albertel 2522: sub subscribe {
                   2523:     my $fname=shift;
1.761     raeburn  2524:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2525:     $fname=~s/[\n\r]//g;
1.1       albertel 2526:     my $author=$fname;
                   2527:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2528:     my ($udom,$uname)=split(/\//,$author);
                   2529:     my $home=homeserver($uname,$udom);
1.335     albertel 2530:     if ($home eq 'no_host') {
                   2531:         return 'not_found';
1.1       albertel 2532:     }
                   2533:     my $answer=reply("sub:$fname",$home);
1.64      www      2534:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2535: 	$answer.=' by '.$home;
                   2536:     }
1.1       albertel 2537:     return $answer;
                   2538: }
                   2539:     
1.8       www      2540: # -------------------------------------------------------------- Replicate file
                   2541: 
                   2542: sub repcopy {
                   2543:     my $filename=shift;
1.23      www      2544:     $filename=~s/\/+/\//g;
1.1142    raeburn  2545:     my $londocroot = $perlvar{'lonDocRoot'};
                   2546:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2547:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2548:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2549: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2550: 	return &repcopy_userfile($filename);
                   2551:     }
1.532     albertel 2552:     $filename=~s/[\n\r]//g;
1.8       www      2553:     my $transname="$filename.in.transfer";
1.828     www      2554: # FIXME: this should flock
1.607     raeburn  2555:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2556:     my $remoteurl=subscribe($filename);
1.64      www      2557:     if ($remoteurl =~ /^con_lost by/) {
                   2558: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2559:            return 'unavailable';
1.8       www      2560:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2561: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2562: 	   return 'not_found';
1.64      www      2563:     } elsif ($remoteurl =~ /^rejected by/) {
                   2564: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2565:            return 'forbidden';
1.20      www      2566:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2567:            return 'ok';
1.8       www      2568:     } else {
1.290     www      2569:         my $author=$filename;
                   2570:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2571:         my ($udom,$uname)=split(/\//,$author);
                   2572:         my $home=homeserver($uname,$udom);
                   2573:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2574:            my @parts=split(/\//,$filename);
                   2575:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2576:            if ($path ne "$londocroot/res") {
1.8       www      2577:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2578: 	       return 'bad_request';
1.8       www      2579:            }
                   2580:            my $count;
                   2581:            for ($count=5;$count<$#parts;$count++) {
                   2582:                $path.="/$parts[$count]";
                   2583:                if ((-e $path)!=1) {
                   2584: 		   mkdir($path,0777);
                   2585:                }
                   2586:            }
                   2587:            my $ua=new LWP::UserAgent;
                   2588:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2589:            my $response=$ua->request($request,$transname);
                   2590:            if ($response->is_error()) {
                   2591: 	       unlink($transname);
                   2592:                my $message=$response->status_line;
1.672     albertel 2593:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2594:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2595:                return 'unavailable';
1.8       www      2596:            } else {
1.16      www      2597: 	       if ($remoteurl!~/\.meta$/) {
                   2598:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2599:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2600:                   if ($mresponse->is_error()) {
                   2601: 		      unlink($filename.'.meta');
                   2602:                       &logthis(
1.672     albertel 2603:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2604:                   }
                   2605: 	       }
1.8       www      2606:                rename($transname,$filename);
1.607     raeburn  2607:                return 'ok';
1.8       www      2608:            }
1.290     www      2609:        }
1.8       www      2610:     }
1.330     www      2611: }
                   2612: 
                   2613: # ------------------------------------------------ Get server side include body
                   2614: sub ssi_body {
1.381     albertel 2615:     my ($filelink,%form)=@_;
1.606     matthew  2616:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2617:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2618:     }
1.953     www      2619:     my $output='';
                   2620:     my $response;
1.980     raeburn  2621:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2622:        ($output,$response)=&externalssi($filelink);
1.953     www      2623:     } else {
1.1004    droeschl 2624:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2625:        $filelink .= 'inhibitmenu=yes';
1.953     www      2626:        ($output,$response)=&ssi($filelink,%form);
                   2627:     }
1.778     albertel 2628:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2629:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2630:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2631:     if (wantarray) {
                   2632:         return ($output, $response);
                   2633:     } else {
                   2634:         return $output;
                   2635:     }
1.8       www      2636: }
                   2637: 
1.15      www      2638: # --------------------------------------------------------- Server Side Include
                   2639: 
1.782     albertel 2640: sub absolute_url {
                   2641:     my ($host_name) = @_;
                   2642:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2643:     if ($host_name eq '') {
                   2644: 	$host_name = $ENV{'SERVER_NAME'};
                   2645:     }
                   2646:     return $protocol.$host_name;
                   2647: }
                   2648: 
1.942     foxr     2649: #
                   2650: #   Server side include.
                   2651: # Parameters:
                   2652: #  fn     Possibly encrypted resource name/id.
                   2653: #  form   Hash that describes how the rendering should be done
                   2654: #         and other things.
1.944     foxr     2655: # Returns:
1.950     raeburn  2656: #   Scalar context: The content of the response.
                   2657: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2658: #     
1.15      www      2659: sub ssi {
                   2660: 
1.944     foxr     2661:     my ($fn,%form)=@_;
1.15      www      2662:     my $ua=new LWP::UserAgent;
1.23      www      2663:     my $request;
1.711     albertel 2664: 
                   2665:     $form{'no_update_last_known'}=1;
1.895     albertel 2666:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2667:     if (%form) {
1.782     albertel 2668:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2669:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2670:     } else {
1.782     albertel 2671:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2672:     }
                   2673: 
1.15      www      2674:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2675:     my $response= $ua->request($request);
1.1182    foxr     2676:     my $content = $response->content;
                   2677: 
                   2678: 
1.944     foxr     2679:     if (wantarray) {
1.1173    foxr     2680: 	return ($content, $response);
1.944     foxr     2681:     } else {
1.1173    foxr     2682: 	return $content;
1.942     foxr     2683:     }
1.324     www      2684: }
                   2685: 
                   2686: sub externalssi {
                   2687:     my ($url)=@_;
                   2688:     my $ua=new LWP::UserAgent;
                   2689:     my $request=new HTTP::Request('GET',$url);
                   2690:     my $response=$ua->request($request);
1.954     raeburn  2691:     if (wantarray) {
                   2692:         return ($response->content, $response);
                   2693:     } else {
                   2694:         return $response->content;
                   2695:     }
1.15      www      2696: }
1.254     www      2697: 
1.492     albertel 2698: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2699: 
                   2700: sub allowuploaded {
                   2701:     my ($srcurl,$url)=@_;
                   2702:     $url=&clutter(&declutter($url));
                   2703:     my $dir=$url;
                   2704:     $dir=~s/\/[^\/]+$//;
                   2705:     my %httpref=();
                   2706:     my $httpurl=&hreflocation('',$url);
                   2707:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2708:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2709: }
1.477     raeburn  2710: 
1.1193    raeburn  2711: #
                   2712: # Determine if the current user should be able to edit a particular resource,
                   2713: # when viewing in course context.
                   2714: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2715: #     Functions.
                   2716: # (b) When displaying folder contents in course editor, used to determine if
                   2717: #     "Edit" link will be displayed alongside resource.
                   2718: #
1.1196    raeburn  2719: #  input: six args -- filename (decluttered), course number, course domain,
                   2720: #                   url, symb (if registered) and group (if this is a group
                   2721: #                   item -- e.g., bulletin board, group page etc.).
                   2722: #  output: array of five scalars -- 
1.1193    raeburn  2723: #          $cfile -- url for file editing if editable on current server
                   2724: #          $home -- homeserver of resource (i.e., for author if published,
                   2725: #                                           or course if uploaded.).
                   2726: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2727: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2728: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2729: #
                   2730: 
                   2731: sub can_edit_resource {
1.1194    raeburn  2732:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2733:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2734: #
                   2735: # For aboutme pages user can only edit his/her own.
                   2736: #
1.1199    raeburn  2737:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2738:         my ($sdom,$sname) = ($1,$2);
                   2739:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2740:             $home = $env{'user.home'};
                   2741:             $cfile = $resurl;
                   2742:             if ($env{'form.forceedit'}) {
                   2743:                 $forceview = 1;
                   2744:             } else {
                   2745:                 $forceedit = 1;
                   2746:             }
                   2747:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2748:         } else {
                   2749:             return;
                   2750:         }
                   2751:     }
                   2752: 
                   2753:     if ($env{'request.course.id'}) {
                   2754:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2755:         if ($group ne '') {
                   2756: # if this is a group homepage or group bulletin board, check group privs
                   2757:             my $allowed = 0;
1.1197    raeburn  2758:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2759:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2760:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2761:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2762:                     $allowed = 1;
                   2763:                 }
1.1197    raeburn  2764:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2765:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2766:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2767:                     $allowed = 1;
                   2768:                 }
                   2769:             }
                   2770:             if ($allowed) {
                   2771:                 $home=&homeserver($cnum,$cdom);
                   2772:                 if ($env{'form.forceedit'}) {
                   2773:                     $forceview = 1;
                   2774:                 } else {
                   2775:                     $forceedit = 1;
                   2776:                 }
                   2777:                 $cfile = $resurl;
                   2778:             } else {
                   2779:                 return;
                   2780:             }
                   2781:         } else {
1.1208    raeburn  2782:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2783:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2784:                     return;
                   2785:                 }
                   2786:             } elsif (!$crsedit) {
1.1194    raeburn  2787: #
                   2788: # No edit allowed where CC has switched to student role.
                   2789: #
                   2790:                 return;
                   2791:             }
                   2792:         }
                   2793:     }
                   2794: 
1.1193    raeburn  2795:     if ($file ne '') {
                   2796:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2797:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2798:                 $uploaded = 1;
                   2799:                 $incourse = 1;
1.1193    raeburn  2800:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2801:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2802:                     if ($env{'form.forceedit'}) {
                   2803:                         $forceview = 1;
                   2804:                     } else {
                   2805:                         $forceedit = 1;
                   2806:                     }
1.1194    raeburn  2807:                 }
                   2808:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2809:                 $incourse = 1;
                   2810:                 if ($env{'form.forceedit'}) {
                   2811:                     $forceview = 1;
                   2812:                 } else {
                   2813:                     $forceedit = 1;
                   2814:                 }
                   2815:                 $cfile = $resurl;
                   2816:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2817:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2818:                     $incourse = 1;
                   2819:                     if ($env{'form.forceedit'}) {
                   2820:                         $forceview = 1;
                   2821:                     } else {
                   2822:                         $forceedit = 1;
                   2823:                     }
                   2824:                     $cfile = $resurl;
1.1199    raeburn  2825:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2826:                     $incourse = 1;
                   2827:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2828:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2829:                     $incourse = 1;
1.1199    raeburn  2830:                     if ($env{'form.forceedit'}) {
                   2831:                         $forceview = 1;
                   2832:                     } else {
                   2833:                         $forceedit = 1;
                   2834:                     }
                   2835:                     $cfile = $resurl;
1.1208    raeburn  2836:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2837:                     $incourse = 1;
                   2838:                     if ($env{'form.forceedit'}) {
                   2839:                         $forceview = 1;
                   2840:                     } else {
                   2841:                         $forceedit = 1;
                   2842:                     }
                   2843:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2844:                 }
                   2845:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2846:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2847:                 if (&is_on_map($template)) { 
                   2848:                     $incourse = 1;
                   2849:                     $forceview = 1;
                   2850:                     $cfile = $template;
1.1193    raeburn  2851:                 }
1.1199    raeburn  2852:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2853:                     $incourse = 1;
                   2854:                     if ($env{'form.forceedit'}) {
                   2855:                         $forceview = 1;
                   2856:                     } else {
                   2857:                         $forceedit = 1;
                   2858:                     }
                   2859:                     $cfile = $resurl;
                   2860:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2861:                 $incourse = 1;
                   2862:                 $forceview = 1;
                   2863:                 if ($symb) {
                   2864:                     my ($map,$id,$res)=&decode_symb($symb);
                   2865:                     $env{'request.symb'} = $symb;
                   2866:                     $cfile = &clutter($res);
                   2867:                 } else {
                   2868:                     $cfile = $env{'form.suppurl'};
                   2869:                     $cfile =~ s{^http://}{};
                   2870:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2871:                 }
1.1234    raeburn  2872:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2873:                 if ($env{'form.forceedit'}) {
                   2874:                     $forceview = 1;
                   2875:                 } else {
                   2876:                     $forceedit = 1;
                   2877:                 }
                   2878:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  2879:             }
                   2880:         }
1.1194    raeburn  2881:         if ($uploaded || $incourse) {
                   2882:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  2883:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  2884:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2885:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2886:             # Check that the user has permission to edit this resource
                   2887:             my $setpriv = 1;
                   2888:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2889:             if (defined($cfudom)) {
                   2890:                 $home=&homeserver($cfuname,$cfudom);
                   2891:                 $cfile=$file;
                   2892:             }
                   2893:         }
1.1194    raeburn  2894:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   2895:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  2896:             my @ids=&current_machine_ids();
                   2897:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2898:                 $switchserver=1;
                   2899:             }
                   2900:         }
                   2901:     }
1.1194    raeburn  2902:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  2903: }
                   2904: 
                   2905: sub is_course_upload {
                   2906:     my ($file,$cnum,$cdom) = @_;
                   2907:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2908:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  2909:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2910:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  2911:         return 1;
                   2912:     }
                   2913:     return;
                   2914: }
                   2915: 
1.1194    raeburn  2916: sub in_course {
1.1195    raeburn  2917:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2918:     if ($hideprivileged) {
                   2919:         my $skipuser;
1.1219    raeburn  2920:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   2921:         my @possdoms = ($cdom);  
                   2922:         if ($coursehash{'checkforpriv'}) { 
                   2923:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   2924:         }
                   2925:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  2926:             $skipuser = 1;
                   2927:             if ($coursehash{'nothideprivileged'}) {
                   2928:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2929:                     my $user;
                   2930:                     if ($item =~ /:/) {
                   2931:                         $user = $item;
                   2932:                     } else {
                   2933:                         $user = join(':',split(/[\@]/,$item));
                   2934:                     }
                   2935:                     if ($user eq $uname.':'.$udom) {
                   2936:                         undef($skipuser);
                   2937:                         last;
                   2938:                     }
                   2939:                 }
                   2940:             }
                   2941:             if ($skipuser) {
                   2942:                 return 0;
                   2943:             }
                   2944:         }
                   2945:     }
1.1194    raeburn  2946:     $type ||= 'any';
                   2947:     if (!defined($cdom) || !defined($cnum)) {
                   2948:         my $cid  = $env{'request.course.id'};
                   2949:         $cdom = $env{'course.'.$cid.'.domain'};
                   2950:         $cnum = $env{'course.'.$cid.'.num'};
                   2951:     }
                   2952:     my $typesref;
1.1195    raeburn  2953:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  2954:         $typesref = ['active','previous','future'];
                   2955:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2956:         $typesref = [$type];
                   2957:     }
                   2958:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2959:                               $typesref,undef,[$cdom]);
                   2960:     my ($tmp) = keys(%roles);
                   2961:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2962:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2963:     if (@course_roles > 0) {
                   2964:         return 1;
                   2965:     }
                   2966:     return 0;
                   2967: }
                   2968: 
1.478     albertel 2969: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2970: # input: action, courseID, current domain, intended
1.637     raeburn  2971: #        path to file, source of file, instruction to parse file for objects,
                   2972: #        ref to hash for embedded objects,
                   2973: #        ref to hash for codebase of java objects.
1.1095    raeburn  2974: #        reference to scalar to accommodate mime type determined
                   2975: #          from File::MMagic if $parser = parse.
1.637     raeburn  2976: #
1.485     raeburn  2977: # output: url to file (if action was uploaddoc), 
                   2978: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2979: #
1.478     albertel 2980: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2981: # course.
1.477     raeburn  2982: #
1.478     albertel 2983: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2984: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2985: #          course's home server.
1.477     raeburn  2986: #
1.478     albertel 2987: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2988: #          be copied from $source (current location) to 
                   2989: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2990: #         and will then be copied to
                   2991: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2992: #         course's home server.
1.485     raeburn  2993: #
1.481     raeburn  2994: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2995: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2996: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2997: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2998: #         in course's home server.
1.637     raeburn  2999: #
1.477     raeburn  3000: 
                   3001: sub process_coursefile {
1.1095    raeburn  3002:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3003:         $mimetype)=@_;
1.477     raeburn  3004:     my $fetchresult;
1.638     albertel 3005:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3006:     if ($action eq 'propagate') {
1.638     albertel 3007:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3008: 			     $home);
1.481     raeburn  3009:     } else {
1.477     raeburn  3010:         my $fpath = '';
                   3011:         my $fname = $file;
1.478     albertel 3012:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3013:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3014:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3015:         if ($action eq 'copy') {
                   3016:             if ($source eq '') {
                   3017:                 $fetchresult = 'no source file';
                   3018:                 return $fetchresult;
                   3019:             } else {
                   3020:                 my $destination = $filepath.'/'.$fname;
                   3021:                 rename($source,$destination);
                   3022:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3023:                                  $home);
1.481     raeburn  3024:             }
                   3025:         } elsif ($action eq 'uploaddoc') {
                   3026:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3027:             print $fh $env{'form.'.$source};
1.481     raeburn  3028:             close($fh);
1.637     raeburn  3029:             if ($parser eq 'parse') {
1.1024    raeburn  3030:                 my $mm = new File::MMagic;
1.1095    raeburn  3031:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3032:                 if ($type eq 'text/html') {
1.1024    raeburn  3033:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3034:                     unless ($parse_result eq 'ok') {
                   3035:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3036:                     }
1.637     raeburn  3037:                 }
1.1095    raeburn  3038:                 if (ref($mimetype)) {
                   3039:                     $$mimetype = $type;
                   3040:                 } 
1.637     raeburn  3041:             }
1.477     raeburn  3042:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3043:                                  $home);
1.481     raeburn  3044:             if ($fetchresult eq 'ok') {
                   3045:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3046:             } else {
                   3047:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3048:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3049:                 return '/adm/notfound.html';
                   3050:             }
1.477     raeburn  3051:         }
                   3052:     }
1.485     raeburn  3053:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3054:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3055:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3056:     }
                   3057:     return $fetchresult;
                   3058: }
                   3059: 
1.637     raeburn  3060: sub build_filepath {
                   3061:     my ($fpath) = @_;
                   3062:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3063:     unless ($fpath eq '') {
                   3064:         my @parts=split('/',$fpath);
                   3065:         foreach my $part (@parts) {
                   3066:             $filepath.= '/'.$part;
                   3067:             if ((-e $filepath)!=1) {
                   3068:                 mkdir($filepath,0777);
                   3069:             }
                   3070:         }
                   3071:     }
                   3072:     return $filepath;
                   3073: }
                   3074: 
                   3075: sub store_edited_file {
1.638     albertel 3076:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3077:     my $file = $primary_url;
                   3078:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3079:     my $fpath = '';
                   3080:     my $fname = $file;
                   3081:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3082:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3083:     my $filepath = &build_filepath($fpath);
                   3084:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3085:     print $fh $content;
                   3086:     close($fh);
1.638     albertel 3087:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3088:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3089: 			  $home);
1.637     raeburn  3090:     if ($$fetchresult eq 'ok') {
                   3091:         return '/uploaded/'.$fpath.'/'.$fname;
                   3092:     } else {
1.638     albertel 3093:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3094: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3095:         return '/adm/notfound.html';
                   3096:     }
                   3097: }
                   3098: 
1.531     albertel 3099: sub clean_filename {
1.831     albertel 3100:     my ($fname,$args)=@_;
1.315     www      3101: # Replace Windows backslashes by forward slashes
1.257     www      3102:     $fname=~s/\\/\//g;
1.831     albertel 3103:     if (!$args->{'keep_path'}) {
                   3104:         # Get rid of everything but the actual filename
                   3105: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3106:     }
1.315     www      3107: # Replace spaces by underscores
                   3108:     $fname=~s/\s+/\_/g;
                   3109: # Replace all other weird characters by nothing
1.831     albertel 3110:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3111: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3112: # numbers
                   3113:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3114:     return $fname;
                   3115: }
1.1051    raeburn  3116: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3117: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3118: # image with the same aspect ratio as the original, but with dimensions which do 
                   3119: # not exceed $resizewidth and $resizeheight.
                   3120:  
1.984     neumanie 3121: sub resizeImage {
1.1051    raeburn  3122:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3123:     my $ima = Image::Magick->new;
                   3124:     my $resized;
                   3125:     if (-e $img_path) {
                   3126:         $ima->Read($img_path);
                   3127:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3128:             my $width = $ima->Get('width');
                   3129:             my $height = $ima->Get('height');
                   3130:             if ($width > $resizewidth) {
                   3131: 	        my $factor = $width/$resizewidth;
                   3132:                 my $newheight = $height/$factor;
                   3133:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3134:                 $resized = 1;
                   3135:             }
                   3136:         }
                   3137:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3138:             my $width = $ima->Get('width');
                   3139:             my $height = $ima->Get('height');
                   3140:             if ($height > $resizeheight) {
                   3141:                 my $factor = $height/$resizeheight;
                   3142:                 my $newwidth = $width/$factor;
                   3143:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3144:                 $resized = 1;
                   3145:             }
                   3146:         }
                   3147:         if ($resized) {
                   3148:             $ima->Write($img_path);
                   3149:         }
                   3150:     }
                   3151:     return;
1.977     amueller 3152: }
                   3153: 
1.608     albertel 3154: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3155: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3156: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3157: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3158: #                                    canceloverwrite, or ''. 
                   3159: #                   if 'coursedoc': upload to the current course
                   3160: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3161: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3162: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3163: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3164: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3165: #        $allfiles - reference to hash for embedded objects
                   3166: #        $codebase - reference to hash for codebase of java objects
                   3167: #        $desuname - username for permanent storage of uploaded file
                   3168: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3169: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3170: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3171: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3172: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3173: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3174: #                    from File::MMagic.
1.858     raeburn  3175: # 
1.686     albertel 3176: # output: url of file in userspace, or error: <message> 
                   3177: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3178: 
1.531     albertel 3179: sub userfileupload {
1.1090    raeburn  3180:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3181:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3182:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3183:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3184:     $fname=&clean_filename($fname);
1.1090    raeburn  3185:     # See if there is anything left
1.257     www      3186:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3187:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3188:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3189:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3190:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3191:         my $now = time;
1.1090    raeburn  3192:         my $filepath;
1.1095    raeburn  3193:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3194:              $filepath = 'tmp/helprequests/'.$now;
                   3195:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3196:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3197:                          '_'.$env{'user.domain'}.'/pending';
                   3198:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3199:             my ($docuname,$docudom);
                   3200:             if ($destudom) {
                   3201:                 $docudom = $destudom;
                   3202:             } else {
                   3203:                 $docudom = $env{'user.domain'};
                   3204:             }
                   3205:             if ($destuname) {
                   3206:                 $docuname = $destuname;
                   3207:             } else {
                   3208:                 $docuname = $env{'user.name'};
                   3209:             }
                   3210:             if (exists($env{'form.group'})) {
                   3211:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3212:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3213:             }
                   3214:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3215:             if ($context eq 'canceloverwrite') {
                   3216:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3217:                 if (-e  $tempfile) {
                   3218:                     my @info = stat($tempfile);
                   3219:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3220:                         unlink($tempfile);
                   3221:                     }
                   3222:                 }
                   3223:                 return;
1.523     raeburn  3224:             }
                   3225:         }
1.1090    raeburn  3226:         # Create the directory if not present
1.741     raeburn  3227:         my @parts=split(/\//,$filepath);
                   3228:         my $fullpath = $perlvar{'lonDaemons'};
                   3229:         for (my $i=0;$i<@parts;$i++) {
                   3230:             $fullpath .= '/'.$parts[$i];
                   3231:             if ((-e $fullpath)!=1) {
                   3232:                 mkdir($fullpath,0777);
                   3233:             }
                   3234:         }
                   3235:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3236:         print $fh $env{'form.'.$formname};
                   3237:         close($fh);
1.1090    raeburn  3238:         if ($context eq 'existingfile') {
                   3239:             my @info = stat($fullpath.'/'.$fname);
                   3240:             return ($fullpath.'/'.$fname,$info[9]);
                   3241:         } else {
                   3242:             return $fullpath.'/'.$fname;
                   3243:         }
1.523     raeburn  3244:     }
1.995     raeburn  3245:     if ($subdir eq 'scantron') {
                   3246:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3247:     } else {
1.995     raeburn  3248:         $fname="$subdir/$fname";
                   3249:     }
1.1090    raeburn  3250:     if ($context eq 'coursedoc') {
1.638     albertel 3251: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3252: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3253:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3254:             return &finishuserfileupload($docuname,$docudom,
                   3255: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3256: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3257:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3258:         } else {
1.1218    raeburn  3259:             if ($env{'form.folder'}) {
                   3260:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3261:             }
1.638     albertel 3262:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3263: 				       $fname,$formname,$parser,
1.1095    raeburn  3264: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3265:         }
1.719     banghart 3266:     } elsif (defined($destuname)) {
                   3267:         my $docuname=$destuname;
                   3268:         my $docudom=$destudom;
1.860     raeburn  3269: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3270: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3271:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3272:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3273:     } else {
1.638     albertel 3274:         my $docuname=$env{'user.name'};
                   3275:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3276:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3277:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3278:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3279:         }
1.860     raeburn  3280: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3281: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3282:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3283:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3284:     }
1.271     www      3285: }
                   3286: 
                   3287: sub finishuserfileupload {
1.860     raeburn  3288:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3289:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3290:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3291:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3292:   
1.860     raeburn  3293:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3294:     $file=$fname;
                   3295:     if ($fname=~m|/|) {
                   3296:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3297: 	$path.=$fnamepath.'/';
                   3298:     }
1.259     www      3299:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3300:     my $count;
                   3301:     for ($count=4;$count<=$#parts;$count++) {
                   3302:         $filepath.="/$parts[$count]";
                   3303:         if ((-e $filepath)!=1) {
                   3304: 	    mkdir($filepath,0777);
                   3305:         }
                   3306:     }
1.984     neumanie 3307: 
1.258     www      3308: # Save the file
                   3309:     {
1.701     albertel 3310: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3311: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3312: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3313: 	    return '/adm/notfound.html';
                   3314: 	}
1.1090    raeburn  3315:         if ($context eq 'overwrite') {
1.1117    foxr     3316:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3317:             my $target = $filepath.'/'.$file;
                   3318:             if (-e $source) {
                   3319:                 my @info = stat($source);
                   3320:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3321:                     unless (&File::Copy::move($source,$target)) {
                   3322:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3323:                         return "Moving from $source failed";
                   3324:                     }
                   3325:                 } else {
                   3326:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3327:                 }
                   3328:             } else {
                   3329:                 return "Temporary file: $source missing";
                   3330:             }
                   3331:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3332: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3333: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3334: 	    return '/adm/notfound.html';
                   3335: 	}
1.570     albertel 3336: 	close(FH);
1.1051    raeburn  3337:         if ($resizewidth && $resizeheight) {
                   3338:             my $mm = new File::MMagic;
                   3339:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3340:             if ($mime_type =~ m{^image/}) {
                   3341: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3342:             }  
1.977     amueller 3343: 	}
1.258     www      3344:     }
1.1152    raeburn  3345:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3346:         if (ref($mimetype)) {
                   3347:             if ($$mimetype eq '') {
                   3348:                 my $mm = new File::MMagic;
                   3349:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3350:                 $$mimetype = $type;
                   3351:             }
                   3352:         }
                   3353:     }
1.637     raeburn  3354:     if ($parser eq 'parse') {
1.1152    raeburn  3355:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3356:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3357:                                                        $allfiles,$codebase);
                   3358:             unless ($parse_result eq 'ok') {
                   3359:                 &logthis('Failed to parse '.$filepath.$file.
                   3360: 	   	         ' for embedded media: '.$parse_result); 
                   3361:             }
1.637     raeburn  3362:         }
                   3363:     }
1.860     raeburn  3364:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3365:         my $input = $filepath.'/'.$file;
                   3366:         my $output = $filepath.'/'.'tn-'.$file;
                   3367:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3368:         system("convert -sample $thumbsize $input $output");
                   3369:         if (-e $filepath.'/'.'tn-'.$file) {
                   3370:             $fetchthumb  = 1; 
                   3371:         }
                   3372:     }
1.858     raeburn  3373:  
1.259     www      3374: # Notify homeserver to grep it
                   3375: #
1.984     neumanie 3376:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3377:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3378:     if ($fetchresult eq 'ok') {
1.860     raeburn  3379:         if ($fetchthumb) {
                   3380:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3381:             if ($thumbresult ne 'ok') {
                   3382:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3383:                          $docuhome.': '.$thumbresult);
                   3384:             }
                   3385:         }
1.259     www      3386: #
1.258     www      3387: # Return the URL to it
1.494     albertel 3388:         return '/uploaded/'.$path.$file;
1.263     www      3389:     } else {
1.494     albertel 3390:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3391: 		 ': '.$fetchresult);
1.263     www      3392:         return '/adm/notfound.html';
1.858     raeburn  3393:     }
1.493     albertel 3394: }
                   3395: 
1.637     raeburn  3396: sub extract_embedded_items {
1.961     raeburn  3397:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3398:     my @state = ();
1.1164    raeburn  3399:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3400:     my %javafiles = (
                   3401:                       codebase => '',
                   3402:                       code => '',
                   3403:                       archive => ''
                   3404:                     );
                   3405:     my %mediafiles = (
                   3406:                       src => '',
                   3407:                       movie => '',
                   3408:                      );
1.648     raeburn  3409:     my $p;
                   3410:     if ($content) {
                   3411:         $p = HTML::LCParser->new($content);
                   3412:     } else {
1.961     raeburn  3413:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3414:     }
1.641     albertel 3415:     while (my $t=$p->get_token()) {
1.640     albertel 3416: 	if ($t->[0] eq 'S') {
                   3417: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3418: 	    push(@state, $tagname);
1.648     raeburn  3419:             if (lc($tagname) eq 'allow') {
                   3420:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3421:             }
1.640     albertel 3422: 	    if (lc($tagname) eq 'img') {
                   3423: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3424: 	    }
1.886     albertel 3425: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3426:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3427:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3428:                 }
1.886     albertel 3429: 	    }
1.645     raeburn  3430:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3431:                 my $src;
1.645     raeburn  3432:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3433:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3434:                 } else {
1.1164    raeburn  3435:                     if ($attr->{'src'} ne '') {
                   3436:                         $src = $attr->{'src'};
                   3437:                         &add_filetype($allfiles,$src,'src');
                   3438:                     }
                   3439:                 }
                   3440:                 my $text = $p->get_trimmed_text();
                   3441:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3442:                     my @swfargs = split(/,/,$1);
                   3443:                     foreach my $item (@swfargs) {
                   3444:                         $item =~ s/["']//g;
                   3445:                         $item =~ s/^\s+//;
                   3446:                         $item =~ s/\s+$//;
                   3447:                     }
                   3448:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3449:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3450:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3451:                         } else {
                   3452:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3453:                         }
                   3454:                     }
1.645     raeburn  3455:                 }
                   3456:             }
                   3457:             if (lc($tagname) eq 'link') {
                   3458:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3459:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3460:                 }
                   3461:             }
1.640     albertel 3462: 	    if (lc($tagname) eq 'object' ||
                   3463: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3464: 		foreach my $item (keys(%javafiles)) {
                   3465: 		    $javafiles{$item} = '';
                   3466: 		}
1.1164    raeburn  3467:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3468:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3469:                 }
1.640     albertel 3470: 	    }
                   3471: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3472: 		my $name = lc($attr->{'name'});
                   3473: 		foreach my $item (keys(%javafiles)) {
                   3474: 		    if ($name eq $item) {
                   3475: 			$javafiles{$item} = $attr->{'value'};
                   3476: 			last;
                   3477: 		    }
                   3478: 		}
1.1164    raeburn  3479:                 my $pathfrom;
1.640     albertel 3480: 		foreach my $item (keys(%mediafiles)) {
                   3481: 		    if ($name eq $item) {
1.1164    raeburn  3482:                         $pathfrom = $attr->{'value'};
                   3483:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3484: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3485: 			last;
                   3486: 		    }
                   3487: 		}
1.1164    raeburn  3488:                 if ($name eq 'flashvars') {
                   3489:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3490:                 }
                   3491:                 if ($pathfrom ne '') {
                   3492:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3493:                                          $pathfrom);
                   3494:                 }
1.640     albertel 3495: 	    }
                   3496: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3497: 		foreach my $item (keys(%javafiles)) {
                   3498: 		    if ($attr->{$item}) {
                   3499: 			$javafiles{$item} = $attr->{$item};
                   3500: 			last;
                   3501: 		    }
                   3502: 		}
                   3503: 		foreach my $item (keys(%mediafiles)) {
                   3504: 		    if ($attr->{$item}) {
                   3505: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3506: 			last;
                   3507: 		    }
                   3508: 		}
1.1164    raeburn  3509:                 if (lc($tagname) eq 'embed') {
                   3510:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3511:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3512:                                              $attr->{'src'});
                   3513:                     }
                   3514:                 }
1.640     albertel 3515: 	    }
1.1243    raeburn  3516:             if (lc($tagname) eq 'iframe') {
                   3517:                 my $src = $attr->{'src'} ;
                   3518:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3519:                     &add_filetype($allfiles,$src,'src');
                   3520:                 } elsif ($src =~ m{^/}) {
                   3521:                     if ($env{'request.course.id'}) {
                   3522:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3523:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3524:                         my $url = &hreflocation('',$fullpath);
                   3525:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3526:                             my $relpath = $1;
                   3527:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3528:                                 &add_filetype($allfiles,$1,'src');
                   3529:                             }
                   3530:                         }
                   3531:                     }
                   3532:                 }
                   3533:             }
1.1164    raeburn  3534:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3535:                 pop(@state);
1.1164    raeburn  3536:             }
1.640     albertel 3537: 	} elsif ($t->[0] eq 'E') {
                   3538: 	    my ($tagname) = ($t->[1]);
                   3539: 	    if ($javafiles{'codebase'} ne '') {
                   3540: 		$javafiles{'codebase'} .= '/';
                   3541: 	    }  
                   3542: 	    if (lc($tagname) eq 'applet' ||
                   3543: 		lc($tagname) eq 'object' ||
                   3544: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3545: 		) {
                   3546: 		foreach my $item (keys(%javafiles)) {
                   3547: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3548: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3549: 			&add_filetype($allfiles,$file,$item);
                   3550: 		    }
                   3551: 		}
                   3552: 	    } 
                   3553: 	    pop @state;
                   3554: 	}
                   3555:     }
1.1164    raeburn  3556:     foreach my $id (sort(keys(%flashvars))) {
                   3557:         if ($shockwave{$id} ne '') {
                   3558:             my @pairs = split(/\&/,$flashvars{$id});
                   3559:             foreach my $pair (@pairs) {
                   3560:                 my ($key,$value) = split(/\=/,$pair);
                   3561:                 if ($key eq 'thumb') {
                   3562:                     &add_filetype($allfiles,$value,$key);
                   3563:                 } elsif ($key eq 'content') {
                   3564:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3565:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3566:                     if ($ext ne '') {
                   3567:                         &add_filetype($allfiles,$path.$value,$ext);
                   3568:                     }
                   3569:                 }
                   3570:             }
                   3571:         }
                   3572:     }
1.637     raeburn  3573:     return 'ok';
                   3574: }
                   3575: 
1.639     albertel 3576: sub add_filetype {
                   3577:     my ($allfiles,$file,$type)=@_;
                   3578:     if (exists($allfiles->{$file})) {
                   3579: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3580: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3581: 	}
                   3582:     } else {
                   3583: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3584:     }
                   3585: }
                   3586: 
1.1164    raeburn  3587: sub embedded_dependency {
                   3588:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3589:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3590:         if (($identifier ne '') &&
                   3591:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3592:             ($pathfrom ne '')) {
                   3593:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3594:             foreach my $dep (@{$related->{$identifier}}) {
                   3595:                 &add_filetype($allfiles,$path.$dep,'object');
                   3596:             }
                   3597:         }
                   3598:     }
                   3599:     return;
                   3600: }
                   3601: 
1.493     albertel 3602: sub removeuploadedurl {
1.984     neumanie 3603:     my ($url)=@_;	
                   3604:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3605:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3606: }
                   3607: 
                   3608: sub removeuserfile {
                   3609:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3610:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3611:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3612:     if ($result eq 'ok') {	
1.798     raeburn  3613:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3614:             my $metafile = $fname.'.meta';
                   3615:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3616: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3617:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3618:             my $sqlresult = 
1.823     albertel 3619:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3620:                                         'portfolio_metadata',$group,
                   3621:                                         'delete');
1.798     raeburn  3622:         }
                   3623:     }
                   3624:     return $result;
1.257     www      3625: }
1.15      www      3626: 
1.530     albertel 3627: sub mkdiruserfile {
                   3628:     my ($docuname,$docudom,$dir)=@_;
                   3629:     my $home=&homeserver($docuname,$docudom);
                   3630:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3631: }
                   3632: 
1.531     albertel 3633: sub renameuserfile {
                   3634:     my ($docuname,$docudom,$old,$new)=@_;
                   3635:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3636:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3637:                         &escape("$old").':'.&escape("$new"),$home);
                   3638:     if ($result eq 'ok') {
                   3639:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3640:             my $oldmeta = $old.'.meta';
                   3641:             my $newmeta = $new.'.meta';
                   3642:             my $metaresult = 
                   3643:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3644: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3645:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3646:             my $sqlresult = 
1.823     albertel 3647:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3648:                                         'portfolio_metadata',$group,
                   3649:                                         'delete');
1.798     raeburn  3650:         }
                   3651:     }
                   3652:     return $result;
1.531     albertel 3653: }
                   3654: 
1.14      www      3655: # ------------------------------------------------------------------------- Log
                   3656: 
                   3657: sub log {
                   3658:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3659:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3660: }
                   3661: 
                   3662: # ------------------------------------------------------------------ Course Log
1.352     www      3663: #
                   3664: # This routine flushes several buffers of non-mission-critical nature
                   3665: #
1.157     www      3666: 
                   3667: sub flushcourselogs {
1.352     www      3668:     &logthis('Flushing log buffers');
                   3669: #
                   3670: # course logs
                   3671: # This is a log of all transactions in a course, which can be used
                   3672: # for data mining purposes
                   3673: #
                   3674: # It also collects the courseid database, which lists last transaction
                   3675: # times and course titles for all courseids
                   3676: #
                   3677:     my %courseidbuffer=();
1.921     raeburn  3678:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3679:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3680: 		          &escape($courselogs{$crsid}),
                   3681: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3682: 	    delete $courselogs{$crsid};
                   3683:         } else {
                   3684:             &logthis('Failed to flush log buffer for '.$crsid);
                   3685:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3686:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3687:                         " exceeded maximum size, deleting.</font>");
                   3688:                delete $courselogs{$crsid};
                   3689:             }
1.352     www      3690:         }
1.920     raeburn  3691:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3692:             'description' => $coursedescrbuf{$crsid},
                   3693:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3694:             'type'        => $coursetypebuf{$crsid},
                   3695:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3696:         };
1.191     harris41 3697:     }
1.352     www      3698: #
                   3699: # Write course id database (reverse lookup) to homeserver of courses 
                   3700: # Is used in pickcourse
                   3701: #
1.840     albertel 3702:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3703:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3704:                                     $courseidbuffer{$crs_home},
                   3705:                                     $crs_home,'timeonly');
1.352     www      3706:     }
                   3707: #
                   3708: # File accesses
                   3709: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3710: #
1.449     matthew  3711:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3712:         if ($entry =~ /___count$/) {
                   3713:             my ($dom,$name);
1.807     albertel 3714:             ($dom,$name,undef)=
1.811     albertel 3715: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3716:             if (! defined($dom) || $dom eq '' || 
                   3717:                 ! defined($name) || $name eq '') {
1.620     albertel 3718:                 my $cid = $env{'request.course.id'};
                   3719:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3720:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3721:             }
1.450     matthew  3722:             my $value = $accesshash{$entry};
                   3723:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3724:             my %temphash=($url => $value);
1.449     matthew  3725:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3726:             if ($result eq 'ok') {
                   3727:                 delete $accesshash{$entry};
                   3728:             }
                   3729:         } else {
1.811     albertel 3730:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3731:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3732:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3733:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3734:                 delete $accesshash{$entry};
                   3735:             }
1.185     www      3736:         }
1.191     harris41 3737:     }
1.352     www      3738: #
                   3739: # Roles
                   3740: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3741: #
1.800     albertel 3742:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3743:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3744: 	    split(/\:/,$entry);
                   3745:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3746:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3747:                 $rudom,$runame) eq 'ok') {
                   3748: 	    delete $userrolehash{$entry};
                   3749:         }
                   3750:     }
1.662     raeburn  3751: #
                   3752: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3753: #
                   3754:     my %domrolebuffer = ();
1.1000    raeburn  3755:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3756:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3757:         if ($domrolebuffer{$rudom}) {
                   3758:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3759:                       '='.&escape($domainrolehash{$entry});
                   3760:         } else {
                   3761:             $domrolebuffer{$rudom}.=&escape($entry).
                   3762:                       '='.&escape($domainrolehash{$entry});
                   3763:         }
                   3764:         delete $domainrolehash{$entry};
                   3765:     }
                   3766:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3767: 	my %servers = &get_servers($dom,'library');
                   3768: 	foreach my $tryserver (keys(%servers)) {
                   3769: 	    unless (&reply('domroleput:'.$dom.':'.
                   3770: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3771: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3772: 	    }
1.662     raeburn  3773:         }
                   3774:     }
1.186     www      3775:     $dumpcount++;
1.157     www      3776: }
                   3777: 
                   3778: sub courselog {
                   3779:     my $what=shift;
1.158     www      3780:     $what=time.':'.$what;
1.620     albertel 3781:     unless ($env{'request.course.id'}) { return ''; }
                   3782:     $coursedombuf{$env{'request.course.id'}}=
                   3783:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3784:     $coursenumbuf{$env{'request.course.id'}}=
                   3785:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3786:     $coursehombuf{$env{'request.course.id'}}=
                   3787:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3788:     $coursedescrbuf{$env{'request.course.id'}}=
                   3789:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3790:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3791:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3792:     $courseownerbuf{$env{'request.course.id'}}=
                   3793:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3794:     $coursetypebuf{$env{'request.course.id'}}=
                   3795:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3796:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3797: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3798:     } else {
1.620     albertel 3799: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3800:     }
1.620     albertel 3801:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3802: 	&flushcourselogs();
                   3803:     }
1.158     www      3804: }
                   3805: 
                   3806: sub courseacclog {
                   3807:     my $fnsymb=shift;
1.620     albertel 3808:     unless ($env{'request.course.id'}) { return ''; }
                   3809:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3810:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3811:         $what.=':POST';
1.583     matthew  3812:         # FIXME: Probably ought to escape things....
1.800     albertel 3813: 	foreach my $key (keys(%env)) {
                   3814:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3815:                 my $formitem = $1;
                   3816:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3817:                     $what.=':'.$formitem.'='.$env{$key};
                   3818:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3819:                     $what.=':'.$formitem.'='.$env{$key};
                   3820:                 }
1.158     www      3821:             }
1.191     harris41 3822:         }
1.583     matthew  3823:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3824:         # FIXME: We should not be depending on a form parameter that someone
                   3825:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3826:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3827:             $what.= ':POST';
                   3828:             # FIXME: Probably ought to escape things....
                   3829:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3830:                                  'crsdiscuss') {
1.620     albertel 3831:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3832:             }
                   3833:         }
1.158     www      3834:     }
                   3835:     &courselog($what);
1.149     www      3836: }
                   3837: 
1.185     www      3838: sub countacc {
                   3839:     my $url=&declutter(shift);
1.458     matthew  3840:     return if (! defined($url) || $url eq '');
1.620     albertel 3841:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3842: #
                   3843: # Mark that this url was used in this course
                   3844: #
1.620     albertel 3845:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3846: #
                   3847: # Increase the access count for this resource in this child process
                   3848: #
1.281     www      3849:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3850:     $accesshash{$key}++;
1.185     www      3851: }
1.349     www      3852: 
1.361     www      3853: sub linklog {
                   3854:     my ($from,$to)=@_;
                   3855:     $from=&declutter($from);
                   3856:     $to=&declutter($to);
                   3857:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3858:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3859: }
1.1160    www      3860: 
                   3861: sub statslog {
                   3862:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3863:     if ($users<2) { return; }
                   3864:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3865:             'course'       => $env{'request.course.id'},
                   3866:             'sections'     => '"all"',
                   3867:             'num_students' => $users,
                   3868:             'part'         => $part,
                   3869:             'symb'         => $symb,
                   3870:             'mean_tries'   => $av_attempts,
                   3871:             'deg_of_diff'  => $degdiff});
                   3872:     foreach my $key (keys(%dynstore)) {
                   3873:         $accesshash{$key}=$dynstore{$key};
                   3874:     }
                   3875: }
1.361     www      3876:   
1.349     www      3877: sub userrolelog {
                   3878:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3879:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3880:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3881:        $userrolehash
                   3882:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3883:                     =$tend.':'.$tstart;
1.662     raeburn  3884:     }
1.1169    droeschl 3885:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3886:        $userrolehash
                   3887:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3888:                     =$tend.':'.$tstart;
                   3889:     }
1.1169    droeschl 3890:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3891:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3892:        $domainrolehash
                   3893:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3894:                     = $tend.':'.$tstart;
                   3895:     }
1.351     www      3896: }
                   3897: 
1.957     raeburn  3898: sub courserolelog {
                   3899:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  3900:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3901:         my $cdom = $1;
                   3902:         my $cnum = $2;
                   3903:         my $sec = $3;
                   3904:         my $namespace = 'rolelog';
                   3905:         my %storehash = (
                   3906:                            role    => $trole,
                   3907:                            start   => $tstart,
                   3908:                            end     => $tend,
                   3909:                            selfenroll => $selfenroll,
                   3910:                            context    => $context,
                   3911:                         );
                   3912:         if ($trole eq 'gr') {
                   3913:             $namespace = 'groupslog';
                   3914:             $storehash{'group'} = $sec;
                   3915:         } else {
                   3916:             $storehash{'section'} = $sec;
                   3917:         }
1.1188    raeburn  3918:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3919:                    $domain,$cnum,$cdom);
1.1184    raeburn  3920:         if (($trole ne 'st') || ($sec ne '')) {
                   3921:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3922:         }
                   3923:     }
                   3924:     return;
                   3925: }
                   3926: 
1.1184    raeburn  3927: sub domainrolelog {
                   3928:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3929:     if ($area =~ m{^/($match_domain)/$}) {
                   3930:         my $cdom = $1;
                   3931:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3932:         my $namespace = 'rolelog';
                   3933:         my %storehash = (
                   3934:                            role    => $trole,
                   3935:                            start   => $tstart,
                   3936:                            end     => $tend,
                   3937:                            context => $context,
                   3938:                         );
1.1188    raeburn  3939:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3940:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  3941:     }
                   3942:     return;
                   3943: 
                   3944: }
                   3945: 
                   3946: sub coauthorrolelog {
                   3947:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3948:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3949:         my $audom = $1;
                   3950:         my $auname = $2;
                   3951:         my $namespace = 'rolelog';
                   3952:         my %storehash = (
                   3953:                            role    => $trole,
                   3954:                            start   => $tstart,
                   3955:                            end     => $tend,
                   3956:                            context => $context,
                   3957:                         );
1.1188    raeburn  3958:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3959:                    $domain,$auname,$audom);
1.1184    raeburn  3960:     }
                   3961:     return;
                   3962: }
                   3963: 
1.351     www      3964: sub get_course_adv_roles {
1.948     raeburn  3965:     my ($cid,$codes) = @_;
1.620     albertel 3966:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3967:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3968:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3969:     my %nothide=();
1.800     albertel 3970:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3971:         if ($user !~ /:/) {
                   3972: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3973:         } else {
                   3974:             $nothide{$user}=1;
                   3975:         }
1.470     www      3976:     }
1.1219    raeburn  3977:     my @possdoms = ($coursehash{'domain'});
                   3978:     if ($coursehash{'checkforpriv'}) {
                   3979:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3980:     }
1.351     www      3981:     my %returnhash=();
                   3982:     my %dumphash=
                   3983:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3984:     my $now=time;
1.997     raeburn  3985:     my %privileged;
1.1000    raeburn  3986:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3987: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3988:         if (($tstart) && ($tstart<0)) { next; }
                   3989:         if (($tend) && ($tend<$now)) { next; }
                   3990:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3991:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3992: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  3993:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3994:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3995: 	if ($role eq 'cr') { next; }
1.948     raeburn  3996:         if ($codes) {
                   3997:             if ($section) { $role .= ':'.$section; }
                   3998:             if ($returnhash{$role}) {
                   3999:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4000:             } else {
                   4001:                 $returnhash{$role}=$username.':'.$domain;
                   4002:             }
1.351     www      4003:         } else {
1.988     raeburn  4004:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4005:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4006:             if ($returnhash{$key}) {
                   4007: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4008:             } else {
                   4009:                 $returnhash{$key}=$username.':'.$domain;
                   4010:             }
1.351     www      4011:         }
1.948     raeburn  4012:     }
1.400     www      4013:     return %returnhash;
                   4014: }
                   4015: 
                   4016: sub get_my_roles {
1.937     raeburn  4017:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4018:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4019:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4020:     my (%dumphash,%nothide);
1.1086    raeburn  4021:     if ($context eq 'userroles') {
1.1166    raeburn  4022:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4023:     } else {
1.1219    raeburn  4024:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4025:         if ($hidepriv) {
                   4026:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4027:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4028:                 if ($user !~ /:/) {
                   4029:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4030:                 } else {
                   4031:                     $nothide{$user} = 1;
                   4032:                 }
                   4033:             }
                   4034:         }
1.858     raeburn  4035:     }
1.400     www      4036:     my %returnhash=();
                   4037:     my $now=time;
1.999     raeburn  4038:     my %privileged;
1.800     albertel 4039:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4040:         my ($role,$tend,$tstart);
                   4041:         if ($context eq 'userroles') {
1.1149    raeburn  4042:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4043: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4044:         } else {
                   4045:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4046:         }
1.400     www      4047:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4048:         my $status = 'active';
1.939     raeburn  4049:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4050:             $status = 'previous';
                   4051:         } 
                   4052:         if (($tstart) && ($now<$tstart)) {
                   4053:             $status = 'future';
                   4054:         }
                   4055:         if (ref($types) eq 'ARRAY') {
                   4056:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4057:                 next;
                   4058:             } 
                   4059:         } else {
                   4060:             if ($status ne 'active') {
                   4061:                 next;
                   4062:             }
                   4063:         }
1.867     raeburn  4064:         my ($rolecode,$username,$domain,$section,$area);
                   4065:         if ($context eq 'userroles') {
1.1186    raeburn  4066:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4067:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4068:         } else {
                   4069:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4070:         }
1.832     raeburn  4071:         if (ref($roledoms) eq 'ARRAY') {
                   4072:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4073:                 next;
                   4074:             }
                   4075:         }
                   4076:         if (ref($roles) eq 'ARRAY') {
                   4077:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4078:                 if ($role =~ /^cr\//) {
                   4079:                     if (!grep(/^cr$/,@{$roles})) {
                   4080:                         next;
                   4081:                     }
1.1104    raeburn  4082:                 } elsif ($role =~ /^gr\//) {
                   4083:                     if (!grep(/^gr$/,@{$roles})) {
                   4084:                         next;
                   4085:                     }
1.922     raeburn  4086:                 } else {
                   4087:                     next;
                   4088:                 }
1.832     raeburn  4089:             }
1.867     raeburn  4090:         }
1.937     raeburn  4091:         if ($hidepriv) {
1.1219    raeburn  4092:             my @privroles = ('dc','su');
1.999     raeburn  4093:             if ($context eq 'userroles') {
1.1219    raeburn  4094:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4095:             } else {
1.1219    raeburn  4096:                 my $possdoms = [$domain];
                   4097:                 if (ref($roledoms) eq 'ARRAY') {
                   4098:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4099:                 }
1.1219    raeburn  4100:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4101:                     if (!$nothide{$username.':'.$domain}) {
                   4102:                         next;
                   4103:                     }
                   4104:                 }
1.937     raeburn  4105:             }
                   4106:         }
1.933     raeburn  4107:         if ($withsec) {
                   4108:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4109:                 $tstart.':'.$tend;
                   4110:         } else {
                   4111:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4112:         }
1.832     raeburn  4113:     }
1.373     www      4114:     return %returnhash;
1.399     www      4115: }
                   4116: 
                   4117: # ----------------------------------------------------- Frontpage Announcements
                   4118: #
                   4119: #
                   4120: 
                   4121: sub postannounce {
                   4122:     my ($server,$text)=@_;
1.844     albertel 4123:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4124:     unless ($text=~/\w/) { $text=''; }
                   4125:     return &reply('setannounce:'.&escape($text),$server);
                   4126: }
                   4127: 
                   4128: sub getannounce {
1.448     albertel 4129: 
                   4130:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4131: 	my $announcement='';
1.800     albertel 4132: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4133: 	close($fh);
1.399     www      4134: 	if ($announcement=~/\w/) { 
                   4135: 	    return 
                   4136:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4137:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4138: 	} else {
                   4139: 	    return '';
                   4140: 	}
                   4141:     } else {
                   4142: 	return '';
                   4143:     }
1.351     www      4144: }
1.353     www      4145: 
                   4146: # ---------------------------------------------------------- Course ID routines
                   4147: # Deal with domain's nohist_courseid.db files
                   4148: #
                   4149: 
                   4150: sub courseidput {
1.921     raeburn  4151:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4152:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4153:     my $outcome;
                   4154:     if ($caller eq 'timeonly') {
                   4155:         my $cids = '';
                   4156:         foreach my $item (keys(%$storehash)) {
                   4157:             $cids.=&escape($item).'&';
                   4158:         }
                   4159:         $cids=~s/\&$//;
                   4160:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4161:                           $coursehome);       
                   4162:     } else {
                   4163:         my $items = '';
                   4164:         foreach my $item (keys(%$storehash)) {
                   4165:             $items.= &escape($item).'='.
                   4166:                      &freeze_escape($$storehash{$item}).'&';
                   4167:         }
                   4168:         $items=~s/\&$//;
                   4169:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4170:                           $coursehome);
1.918     raeburn  4171:     }
                   4172:     if ($outcome eq 'unknown_cmd') {
                   4173:         my $what;
                   4174:         foreach my $cid (keys(%$storehash)) {
                   4175:             $what .= &escape($cid).'=';
1.921     raeburn  4176:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4177:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4178:             }
                   4179:             $what =~ s/\:$/&/;
                   4180:         }
                   4181:         $what =~ s/\&$//;  
                   4182:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4183:     } else {
                   4184:         return $outcome;
                   4185:     }
1.353     www      4186: }
                   4187: 
                   4188: sub courseiddump {
1.921     raeburn  4189:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4190:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4191:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4192:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
                   4193:         $hasuniquecode)=@_;
1.918     raeburn  4194:     my $as_hash = 1;
                   4195:     my %returnhash;
                   4196:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4197:     my %libserv = &all_library();
                   4198:     foreach my $tryserver (keys(%libserv)) {
                   4199:         if ( (  $hostidflag == 1 
                   4200: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4201: 	     || (!defined($hostidflag)) ) {
                   4202: 
1.918     raeburn  4203: 	    if (($domfilter eq '') ||
                   4204: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4205:                 my $rep;
                   4206:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4207:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4208:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4209:                                 &escape($descfilter), &escape($instcodefilter), 
                   4210:                                 &escape($ownerfilter), &escape($coursefilter),
                   4211:                                 &escape($typefilter), &escape($regexp_ok), 
                   4212:                                 $as_hash, &escape($selfenrollonly), 
                   4213:                                 &escape($catfilter), $showhidden, $caller, 
                   4214:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4215:                                 &escape($createdbefore), &escape($createdafter), 
1.1247    raeburn  4216:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180    droeschl 4217:                 } else {
                   4218:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4219:                              $sincefilter.':'.&escape($descfilter).':'.
                   4220:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4221:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4222:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4223:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4224:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4225:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4226:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247    raeburn  4227:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180    droeschl 4228:                              $tryserver);
                   4229:                 }
                   4230:                      
1.918     raeburn  4231:                 my @pairs=split(/\&/,$rep);
                   4232:                 foreach my $item (@pairs) {
                   4233:                     my ($key,$value)=split(/\=/,$item,2);
                   4234:                     $key = &unescape($key);
                   4235:                     next if ($key =~ /^error: 2 /);
                   4236:                     my $result = &thaw_unescape($value);
                   4237:                     if (ref($result) eq 'HASH') {
                   4238:                         $returnhash{$key}=$result;
                   4239:                     } else {
1.921     raeburn  4240:                         my @responses = split(/:/,$value);
                   4241:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4242:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4243:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4244:                         }
1.1008    raeburn  4245:                     }
1.353     www      4246:                 }
                   4247:             }
                   4248:         }
                   4249:     }
                   4250:     return %returnhash;
                   4251: }
                   4252: 
1.1055    raeburn  4253: sub courselastaccess {
                   4254:     my ($cdom,$cnum,$hostidref) = @_;
                   4255:     my %returnhash;
                   4256:     if ($cdom && $cnum) {
                   4257:         my $chome = &homeserver($cnum,$cdom);
                   4258:         if ($chome ne 'no_host') {
                   4259:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4260:             &extract_lastaccess(\%returnhash,$rep);
                   4261:         }
                   4262:     } else {
                   4263:         if (!$cdom) { $cdom=''; }
                   4264:         my %libserv = &all_library();
                   4265:         foreach my $tryserver (keys(%libserv)) {
                   4266:             if (ref($hostidref) eq 'ARRAY') {
                   4267:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4268:             } 
                   4269:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4270:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4271:                 &extract_lastaccess(\%returnhash,$rep);
                   4272:             }
                   4273:         }
                   4274:     }
                   4275:     return %returnhash;
                   4276: }
                   4277: 
                   4278: sub extract_lastaccess {
                   4279:     my ($returnhash,$rep) = @_;
                   4280:     if (ref($returnhash) eq 'HASH') {
                   4281:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4282:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4283:                  $rep eq '') {
                   4284:             my @pairs=split(/\&/,$rep);
                   4285:             foreach my $item (@pairs) {
                   4286:                 my ($key,$value)=split(/\=/,$item,2);
                   4287:                 $key = &unescape($key);
                   4288:                 next if ($key =~ /^error: 2 /);
                   4289:                 $returnhash->{$key} = &thaw_unescape($value);
                   4290:             }
                   4291:         }
                   4292:     }
                   4293:     return;
                   4294: }
                   4295: 
1.658     raeburn  4296: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4297: 
                   4298: sub dcmailput {
1.685     raeburn  4299:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4300:     my $status = &Apache::lonnet::critical(
1.740     www      4301:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4302:        &escape($message),$server);
1.662     raeburn  4303:     return $status;
                   4304: }
                   4305: 
1.658     raeburn  4306: sub dcmaildump {
                   4307:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4308:     my %returnhash=();
1.846     albertel 4309: 
                   4310:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4311:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4312:                                                          &escape($enddate).':';
                   4313: 	my @esc_senders=map { &escape($_)} @$senders;
                   4314: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4315: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4316:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4317:             if (($key) && ($value)) {
                   4318:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4319:             }
                   4320:         }
                   4321:     }
                   4322:     return %returnhash;
                   4323: }
1.662     raeburn  4324: # ---------------------------------------------------------- Domain roles
                   4325: 
                   4326: sub get_domain_roles {
                   4327:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4328:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4329:         $startdate = '.';
                   4330:     }
1.1018    raeburn  4331:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4332:         $enddate = '.';
                   4333:     }
1.922     raeburn  4334:     my $rolelist;
                   4335:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4336:         $rolelist = join('&',@{$roles});
1.922     raeburn  4337:     }
1.662     raeburn  4338:     my %personnel = ();
1.841     albertel 4339: 
                   4340:     my %servers = &get_servers($dom,'library');
                   4341:     foreach my $tryserver (keys(%servers)) {
                   4342: 	%{$personnel{$tryserver}}=();
                   4343: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4344: 					    &escape($startdate).':'.
                   4345: 					    &escape($enddate).':'.
                   4346: 					    &escape($rolelist), $tryserver))) {
                   4347: 	    my ($key,$value) = split(/\=/,$line,2);
                   4348: 	    if (($key) && ($value)) {
                   4349: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4350: 	    }
                   4351: 	}
1.662     raeburn  4352:     }
                   4353:     return %personnel;
                   4354: }
1.658     raeburn  4355: 
1.1057    www      4356: # ----------------------------------------------------------- Interval timing 
1.149     www      4357: 
1.1153    www      4358: {
                   4359: # Caches needed for speedup of navmaps
                   4360: # We don't want to cache this for very long at all (5 seconds at most)
                   4361: # 
                   4362: # The user for whom we cache
                   4363: my $cachedkey='';
                   4364: # The cached times for this user
                   4365: my %cachedtimes=();
                   4366: # When this was last done
                   4367: my $cachedtime=();
                   4368: 
                   4369: sub load_all_first_access {
1.1154    raeburn  4370:     my ($uname,$udom)=@_;
1.1156    www      4371:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4372:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4373:         return;
                   4374:     }
                   4375:     $cachedtime=time;
                   4376:     $cachedkey=$uname.':'.$udom;
                   4377:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4378: }
                   4379: 
1.504     albertel 4380: sub get_first_access {
1.1162    raeburn  4381:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4382:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4383:     if ($argsymb) { $symb=$argsymb; }
                   4384:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4385:     if ($argmap) { $map = $argmap; }
1.926     albertel 4386:     if ($type eq 'course') {
                   4387: 	$res='course';
                   4388:     } elsif ($type eq 'map') {
1.588     albertel 4389: 	$res=&symbread($map);
                   4390:     } else {
                   4391: 	$res=$symb;
                   4392:     }
1.1153    www      4393:     &load_all_first_access($uname,$udom);
                   4394:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4395: }
                   4396: 
                   4397: sub set_first_access {
1.1162    raeburn  4398:     my ($type,$interval)=@_;
1.790     albertel 4399:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4400:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4401:     if ($type eq 'course') {
                   4402: 	$res='course';
                   4403:     } elsif ($type eq 'map') {
1.588     albertel 4404: 	$res=&symbread($map);
                   4405:     } else {
                   4406: 	$res=$symb;
                   4407:     }
1.1153    www      4408:     $cachedkey='';
1.1162    raeburn  4409:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4410:     if (!$firstaccess) {
1.1162    raeburn  4411:         my $start = time;
                   4412: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4413:                           $udom,$uname);
                   4414:         if ($putres eq 'ok') {
                   4415:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4416:                  $udom,$uname); 
                   4417:             &appenv(
                   4418:                      {
                   4419:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4420:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4421:                      }
                   4422:                   );
                   4423:         }
                   4424:         return $putres;
1.505     albertel 4425:     }
                   4426:     return 'already_set';
1.504     albertel 4427: }
1.1153    www      4428: }
1.110     www      4429: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4430: 
                   4431: sub expirespread {
                   4432:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4433:     my $cid=$env{'request.course.id'}; 
1.110     www      4434:     if ($cid) {
                   4435:        my $now=time;
                   4436:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4437:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4438:                             $env{'course.'.$cid.'.num'}.
1.110     www      4439: 	        	    ':nohist_expirationdates:'.
                   4440:                             &escape($key).'='.$now,
1.620     albertel 4441:                             $env{'course.'.$cid.'.home'})
1.110     www      4442:     }
                   4443:     return 'ok';
1.14      www      4444: }
                   4445: 
1.109     www      4446: # ----------------------------------------------------- Devalidate Spreadsheets
                   4447: 
                   4448: sub devalidate {
1.325     www      4449:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4450:     my $cid=$env{'request.course.id'}; 
1.109     www      4451:     if ($cid) {
1.391     matthew  4452:         # delete the stored spreadsheets for
                   4453:         # - the student level sheet of this user in course's homespace
                   4454:         # - the assessment level sheet for this resource 
                   4455:         #   for this user in user's homespace
1.553     albertel 4456: 	# - current conditional state info
1.325     www      4457: 	my $key=$uname.':'.$udom.':';
1.109     www      4458:         my $status=
1.299     matthew  4459: 	    &del('nohist_calculatedsheets',
1.391     matthew  4460: 		 [$key.'studentcalc:'],
1.620     albertel 4461: 		 $env{'course.'.$cid.'.domain'},
                   4462: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4463: 		.' '.
                   4464: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4465: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4466:         unless ($status eq 'ok ok') {
                   4467:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4468:                     $uname.' at '.$udom.' for '.
1.109     www      4469: 		    $symb.': '.$status);
1.133     albertel 4470:         }
1.553     albertel 4471: 	&delenv('user.state.'.$cid);
1.109     www      4472:     }
                   4473: }
                   4474: 
1.265     albertel 4475: sub get_scalar {
                   4476:     my ($string,$end) = @_;
                   4477:     my $value;
                   4478:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4479: 	$value = $1;
                   4480:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4481: 	$value = $1;
                   4482:     }
                   4483:     return &unescape($value);
                   4484: }
                   4485: 
                   4486: sub array2str {
                   4487:   my (@array) = @_;
                   4488:   my $result=&arrayref2str(\@array);
                   4489:   $result=~s/^__ARRAY_REF__//;
                   4490:   $result=~s/__END_ARRAY_REF__$//;
                   4491:   return $result;
                   4492: }
                   4493: 
1.204     albertel 4494: sub arrayref2str {
                   4495:   my ($arrayref) = @_;
1.265     albertel 4496:   my $result='__ARRAY_REF__';
1.204     albertel 4497:   foreach my $elem (@$arrayref) {
1.265     albertel 4498:     if(ref($elem) eq 'ARRAY') {
                   4499:       $result.=&arrayref2str($elem).'&';
                   4500:     } elsif(ref($elem) eq 'HASH') {
                   4501:       $result.=&hashref2str($elem).'&';
                   4502:     } elsif(ref($elem)) {
                   4503:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4504:     } else {
                   4505:       $result.=&escape($elem).'&';
                   4506:     }
                   4507:   }
                   4508:   $result=~s/\&$//;
1.265     albertel 4509:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4510:   return $result;
                   4511: }
                   4512: 
1.168     albertel 4513: sub hash2str {
1.204     albertel 4514:   my (%hash) = @_;
                   4515:   my $result=&hashref2str(\%hash);
1.265     albertel 4516:   $result=~s/^__HASH_REF__//;
                   4517:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4518:   return $result;
                   4519: }
                   4520: 
                   4521: sub hashref2str {
                   4522:   my ($hashref)=@_;
1.265     albertel 4523:   my $result='__HASH_REF__';
1.800     albertel 4524:   foreach my $key (sort(keys(%$hashref))) {
                   4525:     if (ref($key) eq 'ARRAY') {
                   4526:       $result.=&arrayref2str($key).'=';
                   4527:     } elsif (ref($key) eq 'HASH') {
                   4528:       $result.=&hashref2str($key).'=';
                   4529:     } elsif (ref($key)) {
1.265     albertel 4530:       $result.='=';
1.800     albertel 4531:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4532:     } else {
1.1132    raeburn  4533: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4534:     }
                   4535: 
1.800     albertel 4536:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4537:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4538:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4539:       $result.=&hashref2str($hashref->{$key}).'&';
                   4540:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4541:        $result.='&';
1.800     albertel 4542:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4543:     } else {
1.800     albertel 4544:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4545:     }
                   4546:   }
1.168     albertel 4547:   $result=~s/\&$//;
1.265     albertel 4548:   $result .= '__END_HASH_REF__';
1.168     albertel 4549:   return $result;
                   4550: }
                   4551: 
                   4552: sub str2hash {
1.265     albertel 4553:     my ($string)=@_;
                   4554:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4555:     return %$hash;
                   4556: }
                   4557: 
                   4558: sub str2hashref {
1.168     albertel 4559:   my ($string) = @_;
1.265     albertel 4560: 
                   4561:   my %hash;
                   4562: 
                   4563:   if($string !~ /^__HASH_REF__/) {
                   4564:       if (! ($string eq '' || !defined($string))) {
                   4565: 	  $hash{'error'}='Not hash reference';
                   4566:       }
                   4567:       return (\%hash, $string);
                   4568:   }
                   4569: 
                   4570:   $string =~ s/^__HASH_REF__//;
                   4571: 
                   4572:   while($string !~ /^__END_HASH_REF__/) {
                   4573:       #key
                   4574:       my $key='';
                   4575:       if($string =~ /^__HASH_REF__/) {
                   4576:           ($key, $string)=&str2hashref($string);
                   4577:           if(defined($key->{'error'})) {
                   4578:               $hash{'error'}='Bad data';
                   4579:               return (\%hash, $string);
                   4580:           }
                   4581:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4582:           ($key, $string)=&str2arrayref($string);
                   4583:           if($key->[0] eq 'Array reference error') {
                   4584:               $hash{'error'}='Bad data';
                   4585:               return (\%hash, $string);
                   4586:           }
                   4587:       } else {
                   4588:           $string =~ s/^(.*?)=//;
1.267     albertel 4589: 	  $key=&unescape($1);
1.265     albertel 4590:       }
                   4591:       $string =~ s/^=//;
                   4592: 
                   4593:       #value
                   4594:       my $value='';
                   4595:       if($string =~ /^__HASH_REF__/) {
                   4596:           ($value, $string)=&str2hashref($string);
                   4597:           if(defined($value->{'error'})) {
                   4598:               $hash{'error'}='Bad data';
                   4599:               return (\%hash, $string);
                   4600:           }
                   4601:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4602:           ($value, $string)=&str2arrayref($string);
                   4603:           if($value->[0] eq 'Array reference error') {
                   4604:               $hash{'error'}='Bad data';
                   4605:               return (\%hash, $string);
                   4606:           }
                   4607:       } else {
                   4608: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4609:       }
                   4610:       $string =~ s/^&//;
                   4611: 
                   4612:       $hash{$key}=$value;
1.204     albertel 4613:   }
1.265     albertel 4614: 
                   4615:   $string =~ s/^__END_HASH_REF__//;
                   4616: 
                   4617:   return (\%hash, $string);
1.204     albertel 4618: }
                   4619: 
                   4620: sub str2array {
1.265     albertel 4621:     my ($string)=@_;
                   4622:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4623:     return @$array;
                   4624: }
                   4625: 
                   4626: sub str2arrayref {
1.204     albertel 4627:   my ($string) = @_;
1.265     albertel 4628:   my @array;
                   4629: 
                   4630:   if($string !~ /^__ARRAY_REF__/) {
                   4631:       if (! ($string eq '' || !defined($string))) {
                   4632: 	  $array[0]='Array reference error';
                   4633:       }
                   4634:       return (\@array, $string);
                   4635:   }
                   4636: 
                   4637:   $string =~ s/^__ARRAY_REF__//;
                   4638: 
                   4639:   while($string !~ /^__END_ARRAY_REF__/) {
                   4640:       my $value='';
                   4641:       if($string =~ /^__HASH_REF__/) {
                   4642:           ($value, $string)=&str2hashref($string);
                   4643:           if(defined($value->{'error'})) {
                   4644:               $array[0] ='Array reference error';
                   4645:               return (\@array, $string);
                   4646:           }
                   4647:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4648:           ($value, $string)=&str2arrayref($string);
                   4649:           if($value->[0] eq 'Array reference error') {
                   4650:               $array[0] ='Array reference error';
                   4651:               return (\@array, $string);
                   4652:           }
                   4653:       } else {
                   4654: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4655:       }
                   4656:       $string =~ s/^&//;
                   4657: 
                   4658:       push(@array, $value);
1.191     harris41 4659:   }
1.265     albertel 4660: 
                   4661:   $string =~ s/^__END_ARRAY_REF__//;
                   4662: 
                   4663:   return (\@array, $string);
1.168     albertel 4664: }
                   4665: 
1.167     albertel 4666: # -------------------------------------------------------------------Temp Store
                   4667: 
1.168     albertel 4668: sub tmpreset {
                   4669:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4670:   if (!$symb) {
                   4671:     $symb=&symbread();
1.620     albertel 4672:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4673:   }
                   4674:   $symb=escape($symb);
                   4675: 
1.620     albertel 4676:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4677:   $namespace=~s/\//\_/g;
                   4678:   $namespace=~s/\W//g;
                   4679: 
1.620     albertel 4680:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4681:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4682:   if ($domain eq 'public' && $stuname eq 'public') {
                   4683:       $stuname=$ENV{'REMOTE_ADDR'};
                   4684:   }
1.1117    foxr     4685:   my $path=LONCAPA::tempdir();
1.168     albertel 4686:   my %hash;
                   4687:   if (tie(%hash,'GDBM_File',
                   4688: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4689: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4690:     foreach my $key (keys(%hash)) {
1.180     albertel 4691:       if ($key=~ /:$symb/) {
1.168     albertel 4692: 	delete($hash{$key});
                   4693:       }
                   4694:     }
                   4695:   }
                   4696: }
                   4697: 
1.167     albertel 4698: sub tmpstore {
1.168     albertel 4699:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4700: 
                   4701:   if (!$symb) {
                   4702:     $symb=&symbread();
1.620     albertel 4703:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4704:   }
                   4705:   $symb=escape($symb);
                   4706: 
                   4707:   if (!$namespace) {
                   4708:     # I don't think we would ever want to store this for a course.
                   4709:     # it seems this will only be used if we don't have a course.
1.620     albertel 4710:     #$namespace=$env{'request.course.id'};
1.168     albertel 4711:     #if (!$namespace) {
1.620     albertel 4712:       $namespace=$env{'request.state'};
1.168     albertel 4713:     #}
                   4714:   }
                   4715:   $namespace=~s/\//\_/g;
                   4716:   $namespace=~s/\W//g;
1.620     albertel 4717:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4718:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4719:   if ($domain eq 'public' && $stuname eq 'public') {
                   4720:       $stuname=$ENV{'REMOTE_ADDR'};
                   4721:   }
1.168     albertel 4722:   my $now=time;
                   4723:   my %hash;
1.1117    foxr     4724:   my $path=LONCAPA::tempdir();
1.168     albertel 4725:   if (tie(%hash,'GDBM_File',
                   4726: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4727: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4728:     $hash{"version:$symb"}++;
                   4729:     my $version=$hash{"version:$symb"};
                   4730:     my $allkeys=''; 
                   4731:     foreach my $key (keys(%$storehash)) {
                   4732:       $allkeys.=$key.':';
1.591     albertel 4733:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4734:     }
                   4735:     $hash{"$version:$symb:timestamp"}=$now;
                   4736:     $allkeys.='timestamp';
                   4737:     $hash{"$version:keys:$symb"}=$allkeys;
                   4738:     if (untie(%hash)) {
                   4739:       return 'ok';
                   4740:     } else {
                   4741:       return "error:$!";
                   4742:     }
                   4743:   } else {
                   4744:     return "error:$!";
                   4745:   }
                   4746: }
1.167     albertel 4747: 
1.168     albertel 4748: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4749: 
1.168     albertel 4750: sub tmprestore {
                   4751:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4752: 
1.168     albertel 4753:   if (!$symb) {
                   4754:     $symb=&symbread();
1.620     albertel 4755:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4756:   }
                   4757:   $symb=escape($symb);
                   4758: 
1.620     albertel 4759:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4760: 
1.620     albertel 4761:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4762:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4763:   if ($domain eq 'public' && $stuname eq 'public') {
                   4764:       $stuname=$ENV{'REMOTE_ADDR'};
                   4765:   }
1.168     albertel 4766:   my %returnhash;
                   4767:   $namespace=~s/\//\_/g;
                   4768:   $namespace=~s/\W//g;
                   4769:   my %hash;
1.1117    foxr     4770:   my $path=LONCAPA::tempdir();
1.168     albertel 4771:   if (tie(%hash,'GDBM_File',
                   4772: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4773: 	  &GDBM_READER(),0640)) {
1.168     albertel 4774:     my $version=$hash{"version:$symb"};
                   4775:     $returnhash{'version'}=$version;
                   4776:     my $scope;
                   4777:     for ($scope=1;$scope<=$version;$scope++) {
                   4778:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4779:       my @keys=split(/:/,$vkeys);
                   4780:       my $key;
                   4781:       $returnhash{"$scope:keys"}=$vkeys;
                   4782:       foreach $key (@keys) {
1.591     albertel 4783: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4784: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4785:       }
                   4786:     }
1.168     albertel 4787:     if (!(untie(%hash))) {
                   4788:       return "error:$!";
                   4789:     }
                   4790:   } else {
                   4791:     return "error:$!";
                   4792:   }
                   4793:   return %returnhash;
1.167     albertel 4794: }
                   4795: 
1.9       www      4796: # ----------------------------------------------------------------------- Store
                   4797: 
                   4798: sub store {
1.124     www      4799:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4800:     my $home='';
                   4801: 
1.168     albertel 4802:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4803: 
1.213     www      4804:     $symb=&symbclean($symb);
1.122     albertel 4805:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4806: 
1.620     albertel 4807:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4808:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4809: 
                   4810:     &devalidate($symb,$stuname,$domain);
1.109     www      4811: 
                   4812:     $symb=escape($symb);
1.187     www      4813:     if (!$namespace) { 
1.620     albertel 4814:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4815:           return ''; 
                   4816:        } 
                   4817:     }
1.620     albertel 4818:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4819: 
                   4820:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4821:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4822: 
1.12      www      4823:     my $namevalue='';
1.800     albertel 4824:     foreach my $key (keys(%$storehash)) {
                   4825:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4826:     }
1.12      www      4827:     $namevalue=~s/\&$//;
1.187     www      4828:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4829:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4830: }
                   4831: 
1.47      www      4832: # -------------------------------------------------------------- Critical Store
                   4833: 
                   4834: sub cstore {
1.124     www      4835:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4836:     my $home='';
                   4837: 
1.168     albertel 4838:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4839: 
1.213     www      4840:     $symb=&symbclean($symb);
1.122     albertel 4841:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4842: 
1.620     albertel 4843:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4844:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4845: 
                   4846:     &devalidate($symb,$stuname,$domain);
1.109     www      4847: 
                   4848:     $symb=escape($symb);
1.187     www      4849:     if (!$namespace) { 
1.620     albertel 4850:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4851:           return ''; 
                   4852:        } 
                   4853:     }
1.620     albertel 4854:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4855: 
                   4856:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4857:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4858: 
1.47      www      4859:     my $namevalue='';
1.800     albertel 4860:     foreach my $key (keys(%$storehash)) {
                   4861:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4862:     }
1.47      www      4863:     $namevalue=~s/\&$//;
1.187     www      4864:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4865:     return critical
                   4866:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4867: }
                   4868: 
1.9       www      4869: # --------------------------------------------------------------------- Restore
                   4870: 
                   4871: sub restore {
1.124     www      4872:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4873:     my $home='';
                   4874: 
1.168     albertel 4875:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4876: 
1.122     albertel 4877:     if (!$symb) {
1.1224    raeburn  4878:         return if ($namespace eq 'courserequests');
                   4879:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 4880:     } else {
1.1224    raeburn  4881:         unless ($namespace eq 'courserequests') {
                   4882:             $symb=&escape(&symbclean($symb));
                   4883:         }
1.122     albertel 4884:     }
1.188     www      4885:     if (!$namespace) { 
1.620     albertel 4886:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4887:           return ''; 
                   4888:        } 
                   4889:     }
1.620     albertel 4890:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4891:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4892:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4893:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4894: 
1.12      www      4895:     my %returnhash=();
1.800     albertel 4896:     foreach my $line (split(/\&/,$answer)) {
                   4897: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4898:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4899:     }
1.75      www      4900:     my $version;
                   4901:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4902:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4903:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4904:        }
1.75      www      4905:     }
1.13      www      4906:     return %returnhash;
1.34      www      4907: }
                   4908: 
                   4909: # ---------------------------------------------------------- Course Description
1.1118    foxr     4910: #
                   4911: #  
1.34      www      4912: 
                   4913: sub coursedescription {
1.731     albertel 4914:     my ($courseid,$args)=@_;
1.34      www      4915:     $courseid=~s/^\///;
1.49      www      4916:     $courseid=~s/\_/\//g;
1.34      www      4917:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4918:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4919:     my $normalid=$cdomain.'_'.$cnum;
                   4920:     # need to always cache even if we get errors otherwise we keep 
                   4921:     # trying and trying and trying to get the course description.
                   4922:     my %envhash=();
                   4923:     my %returnhash=();
1.731     albertel 4924:     
                   4925:     my $expiretime=600;
                   4926:     if ($env{'request.course.id'} eq $normalid) {
                   4927: 	$expiretime=120;
                   4928:     }
                   4929: 
                   4930:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4931:     if (!$args->{'freshen_cache'}
                   4932: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4933: 	foreach my $key (keys(%env)) {
                   4934: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4935: 	    my ($setting) = $1;
                   4936: 	    $returnhash{$setting} = $env{$key};
                   4937: 	}
                   4938: 	return %returnhash;
                   4939:     }
                   4940: 
1.1118    foxr     4941:     # get the data again
                   4942: 
1.731     albertel 4943:     if (!$args->{'one_time'}) {
                   4944: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4945:     }
1.811     albertel 4946: 
1.34      www      4947:     if ($chome ne 'no_host') {
1.302     albertel 4948:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4949:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4950: 	   my $username = $env{'user.name'}; # Defult username
                   4951: 	   if(defined $args->{'user'}) {
                   4952: 	       $username = $args->{'user'};
                   4953: 	   }
1.129     albertel 4954:            $returnhash{'home'}= $chome;
                   4955: 	   $returnhash{'domain'} = $cdomain;
                   4956: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4957:            if (!defined($returnhash{'type'})) {
                   4958:                $returnhash{'type'} = 'Course';
                   4959:            }
1.130     albertel 4960:            while (my ($name,$value) = each %returnhash) {
1.53      www      4961:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4962:            }
1.270     www      4963:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4964:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4965: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4966:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4967:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4968:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4969:        }
                   4970:     }
1.731     albertel 4971:     if (!$args->{'one_time'}) {
1.949     raeburn  4972: 	&appenv(\%envhash);
1.731     albertel 4973:     }
1.302     albertel 4974:     return %returnhash;
1.461     www      4975: }
                   4976: 
1.1080    raeburn  4977: sub update_released_required {
                   4978:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4979:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4980:         $cid = $env{'request.course.id'};
                   4981:         $cdom = $env{'course.'.$cid.'.domain'};
                   4982:         $cnum = $env{'course.'.$cid.'.num'};
                   4983:         $chome = $env{'course.'.$cid.'.home'};
                   4984:     }
                   4985:     if ($needsrelease) {
                   4986:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4987:         my $needsupdate;
                   4988:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4989:             $needsupdate = 1;
                   4990:         } else {
                   4991:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4992:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4993:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4994:                 $needsupdate = 1;
                   4995:             }
                   4996:         }
                   4997:         if ($needsupdate) {
                   4998:             my %needshash = (
                   4999:                              'internal.releaserequired' => $needsrelease,
                   5000:                             );
                   5001:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5002:             if ($putresult eq 'ok') {
                   5003:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5004:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5005:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5006:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5007:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5008:                 }
                   5009:             }
                   5010:         }
                   5011:     }
                   5012:     return;
                   5013: }
                   5014: 
1.461     www      5015: # -------------------------------------------------See if a user is privileged
                   5016: 
                   5017: sub privileged {
1.1219    raeburn  5018:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5019:     my $now = time;
1.1219    raeburn  5020:     my $roles;
                   5021:     if (ref($possroles) eq 'ARRAY') {
                   5022:         $roles = $possroles; 
                   5023:     } else {
                   5024:         $roles = ['dc','su'];
                   5025:     }
                   5026:     if (ref($possdomains) eq 'ARRAY') {
                   5027:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5028:         foreach my $dom (@{$possdomains}) {
                   5029:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5030:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5031:                 foreach my $role (@{$roles}) {
                   5032:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5033:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5034:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5035:                             return 1 unless (($end && $end < $now) ||
                   5036:                                              ($start && $start > $now));
                   5037:                         }
                   5038:                     }
                   5039:                 }
                   5040:             }
                   5041:         }
                   5042:     } else {
                   5043:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5044:         my $now = time;
1.1170    droeschl 5045: 
1.1219    raeburn  5046:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 5047:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5048:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5049:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5050:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5051:             }
1.1219    raeburn  5052:         }
                   5053:     }
                   5054:     return 0;
                   5055: }
1.1170    droeschl 5056: 
1.1219    raeburn  5057: sub privileged_by_domain {
                   5058:     my ($domains,$roles) = @_;
                   5059:     my %privileged = ();
                   5060:     my $cachetime = 60*60*24;
                   5061:     my $now = time;
                   5062:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5063:         return %privileged;
                   5064:     }
                   5065:     foreach my $dom (@{$domains}) {
                   5066:         next if (ref($privileged{$dom}) eq 'HASH');
                   5067:         my $needroles;
                   5068:         foreach my $role (@{$roles}) {
                   5069:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5070:             if (defined($cached)) {
                   5071:                 if (ref($result) eq 'HASH') {
                   5072:                     $privileged{$dom}{$role} = $result;
                   5073:                 }
                   5074:             } else {
                   5075:                 $needroles = 1;
                   5076:             }
                   5077:         }
                   5078:         if ($needroles) {
                   5079:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5080:             $privileged{$dom} = {};
                   5081:             foreach my $server (keys(%dompersonnel)) {
                   5082:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5083:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5084:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5085:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5086:                         next if ($end && $end < $now);
                   5087:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5088:                             $dompersonnel{$server}{$item};
                   5089:                     }
                   5090:                 }
                   5091:             }
                   5092:             if (ref($privileged{$dom}) eq 'HASH') {
                   5093:                 foreach my $role (@{$roles}) {
                   5094:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5095:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5096:                     } else {
                   5097:                         my %hash = ();
                   5098:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5099:                     }
                   5100:                 }
                   5101:             }
                   5102:         }
                   5103:     }
                   5104:     return %privileged;
1.9       www      5105: }
1.1       albertel 5106: 
1.103     harris41 5107: # -------------------------------------------------------- Get user privileges
1.11      www      5108: 
                   5109: sub rolesinit {
1.1169    droeschl 5110:     my ($domain, $username) = @_;
                   5111:     my %userroles = ('user.login.time' => time);
                   5112:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5113: 
                   5114:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5115:     # also, blocking can be triggered by an activating timer
                   5116:     # it's saved in the user's %env.
                   5117:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5118:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5119:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5120:         %timerintchk, %timerintenv);
                   5121: 
1.1162    raeburn  5122:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5123:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5124:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5125:     }
1.1169    droeschl 5126: 
1.1162    raeburn  5127:     foreach my $key (keys(%timerinterval)) {
                   5128:         my ($cid,$rest) = split(/\0/,$key);
                   5129:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5130:     }
1.1169    droeschl 5131: 
1.11      www      5132:     my %allroles=();
1.1162    raeburn  5133:     my %allgroups=();
1.11      www      5134: 
1.1169    droeschl 5135:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5136:         my $role = $rolesdump{$area};
                   5137:         $area =~ s/\_\w\w$//;
                   5138: 
                   5139:         my ($trole, $tend, $tstart, $group_privs);
                   5140: 
                   5141:         if ($role =~ /^cr/) {
                   5142:         # Custom role, defined by a user 
                   5143:         # e.g., user.role.cr/msu/smith/mynewrole
                   5144:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5145:                 $trole = $1;
                   5146:                 ($tend, $tstart) = split('_', $2);
                   5147:             } else {
                   5148:                 $trole = $role;
                   5149:             }
                   5150:         } elsif ($role =~ m|^gr/|) {
                   5151:         # Role of member in a group, defined within a course/community
                   5152:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5153:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5154:             next if $tstart eq '-1';
                   5155:             ($trole, $group_privs) = split(/\//, $trole);
                   5156:             $group_privs = &unescape($group_privs);
                   5157:         } else {
                   5158:         # Just a normal role, defined in roles.tab
                   5159:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5160:         }
                   5161: 
                   5162:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5163:                  $username);
                   5164:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5165: 
                   5166:         # role expired or not available yet?
                   5167:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5168:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5169: 
                   5170:         next if $area eq '' or $trole eq '';
                   5171: 
                   5172:         my $spec = "$trole.$area";
                   5173:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5174: 
                   5175:         if ($trole =~ /^cr\//) {
                   5176:         # Custom role, defined by a user
                   5177:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5178:         } elsif ($trole eq 'gr') {
                   5179:         # Role of a member in a group, defined within a course/community
                   5180:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5181:             next;
                   5182:         } else {
                   5183:         # Normal role, defined in roles.tab
                   5184:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5185:         }
                   5186: 
                   5187:         my $cid = $tdomain.'_'.$trest;
                   5188:         unless ($firstaccchk{$cid}) {
                   5189:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5190:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5191:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5192:                         $coursetimerstarts{$cid}{$item}; 
                   5193:                 }
                   5194:             }
                   5195:             $firstaccchk{$cid} = 1;
                   5196:         }
                   5197:         unless ($timerintchk{$cid}) {
                   5198:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5199:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5200:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5201:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5202:                 }
1.12      www      5203:             }
1.1169    droeschl 5204:             $timerintchk{$cid} = 1;
1.191     harris41 5205:         }
1.11      www      5206:     }
1.1169    droeschl 5207: 
                   5208:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5209:         \%allroles, \%allgroups);
                   5210:     $env{'user.adv'} = $userroles{'user.adv'};
                   5211: 
1.1162    raeburn  5212:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5213: }
                   5214: 
1.567     raeburn  5215: sub set_arearole {
1.1215    raeburn  5216:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5217:     unless ($nolog) {
1.567     raeburn  5218: # log the associated role with the area
1.1215    raeburn  5219:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5220:     }
1.743     albertel 5221:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5222: }
                   5223: 
                   5224: sub custom_roleprivs {
                   5225:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5226:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5227:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5228:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5229:         my ($rdummy,$roledef)=
                   5230:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5231:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5232:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5233:             if (defined($syspriv)) {
1.1043    raeburn  5234:                 if ($trest =~ /^$match_community$/) {
                   5235:                     $syspriv =~ s/bre\&S//; 
                   5236:                 }
1.567     raeburn  5237:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5238:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5239:             }
                   5240:             if ($tdomain ne '') {
                   5241:                 if (defined($dompriv)) {
                   5242:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5243:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5244:                 }
                   5245:                 if (($trest ne '') && (defined($coursepriv))) {
                   5246:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5247:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5248:                 }
                   5249:             }
                   5250:         }
                   5251:     }
                   5252: }
                   5253: 
1.678     raeburn  5254: sub group_roleprivs {
                   5255:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5256:     my $access = 1;
                   5257:     my $now = time;
                   5258:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5259:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5260:     if ($access) {
1.811     albertel 5261:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5262:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5263:     }
                   5264: }
1.567     raeburn  5265: 
                   5266: sub standard_roleprivs {
                   5267:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5268:     if (defined($pr{$trole.':s'})) {
                   5269:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5270:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5271:     }
                   5272:     if ($tdomain ne '') {
                   5273:         if (defined($pr{$trole.':d'})) {
                   5274:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5275:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5276:         }
                   5277:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5278:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5279:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5280:         }
                   5281:     }
                   5282: }
                   5283: 
                   5284: sub set_userprivs {
1.1064    raeburn  5285:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5286:     my $author=0;
                   5287:     my $adv=0;
1.678     raeburn  5288:     my %grouproles = ();
                   5289:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5290:         my @groupkeys; 
1.1000    raeburn  5291:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5292:             push(@groupkeys,$role);
                   5293:         }
                   5294:         if (ref($groups_roles) eq 'HASH') {
                   5295:             foreach my $key (keys(%{$groups_roles})) {
                   5296:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5297:                     push(@groupkeys,$key);
                   5298:                 }
                   5299:             }
                   5300:         }
                   5301:         if (@groupkeys > 0) {
                   5302:             foreach my $role (@groupkeys) {
                   5303:                 my ($trole,$area,$sec,$extendedarea);
                   5304:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5305:                     $trole = $1;
                   5306:                     $area = $2;
                   5307:                     $sec = $3;
                   5308:                     $extendedarea = $area.$sec;
                   5309:                     if (exists($$allgroups{$area})) {
                   5310:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5311:                             my $spec = $trole.'.'.$extendedarea;
                   5312:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5313:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5314:                         }
1.678     raeburn  5315:                     }
                   5316:                 }
                   5317:             }
                   5318:         }
                   5319:     }
1.800     albertel 5320:     foreach my $group (keys(%grouproles)) {
                   5321:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5322:     }
1.800     albertel 5323:     foreach my $role (keys(%{$allroles})) {
                   5324:         my %thesepriv;
1.941     raeburn  5325:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5326:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5327:             if ($item ne '') {
                   5328:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5329:                 if ($restrictions eq '') {
                   5330:                     $thesepriv{$privilege}='F';
                   5331:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5332:                     $thesepriv{$privilege}.=$restrictions;
                   5333:                 }
                   5334:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5335:             }
                   5336:         }
                   5337:         my $thesestr='';
1.1104    raeburn  5338:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5339: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5340: 	}
                   5341:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5342:     }
                   5343:     return ($author,$adv);
                   5344: }
                   5345: 
1.994     raeburn  5346: sub role_status {
1.1104    raeburn  5347:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5348:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5349:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5350:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5351:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5352:             $$where = '/'.$two;
1.994     raeburn  5353:             $$trolecode=$$role.'.'.$$where;
                   5354:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5355:             $$tstatus='is';
1.1104    raeburn  5356:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5357:                 $$tstatus='future';
1.1034    raeburn  5358:                 if ($$tstart<$now) {
                   5359:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5360:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5361:                             my (%allroles,%allgroups,$group_privs,
                   5362:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5363:                             my %userroles = (
                   5364:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5365:                             );
1.1064    raeburn  5366:                             @rolecodes = ('cm'); 
1.1002    raeburn  5367:                             my $spec=$$role.'.'.$$where;
                   5368:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5369:                             if ($$role =~ /^cr\//) {
                   5370:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5371:                                 push(@rolecodes,'cr');
1.1002    raeburn  5372:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5373:                                 push(@rolecodes,$$role);
1.1002    raeburn  5374:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5375:                                                     $env{'user.name'});
1.1064    raeburn  5376:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5377:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5378:                                 $group_privs = &unescape($group_privs);
                   5379:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5380:                                 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  5381:                                 &get_groups_roles($tdomain,$trest,
                   5382:                                                   \%course_roles,\@rolecodes,
                   5383:                                                   \%groups_roles);
1.1002    raeburn  5384:                             } else {
1.1064    raeburn  5385:                                 push(@rolecodes,$$role);
1.1002    raeburn  5386:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5387:                             }
1.1064    raeburn  5388:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5389:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5390:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5391:                         }
                   5392:                     }
1.1034    raeburn  5393:                     $$tstatus = 'is';
1.1002    raeburn  5394:                 }
1.994     raeburn  5395:             }
                   5396:             if ($$tend) {
1.1104    raeburn  5397:                 if ($$tend<$update) {
1.994     raeburn  5398:                     $$tstatus='expired';
                   5399:                 } elsif ($$tend<$now) {
                   5400:                     $$tstatus='will_not';
                   5401:                 }
                   5402:             }
                   5403:         }
                   5404:     }
                   5405: }
                   5406: 
1.1104    raeburn  5407: sub get_groups_roles {
                   5408:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5409:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5410:                   (ref($rolecodes) eq 'ARRAY') && 
                   5411:                   (ref($groups_roles) eq 'HASH')); 
                   5412:     if (keys(%{$cdom_courseroles}) > 0) {
                   5413:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5414:         if ($cdom ne '' && $cnum ne '') {
                   5415:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5416:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5417:                     my $crsrole = $1;
                   5418:                     my $crssec = $2;
                   5419:                     if ($crsrole =~ /^cr/) {
                   5420:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5421:                             push(@{$rolecodes},'cr');
                   5422:                         }
                   5423:                     } else {
                   5424:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5425:                             push(@{$rolecodes},$crsrole);
                   5426:                         }
                   5427:                     }
                   5428:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5429:                     if ($crssec ne '') {
                   5430:                         $rolekey .= "/$crssec";
                   5431:                     }
                   5432:                     $rolekey .= './';
                   5433:                     $groups_roles->{$rolekey} = $rolecodes;
                   5434:                 }
                   5435:             }
                   5436:         }
                   5437:     }
                   5438:     return;
                   5439: }
                   5440: 
                   5441: sub delete_env_groupprivs {
                   5442:     my ($where,$courseroles,$possroles) = @_;
                   5443:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5444:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5445:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5446:         %{$courseroles->{$udom}} =
                   5447:             &get_my_roles('','','userroles',['active'],
                   5448:                           $possroles,[$udom],1);
                   5449:     }
                   5450:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5451:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5452:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5453:             my $area = '/'.$cdom.'/'.$cnum;
                   5454:             my $privkey = "user.priv.$crsrole.$area";
                   5455:             if ($crssec ne '') {
                   5456:                 $privkey .= '/'.$crssec;
                   5457:             }
                   5458:             $privkey .= ".$area/$group";
                   5459:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5460:         }
                   5461:     }
                   5462:     return;
                   5463: }
                   5464: 
1.994     raeburn  5465: sub check_adhoc_privs {
1.1104    raeburn  5466:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5467:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5468:     my $setprivs;
1.994     raeburn  5469:     if ($env{$cckey}) {
                   5470:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5471:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5472:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5473:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5474:             $setprivs = 1;
1.994     raeburn  5475:         }
                   5476:     } else {
1.1088    raeburn  5477:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5478:         $setprivs = 1;
1.994     raeburn  5479:     }
1.1185    raeburn  5480:     return $setprivs;
1.994     raeburn  5481: }
                   5482: 
                   5483: sub set_adhoc_privileges {
                   5484: # role can be cc or ca
1.1088    raeburn  5485:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5486:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5487:     my $spec = $role.'.'.$area;
                   5488:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5489:                                   $env{'user.name'},1);
1.994     raeburn  5490:     my %ccrole = ();
                   5491:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5492:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5493:     &appenv(\%userroles,[$role,'cm']);
                   5494:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5495:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5496:         &appenv( {'request.role'        => $spec,
                   5497:                   'request.role.domain' => $dcdom,
                   5498:                   'request.course.sec'  => ''
                   5499:                  }
                   5500:                );
                   5501:         my $tadv=0;
                   5502:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5503:         &appenv({'request.role.adv'    => $tadv});
                   5504:     }
1.994     raeburn  5505: }
                   5506: 
1.12      www      5507: # --------------------------------------------------------------- get interface
                   5508: 
                   5509: sub get {
1.131     albertel 5510:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5511:    my $items='';
1.800     albertel 5512:    foreach my $item (@$storearr) {
                   5513:        $items.=&escape($item).'&';
1.191     harris41 5514:    }
1.12      www      5515:    $items=~s/\&$//;
1.620     albertel 5516:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5517:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5518:    my $uhome=&homeserver($uname,$udomain);
                   5519: 
1.133     albertel 5520:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5521:    my @pairs=split(/\&/,$rep);
1.273     albertel 5522:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5523:      return @pairs;
                   5524:    }
1.15      www      5525:    my %returnhash=();
1.42      www      5526:    my $i=0;
1.800     albertel 5527:    foreach my $item (@$storearr) {
                   5528:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5529:       $i++;
1.191     harris41 5530:    }
1.15      www      5531:    return %returnhash;
1.27      www      5532: }
                   5533: 
                   5534: # --------------------------------------------------------------- del interface
                   5535: 
                   5536: sub del {
1.133     albertel 5537:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5538:    my $items='';
1.800     albertel 5539:    foreach my $item (@$storearr) {
                   5540:        $items.=&escape($item).'&';
1.191     harris41 5541:    }
1.984     neumanie 5542: 
1.27      www      5543:    $items=~s/\&$//;
1.620     albertel 5544:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5545:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5546:    my $uhome=&homeserver($uname,$udomain);
                   5547:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5548: }
                   5549: 
                   5550: # -------------------------------------------------------------- dump interface
                   5551: 
1.1180    droeschl 5552: sub unserialize {
                   5553:     my ($rep, $escapedkeys) = @_;
                   5554: 
                   5555:     return {} if $rep =~ /^error/;
                   5556: 
                   5557:     my %returnhash=();
1.1252    raeburn  5558: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5559: 	    my ($key, $value) = split(/=/, $item, 2);
                   5560: 	    $key = unescape($key) unless $escapedkeys;
                   5561: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5562: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5563: 	}
                   5564:     #return %returnhash;
                   5565:     return \%returnhash;
                   5566: }        
                   5567: 
                   5568: # see Lond::dump_with_regexp
                   5569: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5570: sub dump {
1.1180    droeschl 5571:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5572:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5573:     if (!$uname) { $uname=$env{'user.name'}; }
                   5574:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5575: 
1.1180    droeschl 5576:     my $reply;
                   5577:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5578:         # user is hosted on this machine
                   5579:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5580:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5581:         return %{unserialize($reply, $escapedkeys)};
                   5582:     }
1.755     albertel 5583:     if ($regexp) {
                   5584: 	$regexp=&escape($regexp);
                   5585:     } else {
                   5586: 	$regexp='.';
                   5587:     }
1.1166    raeburn  5588:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5589:     my @pairs=split(/\&/,$rep);
                   5590:     my %returnhash=();
1.1098    foxr     5591:     if (!($rep =~ /^error/ )) {
                   5592: 	foreach my $item (@pairs) {
                   5593: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5594:         $key = unescape($key) unless $escapedkeys;
                   5595:         #$key = &unescape($key);
1.1098    foxr     5596: 	    next if ($key =~ /^error: 2 /);
                   5597: 	    $returnhash{$key}=&thaw_unescape($value);
                   5598: 	}
1.755     albertel 5599:     }
                   5600:     return %returnhash;
1.407     www      5601: }
                   5602: 
1.1098    foxr     5603: 
1.717     albertel 5604: # --------------------------------------------------------- dumpstore interface
                   5605: 
                   5606: sub dumpstore {
                   5607:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5608:    # same as dump but keys must be escaped. They may contain colon separated
                   5609:    # lists of values that may themself contain colons (e.g. symbs).
                   5610:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5611: }
                   5612: 
1.407     www      5613: # -------------------------------------------------------------- keys interface
                   5614: 
                   5615: sub getkeys {
                   5616:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5617:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5618:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5619:    my $uhome=&homeserver($uname,$udomain);
                   5620:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5621:    my @keyarray=();
1.800     albertel 5622:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5623:       next if ($key =~ /^error: 2 /);
1.800     albertel 5624:       push(@keyarray,&unescape($key));
1.407     www      5625:    }
                   5626:    return @keyarray;
1.318     matthew  5627: }
                   5628: 
1.319     matthew  5629: # --------------------------------------------------------------- currentdump
                   5630: sub currentdump {
1.328     matthew  5631:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5632:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5633:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5634:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5635:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5636:    my $rep;
                   5637: 
                   5638:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5639:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5640:                    $courseid)));
                   5641:    } else {
                   5642:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5643:    }
                   5644: 
1.318     matthew  5645:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5646:    #
1.318     matthew  5647:    my %returnhash=();
1.319     matthew  5648:    #
                   5649:    if ($rep eq "unknown_cmd") { 
                   5650:        # an old lond will not know currentdump
                   5651:        # Do a dump and make it look like a currentdump
1.822     albertel 5652:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5653:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5654:        my %hash = @tmp;
                   5655:        @tmp=();
1.424     matthew  5656:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5657:    } else {
                   5658:        my @pairs=split(/\&/,$rep);
1.800     albertel 5659:        foreach my $pair (@pairs) {
                   5660:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5661:            my ($symb,$param) = split(/:/,$key);
                   5662:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5663:                                                         &thaw_unescape($value);
1.319     matthew  5664:        }
1.191     harris41 5665:    }
1.12      www      5666:    return %returnhash;
1.424     matthew  5667: }
                   5668: 
                   5669: sub convert_dump_to_currentdump{
                   5670:     my %hash = %{shift()};
                   5671:     my %returnhash;
                   5672:     # Code ripped from lond, essentially.  The only difference
                   5673:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5674:     # we might run in to problems with parameter names =~ /^v\./
                   5675:     while (my ($key,$value) = each(%hash)) {
                   5676:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5677: 	$symb  = &unescape($symb);
                   5678: 	$param = &unescape($param);
1.424     matthew  5679:         next if ($v eq 'version' || $symb eq 'keys');
                   5680:         next if (exists($returnhash{$symb}) &&
                   5681:                  exists($returnhash{$symb}->{$param}) &&
                   5682:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5683:         $returnhash{$symb}->{$param}=$value;
                   5684:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5685:     }
                   5686:     #
                   5687:     # Remove all of the keys in the hashes which keep track of
                   5688:     # the version of the parameter.
                   5689:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5690:         # use a foreach because we are going to delete from the hash.
                   5691:         foreach my $key (keys(%$param_hash)) {
                   5692:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5693:         }
                   5694:     }
                   5695:     return \%returnhash;
1.12      www      5696: }
                   5697: 
1.627     albertel 5698: # ------------------------------------------------------ critical inc interface
                   5699: 
                   5700: sub cinc {
                   5701:     return &inc(@_,'critical');
                   5702: }
                   5703: 
1.449     matthew  5704: # --------------------------------------------------------------- inc interface
                   5705: 
                   5706: sub inc {
1.627     albertel 5707:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5708:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5709:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5710:     my $uhome=&homeserver($uname,$udomain);
                   5711:     my $items='';
                   5712:     if (! ref($store)) {
                   5713:         # got a single value, so use that instead
                   5714:         $items = &escape($store).'=&';
                   5715:     } elsif (ref($store) eq 'SCALAR') {
                   5716:         $items = &escape($$store).'=&';        
                   5717:     } elsif (ref($store) eq 'ARRAY') {
                   5718:         $items = join('=&',map {&escape($_);} @{$store});
                   5719:     } elsif (ref($store) eq 'HASH') {
                   5720:         while (my($key,$value) = each(%{$store})) {
                   5721:             $items.= &escape($key).'='.&escape($value).'&';
                   5722:         }
                   5723:     }
                   5724:     $items=~s/\&$//;
1.627     albertel 5725:     if ($critical) {
                   5726: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5727:     } else {
                   5728: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5729:     }
1.449     matthew  5730: }
                   5731: 
1.12      www      5732: # --------------------------------------------------------------- put interface
                   5733: 
                   5734: sub put {
1.134     albertel 5735:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5736:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5737:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5738:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5739:    my $items='';
1.800     albertel 5740:    foreach my $item (keys(%$storehash)) {
                   5741:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5742:    }
1.12      www      5743:    $items=~s/\&$//;
1.134     albertel 5744:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5745: }
                   5746: 
1.631     albertel 5747: # ------------------------------------------------------------ newput interface
                   5748: 
                   5749: sub newput {
                   5750:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5751:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5752:    if (!$uname) { $uname=$env{'user.name'}; }
                   5753:    my $uhome=&homeserver($uname,$udomain);
                   5754:    my $items='';
                   5755:    foreach my $key (keys(%$storehash)) {
                   5756:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5757:    }
                   5758:    $items=~s/\&$//;
                   5759:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5760: }
                   5761: 
                   5762: # ---------------------------------------------------------  putstore interface
                   5763: 
1.524     raeburn  5764: sub putstore {
1.715     albertel 5765:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5766:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5767:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5768:    my $uhome=&homeserver($uname,$udomain);
                   5769:    my $items='';
1.715     albertel 5770:    foreach my $key (keys(%$storehash)) {
                   5771:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5772:    }
1.715     albertel 5773:    $items=~s/\&$//;
1.716     albertel 5774:    my $esc_symb=&escape($symb);
                   5775:    my $esc_v=&escape($version);
1.715     albertel 5776:    my $reply =
1.716     albertel 5777:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5778: 	      $uhome);
                   5779:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5780:        # gfall back to way things use to be done
1.715     albertel 5781:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5782: 			    $uname);
1.524     raeburn  5783:    }
1.715     albertel 5784:    return $reply;
                   5785: }
                   5786: 
                   5787: sub old_putstore {
1.716     albertel 5788:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5789:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5790:     if (!$uname) { $uname=$env{'user.name'}; }
                   5791:     my $uhome=&homeserver($uname,$udomain);
                   5792:     my %newstorehash;
1.800     albertel 5793:     foreach my $item (keys(%$storehash)) {
                   5794: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5795: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5796:     }
                   5797:     my $items='';
                   5798:     my %allitems = ();
1.800     albertel 5799:     foreach my $item (keys(%newstorehash)) {
                   5800: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5801: 	    my $key = $1.':keys:'.$2;
                   5802: 	    $allitems{$key} .= $3.':';
                   5803: 	}
1.800     albertel 5804: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5805:     }
1.800     albertel 5806:     foreach my $item (keys(%allitems)) {
                   5807: 	$allitems{$item} =~ s/\:$//;
                   5808: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5809:     }
                   5810:     $items=~s/\&$//;
                   5811:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5812: }
                   5813: 
1.47      www      5814: # ------------------------------------------------------ critical put interface
                   5815: 
                   5816: sub cput {
1.134     albertel 5817:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5818:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5819:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5820:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5821:    my $items='';
1.800     albertel 5822:    foreach my $item (keys(%$storehash)) {
                   5823:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5824:    }
1.47      www      5825:    $items=~s/\&$//;
1.134     albertel 5826:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5827: }
                   5828: 
                   5829: # -------------------------------------------------------------- eget interface
                   5830: 
                   5831: sub eget {
1.133     albertel 5832:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5833:    my $items='';
1.800     albertel 5834:    foreach my $item (@$storearr) {
                   5835:        $items.=&escape($item).'&';
1.191     harris41 5836:    }
1.12      www      5837:    $items=~s/\&$//;
1.620     albertel 5838:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5839:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5840:    my $uhome=&homeserver($uname,$udomain);
                   5841:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5842:    my @pairs=split(/\&/,$rep);
                   5843:    my %returnhash=();
1.42      www      5844:    my $i=0;
1.800     albertel 5845:    foreach my $item (@$storearr) {
                   5846:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5847:       $i++;
1.191     harris41 5848:    }
1.12      www      5849:    return %returnhash;
                   5850: }
                   5851: 
1.667     albertel 5852: # ------------------------------------------------------------ tmpput interface
                   5853: sub tmpput {
1.802     raeburn  5854:     my ($storehash,$server,$context)=@_;
1.667     albertel 5855:     my $items='';
1.800     albertel 5856:     foreach my $item (keys(%$storehash)) {
                   5857: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5858:     }
                   5859:     $items=~s/\&$//;
1.802     raeburn  5860:     if (defined($context)) {
                   5861:         $items .= ':'.&escape($context);
                   5862:     }
1.667     albertel 5863:     return &reply("tmpput:$items",$server);
                   5864: }
                   5865: 
                   5866: # ------------------------------------------------------------ tmpget interface
                   5867: sub tmpget {
1.688     albertel 5868:     my ($token,$server)=@_;
                   5869:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5870:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5871:     my %returnhash;
                   5872:     foreach my $item (split(/\&/,$rep)) {
                   5873: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5874:         next if ($key =~ /^error: 2 /);
1.667     albertel 5875: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5876:     }
                   5877:     return %returnhash;
                   5878: }
                   5879: 
1.1113    raeburn  5880: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5881: sub tmpdel {
                   5882:     my ($token,$server)=@_;
                   5883:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5884:     return &reply("tmpdel:$token",$server);
                   5885: }
                   5886: 
1.1198    raeburn  5887: # ------------------------------------------------------------ get_timebased_id 
                   5888: 
                   5889: sub get_timebased_id {
                   5890:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5891:         $maxtries) = @_;
                   5892:     my ($newid,$error,$dellock);
                   5893:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   5894:         return ('','ok','invalid call to get suffix');
                   5895:     }
                   5896: 
                   5897: # set defaults for any optional args for which values were not supplied
                   5898:     if ($who eq '') {
                   5899:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5900:     }
                   5901:     if (!$locktries) {
                   5902:         $locktries = 3;
                   5903:     }
                   5904:     if (!$maxtries) {
                   5905:         $maxtries = 10;
                   5906:     }
                   5907:     
                   5908:     if (($cdom eq '') || ($cnum eq '')) {
                   5909:         if ($env{'request.course.id'}) {
                   5910:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5911:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5912:         }
                   5913:         if (($cdom eq '') || ($cnum eq '')) {
                   5914:             return ('','ok','call to get suffix not in course context');
                   5915:         }
                   5916:     }
                   5917: 
                   5918: # construct locking item
                   5919:     my $lockhash = {
                   5920:                       $prefix."\0".'locked_'.$keyid => $who,
                   5921:                    };
                   5922:     my $tries = 0;
                   5923: 
                   5924: # attempt to get lock on nohist_$namespace file
                   5925:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5926:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5927:         $tries ++;
                   5928:         sleep 1;
                   5929:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5930:     }
                   5931: 
                   5932: # attempt to get unique identifier, based on current timestamp
                   5933:     if ($gotlock eq 'ok') {
                   5934:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5935:         my $id = time;
                   5936:         $newid = $id;
                   5937:         my $idtries = 0;
                   5938:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5939:             if ($idtype eq 'concat') {
                   5940:                 $newid = $id.$idtries;
                   5941:             } else {
                   5942:                 $newid ++;
                   5943:             }
                   5944:             $idtries ++;
                   5945:         }
                   5946:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5947:             my %new_item =  (
                   5948:                               $prefix."\0".$newid => $who,
                   5949:                             );
                   5950:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5951:                                                  $cdom,$cnum);
                   5952:             if ($putresult ne 'ok') {
                   5953:                 undef($newid);
                   5954:                 $error = 'error saving new item: '.$putresult;
                   5955:             }
                   5956:         } else {
                   5957:              $error = ('error: no unique suffix available for the new item ');
                   5958:         }
                   5959: #  remove lock
                   5960:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5961:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5962:     } else {
                   5963:         $error = "error: could not obtain lockfile\n";
                   5964:         $dellock = 'ok';
                   5965:     }
                   5966:     return ($newid,$dellock,$error);
                   5967: }
                   5968: 
1.765     albertel 5969: # -------------------------------------------------- portfolio access checking
                   5970: 
                   5971: sub portfolio_access {
1.766     albertel 5972:     my ($requrl) = @_;
1.765     albertel 5973:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5974:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5975:     if ($result) {
                   5976:         my %setters;
                   5977:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5978:             my ($startblock,$endblock) =
                   5979:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5980:             if ($startblock && $endblock) {
                   5981:                 return 'B';
                   5982:             }
                   5983:         } else {
                   5984:             my ($startblock,$endblock) =
                   5985:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5986:             if ($startblock && $endblock) {
                   5987:                 return 'B';
                   5988:             }
                   5989:         }
                   5990:     }
1.765     albertel 5991:     if ($result eq 'ok') {
1.766     albertel 5992:        return 'F';
1.765     albertel 5993:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5994:        return 'A';
1.765     albertel 5995:     }
1.766     albertel 5996:     return '';
1.765     albertel 5997: }
                   5998: 
                   5999: sub get_portfolio_access {
1.767     albertel 6000:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6001: 
                   6002:     if (!ref($access_hash)) {
                   6003: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6004: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6005: 						   $file_name);
                   6006: 	$access_hash = $access_controls{$file_name};
                   6007:     }
                   6008: 
1.765     albertel 6009:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6010:     my $now = time;
                   6011:     if (ref($access_hash) eq 'HASH') {
                   6012:         foreach my $key (keys(%{$access_hash})) {
                   6013:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6014:             if ($start > $now) {
                   6015:                 next;
                   6016:             }
                   6017:             if ($end && $end<$now) {
                   6018:                 next;
                   6019:             }
                   6020:             if ($scope eq 'public') {
                   6021:                 $public = $key;
                   6022:                 last;
                   6023:             } elsif ($scope eq 'guest') {
                   6024:                 $guest = $key;
                   6025:             } elsif ($scope eq 'domains') {
                   6026:                 push(@domains,$key);
                   6027:             } elsif ($scope eq 'users') {
                   6028:                 push(@users,$key);
                   6029:             } elsif ($scope eq 'course') {
                   6030:                 push(@courses,$key);
                   6031:             } elsif ($scope eq 'group') {
                   6032:                 push(@groups,$key);
                   6033:             }
                   6034:         }
                   6035:         if ($public) {
                   6036:             return 'ok';
                   6037:         }
                   6038:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6039:             if ($guest) {
                   6040:                 return $guest;
                   6041:             }
                   6042:         } else {
                   6043:             if (@domains > 0) {
                   6044:                 foreach my $domkey (@domains) {
                   6045:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6046:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6047:                             return 'ok';
                   6048:                         }
                   6049:                     }
                   6050:                 }
                   6051:             }
                   6052:             if (@users > 0) {
                   6053:                 foreach my $userkey (@users) {
1.865     raeburn  6054:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6055:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6056:                             if (ref($item) eq 'HASH') {
                   6057:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6058:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6059:                                     return 'ok';
                   6060:                                 }
                   6061:                             }
                   6062:                         }
                   6063:                     } 
1.765     albertel 6064:                 }
                   6065:             }
                   6066:             my %roleshash;
                   6067:             my @courses_and_groups = @courses;
                   6068:             push(@courses_and_groups,@groups); 
                   6069:             if (@courses_and_groups > 0) {
                   6070:                 my (%allgroups,%allroles); 
                   6071:                 my ($start,$end,$role,$sec,$group);
                   6072:                 foreach my $envkey (%env) {
1.1060    raeburn  6073:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6074:                         my $cid = $2.'_'.$3; 
                   6075:                         if ($1 eq 'gr') {
                   6076:                             $group = $4;
                   6077:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6078:                         } else {
                   6079:                             if ($4 eq '') {
                   6080:                                 $sec = 'none';
                   6081:                             } else {
                   6082:                                 $sec = $4;
                   6083:                             }
                   6084:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6085:                         }
1.811     albertel 6086:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6087:                         my $cid = $2.'_'.$3;
                   6088:                         if ($4 eq '') {
                   6089:                             $sec = 'none';
                   6090:                         } else {
                   6091:                             $sec = $4;
                   6092:                         }
                   6093:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6094:                     }
                   6095:                 }
                   6096:                 if (keys(%allroles) == 0) {
                   6097:                     return;
                   6098:                 }
                   6099:                 foreach my $key (@courses_and_groups) {
                   6100:                     my %content = %{$$access_hash{$key}};
                   6101:                     my $cnum = $content{'number'};
                   6102:                     my $cdom = $content{'domain'};
                   6103:                     my $cid = $cdom.'_'.$cnum;
                   6104:                     if (!exists($allroles{$cid})) {
                   6105:                         next;
                   6106:                     }    
                   6107:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6108:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6109:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6110:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6111:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6112:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6113:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6114:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6115:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6116:                                         if (grep/^all$/,@sections) {
                   6117:                                             return 'ok';
                   6118:                                         } else {
                   6119:                                             if (grep/^$sec$/,@sections) {
                   6120:                                                 return 'ok';
                   6121:                                             }
                   6122:                                         }
                   6123:                                     }
                   6124:                                 }
                   6125:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6126:                                     if (grep/^none$/,@groups) {
                   6127:                                         return 'ok';
                   6128:                                     }
                   6129:                                 } else {
                   6130:                                     if (grep/^all$/,@groups) {
                   6131:                                         return 'ok';
                   6132:                                     } 
                   6133:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6134:                                         if (grep/^$group$/,@groups) {
                   6135:                                             return 'ok';
                   6136:                                         }
                   6137:                                     }
                   6138:                                 } 
                   6139:                             }
                   6140:                         }
                   6141:                     }
                   6142:                 }
                   6143:             }
                   6144:             if ($guest) {
                   6145:                 return $guest;
                   6146:             }
                   6147:         }
                   6148:     }
                   6149:     return;
                   6150: }
                   6151: 
                   6152: sub course_group_datechecker {
                   6153:     my ($dates,$now,$status) = @_;
                   6154:     my ($start,$end) = split(/\./,$dates);
                   6155:     if (!$start && !$end) {
                   6156:         return 'ok';
                   6157:     }
                   6158:     if (grep/^active$/,@{$status}) {
                   6159:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6160:             return 'ok';
                   6161:         }
                   6162:     }
                   6163:     if (grep/^previous$/,@{$status}) {
                   6164:         if ($end > $now ) {
                   6165:             return 'ok';
                   6166:         }
                   6167:     }
                   6168:     if (grep/^future$/,@{$status}) {
                   6169:         if ($start > $now) {
                   6170:             return 'ok';
                   6171:         }
                   6172:     }
                   6173:     return; 
                   6174: }
                   6175: 
                   6176: sub parse_portfolio_url {
                   6177:     my ($url) = @_;
                   6178: 
                   6179:     my ($type,$udom,$unum,$group,$file_name);
                   6180:     
1.823     albertel 6181:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6182: 	$type = 1;
                   6183:         $udom = $1;
                   6184:         $unum = $2;
                   6185:         $file_name = $3;
1.823     albertel 6186:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6187: 	$type = 2;
                   6188:         $udom = $1;
                   6189:         $unum = $2;
                   6190:         $group = $3;
                   6191:         $file_name = $3.'/'.$4;
                   6192:     }
                   6193:     if (wantarray) {
                   6194: 	return ($type,$udom,$unum,$file_name,$group);
                   6195:     }
                   6196:     return $type;
                   6197: }
                   6198: 
                   6199: sub is_portfolio_url {
                   6200:     my ($url) = @_;
                   6201:     return scalar(&parse_portfolio_url($url));
                   6202: }
                   6203: 
1.798     raeburn  6204: sub is_portfolio_file {
                   6205:     my ($file) = @_;
1.820     raeburn  6206:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6207:         return 1;
                   6208:     }
                   6209:     return;
                   6210: }
                   6211: 
1.976     raeburn  6212: sub usertools_access {
1.1084    raeburn  6213:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6214:     my ($access,%tools);
                   6215:     if ($context eq '') {
                   6216:         $context = 'tools';
                   6217:     }
                   6218:     if ($context eq 'requestcourses') {
                   6219:         %tools = (
                   6220:                       official   => 1,
                   6221:                       unofficial => 1,
1.1006    raeburn  6222:                       community  => 1,
1.1246    raeburn  6223:                       textbook   => 1,
1.985     raeburn  6224:                  );
1.1183    raeburn  6225:     } elsif ($context eq 'requestauthor') {
                   6226:         %tools = (
                   6227:                       requestauthor => 1,
                   6228:                  );
1.985     raeburn  6229:     } else {
                   6230:         %tools = (
                   6231:                       aboutme   => 1,
                   6232:                       blog      => 1,
1.1177    raeburn  6233:                       webdav    => 1,
1.985     raeburn  6234:                       portfolio => 1,
                   6235:                  );
                   6236:     }
1.976     raeburn  6237:     return if (!defined($tools{$tool}));
                   6238: 
1.1242    raeburn  6239:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6240:         $udom = $env{'user.domain'};
                   6241:         $uname = $env{'user.name'};
                   6242:     }
                   6243: 
1.978     raeburn  6244:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6245:         if ($action ne 'reload') {
1.985     raeburn  6246:             if ($context eq 'requestcourses') {
                   6247:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6248:             } elsif ($context eq 'requestauthor') {
                   6249:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6250:             } else {
                   6251:                 return $env{'environment.availabletools.'.$tool};
                   6252:             }
                   6253:         }
1.976     raeburn  6254:     }
                   6255: 
1.1183    raeburn  6256:     my ($toolstatus,$inststatus,$envkey);
                   6257:     if ($context eq 'requestauthor') {
                   6258:         $envkey = $context; 
                   6259:     } else {
                   6260:         $envkey = $context.'.'.$tool;
                   6261:     }
1.976     raeburn  6262: 
1.985     raeburn  6263:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6264:          ($action ne 'reload')) {
1.1183    raeburn  6265:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6266:         $inststatus = $env{'environment.inststatus'};
                   6267:     } else {
1.1084    raeburn  6268:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6269:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6270:             $inststatus = $userenvref->{'inststatus'};
                   6271:         } else {
1.1183    raeburn  6272:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6273:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6274:             $inststatus = $userenv{'inststatus'};
                   6275:         }
1.976     raeburn  6276:     }
                   6277: 
                   6278:     if ($toolstatus ne '') {
                   6279:         if ($toolstatus) {
                   6280:             $access = 1;
                   6281:         } else {
                   6282:             $access = 0;
                   6283:         }
                   6284:         return $access;
                   6285:     }
                   6286: 
1.1084    raeburn  6287:     my ($is_adv,%domdef);
                   6288:     if (ref($is_advref) eq 'HASH') {
                   6289:         $is_adv = $is_advref->{'is_adv'};
                   6290:     } else {
                   6291:         $is_adv = &is_advanced_user($udom,$uname);
                   6292:     }
                   6293:     if (ref($domdefref) eq 'HASH') {
                   6294:         %domdef = %{$domdefref};
                   6295:     } else {
                   6296:         %domdef = &get_domain_defaults($udom);
                   6297:     }
1.976     raeburn  6298:     if (ref($domdef{$tool}) eq 'HASH') {
                   6299:         if ($is_adv) {
                   6300:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6301:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6302:                     $access = 1;
                   6303:                 } else {
                   6304:                     $access = 0;
                   6305:                 }
                   6306:                 return $access;
                   6307:             }
                   6308:         }
                   6309:         if ($inststatus ne '') {
                   6310:             my ($hasaccess,$hasnoaccess);
                   6311:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6312:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6313:                     if ($domdef{$tool}{$affiliation}) {
                   6314:                         $hasaccess = 1;
                   6315:                     } else {
                   6316:                         $hasnoaccess = 1;
                   6317:                     }
                   6318:                 }
                   6319:             }
                   6320:             if ($hasaccess || $hasnoaccess) {
                   6321:                 if ($hasaccess) {
                   6322:                     $access = 1;
                   6323:                 } elsif ($hasnoaccess) {
                   6324:                     $access = 0; 
                   6325:                 }
                   6326:                 return $access;
                   6327:             }
                   6328:         } else {
                   6329:             if ($domdef{$tool}{'default'} ne '') {
                   6330:                 if ($domdef{$tool}{'default'}) {
                   6331:                     $access = 1;
                   6332:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6333:                     $access = 0;
                   6334:                 }
                   6335:                 return $access;
                   6336:             }
                   6337:         }
                   6338:     } else {
1.1177    raeburn  6339:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6340:             $access = 1;
                   6341:         } else {
                   6342:             $access = 0;
                   6343:         }
1.976     raeburn  6344:         return $access;
                   6345:     }
                   6346: }
                   6347: 
1.1050    raeburn  6348: sub is_course_owner {
                   6349:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6350:     if (($udom eq '') || ($uname eq '')) {
                   6351:         $udom = $env{'user.domain'};
                   6352:         $uname = $env{'user.name'};
                   6353:     }
                   6354:     unless (($udom eq '') || ($uname eq '')) {
                   6355:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6356:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6357:                 return 1;
                   6358:             } else {
                   6359:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6360:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6361:                     return 1;
                   6362:                 }
                   6363:             }
                   6364:         }
                   6365:     }
                   6366:     return;
                   6367: }
                   6368: 
1.976     raeburn  6369: sub is_advanced_user {
                   6370:     my ($udom,$uname) = @_;
1.1085    raeburn  6371:     if ($udom ne '' && $uname ne '') {
                   6372:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6373:             if (wantarray) {
                   6374:                 return ($env{'user.adv'},$env{'user.author'});
                   6375:             } else {
                   6376:                 return $env{'user.adv'};
                   6377:             }
1.1085    raeburn  6378:         }
                   6379:     }
1.976     raeburn  6380:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6381:     my %allroles;
1.1128    raeburn  6382:     my ($is_adv,$is_author);
1.976     raeburn  6383:     foreach my $role (keys(%roleshash)) {
                   6384:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6385:         my $area = '/'.$tdomain.'/'.$trest;
                   6386:         if ($sec ne '') {
                   6387:             $area .= '/'.$sec;
                   6388:         }
                   6389:         if (($area ne '') && ($trole ne '')) {
                   6390:             my $spec=$trole.'.'.$area;
                   6391:             if ($trole =~ /^cr\//) {
                   6392:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6393:             } elsif ($trole ne 'gr') {
                   6394:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6395:             }
1.1128    raeburn  6396:             if ($trole eq 'au') {
                   6397:                 $is_author = 1;
                   6398:             }
1.976     raeburn  6399:         }
                   6400:     }
                   6401:     foreach my $role (keys(%allroles)) {
                   6402:         last if ($is_adv);
                   6403:         foreach my $item (split(/:/,$allroles{$role})) {
                   6404:             if ($item ne '') {
                   6405:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6406:                 if ($privilege eq 'adv') {
                   6407:                     $is_adv = 1;
                   6408:                     last;
                   6409:                 }
                   6410:             }
                   6411:         }
                   6412:     }
1.1128    raeburn  6413:     if (wantarray) {
                   6414:         return ($is_adv,$is_author);
                   6415:     }
1.976     raeburn  6416:     return $is_adv;
                   6417: }
1.798     raeburn  6418: 
1.1035    raeburn  6419: sub check_can_request {
1.1036    raeburn  6420:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6421:     my $canreq = 0;
                   6422:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6423:     my @options = ('approval','validate','autolimit');
                   6424:     my $optregex = join('|',@options);
                   6425:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6426:         foreach my $type (@{$types}) {
                   6427:             if (&usertools_access($env{'user.name'},
                   6428:                                   $env{'user.domain'},
                   6429:                                   $type,undef,'requestcourses')) {
                   6430:                 $canreq ++;
1.1036    raeburn  6431:                 if (ref($request_domains) eq 'HASH') {
                   6432:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6433:                 }
1.1035    raeburn  6434:                 if ($dom eq $env{'user.domain'}) {
                   6435:                     $can_request->{$type} = 1;
                   6436:                 }
                   6437:             }
                   6438:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6439:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6440:                 if (@curr > 0) {
1.1036    raeburn  6441:                     foreach my $item (@curr) {
                   6442:                         if (ref($request_domains) eq 'HASH') {
                   6443:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6444:                             if ($otherdom ne '') {
                   6445:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6446:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6447:                                         push(@{$request_domains->{$type}},$otherdom);
                   6448:                                     }
                   6449:                                 } else {
                   6450:                                     push(@{$request_domains->{$type}},$otherdom);
                   6451:                                 }
                   6452:                             }
                   6453:                         }
                   6454:                     }
                   6455:                     unless($dom eq $env{'user.domain'}) {
                   6456:                         $canreq ++;
1.1035    raeburn  6457:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6458:                             $can_request->{$type} = 1;
                   6459:                         }
                   6460:                     }
                   6461:                 }
                   6462:             }
                   6463:         }
                   6464:     }
                   6465:     return $canreq;
                   6466: }
                   6467: 
1.341     www      6468: # ---------------------------------------------- Custom access rule evaluation
                   6469: 
                   6470: sub customaccess {
                   6471:     my ($priv,$uri)=@_;
1.807     albertel 6472:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6473:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6474:     $udom = &LONCAPA::clean_domain($udom);
                   6475:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6476:     my $access=0;
1.800     albertel 6477:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6478: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6479: 	if ($type eq 'user') {
                   6480: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6481: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6482: 		if ($tdom) {
                   6483: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6484: 		}
1.896     albertel 6485: 		if ($tuname) {
                   6486: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6487: 		}
                   6488: 		$access=($effect eq 'allow');
                   6489: 		last;
                   6490: 	    }
                   6491: 	} else {
                   6492: 	    if ($role) {
                   6493: 		if ($role ne $urole) { next; }
                   6494: 	    }
                   6495: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6496: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6497: 		if ($tdom) {
                   6498: 		    if ($tdom ne $udom) { next; }
                   6499: 		}
                   6500: 		if ($tcrs) {
                   6501: 		    if ($tcrs ne $ucrs) { next; }
                   6502: 		}
                   6503: 		if ($tsec) {
                   6504: 		    if ($tsec ne $usec) { next; }
                   6505: 		}
                   6506: 		$access=($effect eq 'allow');
                   6507: 		last;
                   6508: 	    }
                   6509: 	    if ($realm eq '' && $role eq '') {
                   6510: 		$access=($effect eq 'allow');
                   6511: 	    }
1.402     bowersj2 6512: 	}
1.341     www      6513:     }
                   6514:     return $access;
                   6515: }
                   6516: 
1.103     harris41 6517: # ------------------------------------------------- Check for a user privilege
1.12      www      6518: 
                   6519: sub allowed {
1.810     raeburn  6520:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6521:     my $ver_orguri=$uri;
1.439     www      6522:     $uri=&deversion($uri);
1.152     www      6523:     my $orguri=$uri;
1.52      www      6524:     $uri=&declutter($uri);
1.809     raeburn  6525: 
1.810     raeburn  6526:     if ($priv eq 'evb') {
                   6527: # Evade communication block restrictions for specified role in a course
                   6528:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6529:             return $1;
                   6530:         } else {
                   6531:             return;
                   6532:         }
                   6533:     }
                   6534: 
1.620     albertel 6535:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6536: # Free bre access to adm and meta resources
1.775     albertel 6537:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6538: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6539: 	&& ($priv eq 'bre')) {
1.14      www      6540: 	return 'F';
1.159     www      6541:     }
                   6542: 
1.545     banghart 6543: # Free bre access to user's own portfolio contents
1.714     raeburn  6544:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6545:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6546: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6547:         my %setters;
                   6548:         my ($startblock,$endblock) = 
                   6549:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6550:         if ($startblock && $endblock) {
                   6551:             return 'B';
                   6552:         } else {
                   6553:             return 'F';
                   6554:         }
1.545     banghart 6555:     }
                   6556: 
1.762     raeburn  6557: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6558:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6559:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6560:         if (exists($env{'request.course.id'})) {
                   6561:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6562:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6563:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6564:                 my $courseprivid=$env{'request.course.id'};
                   6565:                 $courseprivid=~s/\_/\//;
                   6566:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6567:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6568:                     return $1; 
1.762     raeburn  6569:                 } else {
                   6570:                     if ($env{'request.course.sec'}) {
                   6571:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6572:                     }
                   6573:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6574:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6575:                         return $2;
                   6576:                     }
1.714     raeburn  6577:                 }
                   6578:             }
                   6579:         }
                   6580:     }
                   6581: 
1.159     www      6582: # Free bre to public access
                   6583: 
                   6584:     if ($priv eq 'bre') {
1.238     www      6585:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6586: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6587:            return 'F'; 
                   6588:         }
1.238     www      6589:         if ($copyright eq 'priv') {
                   6590:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6591: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6592: 		return '';
                   6593:             }
                   6594:         }
                   6595:         if ($copyright eq 'domain') {
                   6596:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6597: 	    unless (($env{'user.domain'} eq $1) ||
                   6598:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6599: 		return '';
                   6600:             }
1.262     matthew  6601:         }
1.620     albertel 6602:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6603:             # Library role, so allow browsing of resources in this domain.
                   6604:             return 'F';
1.238     www      6605:         }
1.341     www      6606:         if ($copyright eq 'custom') {
                   6607: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6608:         }
1.14      www      6609:     }
1.264     matthew  6610:     # Domain coordinator is trying to create a course
1.620     albertel 6611:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6612:         # uri is the requested domain in this case.
                   6613:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6614:         # a role of dc for the domain in question.
1.620     albertel 6615:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6616:     }
1.29      www      6617: 
1.52      www      6618:     my $thisallowed='';
                   6619:     my $statecond=0;
                   6620:     my $courseprivid='';
                   6621: 
1.1039    raeburn  6622:     my $ownaccess;
1.1043    raeburn  6623:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6624:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6625:         if ($uri eq '') {
                   6626:             $ownaccess = 1;
                   6627:         } else {
                   6628:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6629:                 my $udom = $env{'user.domain'};
                   6630:                 my $uname = $env{'user.name'};
                   6631:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6632:                     $ownaccess = 1;
1.1040    raeburn  6633:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6634:                     unless ($uri =~ m{\.\./}) {
                   6635:                         $ownaccess = 1;
                   6636:                     }
                   6637:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6638:                     my $now = time;
                   6639:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6640:                         my $adom = $1;
                   6641:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6642:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6643:                                 my ($start,$end) = split('.',$env{$key});
                   6644:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6645:                                     $ownaccess = 1;
                   6646:                                     last;
                   6647:                                 }
                   6648:                             }
                   6649:                         }
                   6650:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6651:                         my $adom = $1;
                   6652:                         my $aname = $2;
1.1042    raeburn  6653:                         foreach my $role ('ca','aa') { 
                   6654:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6655:                                 my ($start,$end) =
                   6656:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6657:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6658:                                     $ownaccess = 1;
                   6659:                                     last;
                   6660:                                 }
1.1039    raeburn  6661:                             }
                   6662:                         }
                   6663:                     }
                   6664:                 }
                   6665:             }
                   6666:         }
                   6667:     }
                   6668: 
1.52      www      6669: # Course
                   6670: 
1.620     albertel 6671:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6672:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6673:             $thisallowed.=$1;
                   6674:         }
1.52      www      6675:     }
1.29      www      6676: 
1.52      www      6677: # Domain
                   6678: 
1.620     albertel 6679:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6680:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6681:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6682:             $thisallowed.=$1;
                   6683:         }
1.12      www      6684:     }
1.52      www      6685: 
1.1141    raeburn  6686: # User who is not author or co-author might still be able to edit
                   6687: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6688:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6689:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6690:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6691:             $thisallowed.=$1;
                   6692:         }
                   6693:     }
                   6694: 
1.52      www      6695: # Course: uri itself is a course
1.66      www      6696:     my $courseuri=$uri;
                   6697:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6698:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6699: 
1.620     albertel 6700:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6701:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6702:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6703:             $thisallowed.=$1;
                   6704:         }
1.12      www      6705:     }
1.29      www      6706: 
1.665     albertel 6707: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6708: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6709:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6710: 	$thisallowed='';
1.671     raeburn  6711:         my ($match)=&is_on_map($uri);
                   6712:         if ($match) {
                   6713:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6714:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6715:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6716:                 if (@blockers > 0) {
                   6717:                     $thisallowed = 'B';
                   6718:                 } else {
                   6719:                     $thisallowed.=$1;
                   6720:                 }
1.671     raeburn  6721:             }
                   6722:         } else {
1.705     albertel 6723:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6724:             if ($refuri) {
                   6725:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6726:                     $thisallowed='F';
1.671     raeburn  6727:                 } else {
                   6728:                     $refuri=&declutter($refuri);
                   6729:                     my ($match) = &is_on_map($refuri);
                   6730:                     if ($match) {
1.1162    raeburn  6731:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6732:                         if (@blockers > 0) {
                   6733:                             $thisallowed = 'B';
                   6734:                         } else {
                   6735:                             $thisallowed='F';
                   6736:                         }
1.671     raeburn  6737:                     }
1.669     raeburn  6738:                 }
1.671     raeburn  6739:             }
                   6740:         }
1.314     www      6741:     }
1.492     albertel 6742: 
1.766     albertel 6743:     if ($priv eq 'bre'
                   6744: 	&& $thisallowed ne 'F' 
                   6745: 	&& $thisallowed ne '2'
                   6746: 	&& &is_portfolio_url($uri)) {
                   6747: 	$thisallowed = &portfolio_access($uri);
                   6748:     }
1.1250    raeburn  6749: 
1.52      www      6750: # Full access at system, domain or course-wide level? Exit.
1.29      www      6751:     if ($thisallowed=~/F/) {
                   6752: 	return 'F';
                   6753:     }
                   6754: 
1.52      www      6755: # If this is generating or modifying users, exit with special codes
1.29      www      6756: 
1.643     www      6757:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6758: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6759: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6760: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6761: 	    unless ($auname) { return $thisallowed; }
                   6762: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6763: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6764: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6765: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6766: 	}
1.52      www      6767: 	return $thisallowed;
                   6768:     }
                   6769: #
1.103     harris41 6770: # Gathered so far: system, domain and course wide privileges
1.52      www      6771: #
                   6772: # Course: See if uri or referer is an individual resource that is part of 
                   6773: # the course
                   6774: 
1.620     albertel 6775:     if ($env{'request.course.id'}) {
1.232     www      6776: 
1.620     albertel 6777:        $courseprivid=$env{'request.course.id'};
                   6778:        if ($env{'request.course.sec'}) {
                   6779:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6780:        }
                   6781:        $courseprivid=~s/\_/\//;
                   6782:        my $checkreferer=1;
1.232     www      6783:        my ($match,$cond)=&is_on_map($uri);
                   6784:        if ($match) {
                   6785:            $statecond=$cond;
1.620     albertel 6786:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6787:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6788:                my $value = $1;
                   6789:                if ($priv eq 'bre') {
                   6790:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6791:                    if (@blockers > 0) {
                   6792:                        $thisallowed = 'B';
                   6793:                    } else {
                   6794:                        $thisallowed.=$value;
                   6795:                    }
                   6796:                } else {
                   6797:                    $thisallowed.=$value;
                   6798:                }
1.52      www      6799:                $checkreferer=0;
                   6800:            }
1.29      www      6801:        }
1.83      www      6802:        
1.148     www      6803:        if ($checkreferer) {
1.620     albertel 6804: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6805:             unless ($refuri) {
1.800     albertel 6806:                 foreach my $key (keys(%env)) {
                   6807: 		    if ($key=~/^httpref\..*\*/) {
                   6808: 			my $pattern=$key;
1.156     www      6809:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6810:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6811:                         $pattern=~s/\//\\\//g;
1.152     www      6812:                         if ($orguri=~/$pattern/) {
1.800     albertel 6813: 			    $refuri=$env{$key};
1.148     www      6814:                         }
                   6815:                     }
1.191     harris41 6816:                 }
1.148     www      6817:             }
1.232     www      6818: 
1.148     www      6819:          if ($refuri) { 
1.152     www      6820: 	  $refuri=&declutter($refuri);
1.232     www      6821:           my ($match,$cond)=&is_on_map($refuri);
                   6822:             if ($match) {
                   6823:               my $refstatecond=$cond;
1.620     albertel 6824:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6825:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6826:                   my $value = $1;
                   6827:                   if ($priv eq 'bre') {
                   6828:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6829:                       if (@blockers > 0) {
                   6830:                           $thisallowed = 'B';
                   6831:                       } else {
                   6832:                           $thisallowed.=$value;
                   6833:                       }
                   6834:                   } else {
                   6835:                       $thisallowed.=$value;
                   6836:                   }
1.53      www      6837:                   $uri=$refuri;
                   6838:                   $statecond=$refstatecond;
1.52      www      6839:               }
                   6840:           }
1.148     www      6841:         }
1.29      www      6842:        }
1.52      www      6843:    }
1.29      www      6844: 
1.52      www      6845: #
1.103     harris41 6846: # Gathered now: all privileges that could apply, and condition number
1.52      www      6847: # 
                   6848: #
                   6849: # Full or no access?
                   6850: #
1.29      www      6851: 
1.52      www      6852:     if ($thisallowed=~/F/) {
                   6853: 	return 'F';
                   6854:     }
1.29      www      6855: 
1.52      www      6856:     unless ($thisallowed) {
                   6857:         return '';
                   6858:     }
1.29      www      6859: 
1.52      www      6860: # Restrictions exist, deal with them
                   6861: #
                   6862: #   C:according to course preferences
                   6863: #   R:according to resource settings
                   6864: #   L:unless locked
                   6865: #   X:according to user session state
                   6866: #
                   6867: 
                   6868: # Possibly locked functionality, check all courses
1.54      www      6869: # Locks might take effect only after 10 minutes cache expiration for other
                   6870: # courses, and 2 minutes for current course
1.52      www      6871: 
                   6872:     my $envkey;
                   6873:     if ($thisallowed=~/L/) {
1.1000    raeburn  6874:         foreach $envkey (keys(%env)) {
1.54      www      6875:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6876:                my $courseid=$2;
                   6877:                my $roleid=$1.'.'.$2;
1.92      www      6878:                $courseid=~s/^\///;
1.54      www      6879:                my $expiretime=600;
1.620     albertel 6880:                if ($env{'request.role'} eq $roleid) {
1.54      www      6881: 		  $expiretime=120;
                   6882:                }
                   6883: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6884:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6885:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6886: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6887:                }
1.620     albertel 6888:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6889:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6890: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6891:                        &log($env{'user.domain'},$env{'user.name'},
                   6892:                             $env{'user.home'},
1.57      www      6893:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6894:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6895:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6896: 		       return '';
                   6897:                    }
                   6898:                }
1.620     albertel 6899:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6900:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6901: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6902:                        &log($env{'user.domain'},$env{'user.name'},
                   6903:                             $env{'user.home'},
1.57      www      6904:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6905:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6906:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6907: 		       return '';
                   6908:                    }
                   6909:                }
                   6910: 	   }
1.29      www      6911:        }
1.52      www      6912:     }
                   6913:    
                   6914: #
                   6915: # Rest of the restrictions depend on selected course
                   6916: #
                   6917: 
1.620     albertel 6918:     unless ($env{'request.course.id'}) {
1.766     albertel 6919: 	if ($thisallowed eq 'A') {
                   6920: 	    return 'A';
1.814     raeburn  6921:         } elsif ($thisallowed eq 'B') {
                   6922:             return 'B';
1.766     albertel 6923: 	} else {
                   6924: 	    return '1';
                   6925: 	}
1.52      www      6926:     }
1.29      www      6927: 
1.52      www      6928: #
                   6929: # Now user is definitely in a course
                   6930: #
1.53      www      6931: 
                   6932: 
                   6933: # Course preferences
                   6934: 
                   6935:    if ($thisallowed=~/C/) {
1.620     albertel 6936:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6937:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6938:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6939: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6940: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6941: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6942: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6943: 			$env{'request.course.id'});
                   6944: 	   }
1.237     www      6945:            return '';
                   6946:        }
                   6947: 
1.620     albertel 6948:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6949: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6950: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6951: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6952: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6953: 			$env{'request.course.id'});
                   6954: 	   }
1.54      www      6955:            return '';
                   6956:        }
1.53      www      6957:    }
                   6958: 
                   6959: # Resource preferences
                   6960: 
                   6961:    if ($thisallowed=~/R/) {
1.620     albertel 6962:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6963:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6964: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6965: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6966: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6967: 	   }
                   6968: 	   return '';
1.54      www      6969:        }
1.53      www      6970:    }
1.30      www      6971: 
1.246     www      6972: # Restricted by state or randomout?
1.30      www      6973: 
1.52      www      6974:    if ($thisallowed=~/X/) {
1.620     albertel 6975:       if ($env{'acc.randomout'}) {
1.579     albertel 6976: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6977:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6978:             return ''; 
                   6979:          }
1.247     www      6980:       }
                   6981:       if (&condval($statecond)) {
1.52      www      6982: 	 return '2';
                   6983:       } else {
                   6984:          return '';
                   6985:       }
                   6986:    }
1.30      www      6987: 
1.766     albertel 6988:     if ($thisallowed eq 'A') {
                   6989: 	return 'A';
1.814     raeburn  6990:     } elsif ($thisallowed eq 'B') {
                   6991:         return 'B';
1.766     albertel 6992:     }
1.52      www      6993:    return 'F';
1.232     www      6994: }
1.1162    raeburn  6995: 
1.1192    raeburn  6996: # ------------------------------------------- Check construction space access
                   6997: 
                   6998: sub constructaccess {
                   6999:     my ($url,$setpriv)=@_;
                   7000: 
                   7001: # We do not allow editing of previous versions of files
                   7002:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7003: 
                   7004: # Get username and domain from URL
                   7005:     my ($ownername,$ownerdomain,$ownerhome);
                   7006: 
                   7007:     ($ownerdomain,$ownername) =
                   7008:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7009: 
                   7010: # The URL does not really point to any authorspace, forget it
                   7011:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7012: 
                   7013: # Now we need to see if the user has access to the authorspace of
                   7014: # $ownername at $ownerdomain
                   7015: 
                   7016:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7017: # Real author for this?
                   7018:        $ownerhome = $env{'user.home'};
                   7019:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7020:           return ($ownername,$ownerdomain,$ownerhome);
                   7021:        }
                   7022:     } else {
                   7023: # Co-author for this?
                   7024:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7025:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7026:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7027:             return ($ownername,$ownerdomain,$ownerhome);
                   7028:         }
                   7029:     }
                   7030: 
                   7031: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7032: # we might as well leave
                   7033:    unless ($setpriv) { return ''; }
                   7034: 
                   7035: # Backdoor access?
                   7036:     my $allowed=&allowed('eco',$ownerdomain);
                   7037: # Nope
                   7038:     unless ($allowed) { return ''; }
                   7039: # Looks like we may have access, but could be locked by the owner of the construction space
                   7040:     if ($allowed eq 'U') {
                   7041:         my %blocked=&get('environment',['domcoord.author'],
                   7042:                          $ownerdomain,$ownername);
                   7043: # Is blocked by owner
                   7044:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7045:     }
                   7046:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7047: # Grant temporary access
                   7048:         my $then=$env{'user.login.time'};
1.1209    raeburn  7049:         my $update=$env{'user.update.time'};
1.1192    raeburn  7050:         if (!$update) { $update = $then; }
                   7051:         my $refresh=$env{'user.refresh.time'};
                   7052:         if (!$refresh) { $refresh = $update; }
                   7053:         my $now = time;
                   7054:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7055:                            $now,'ca','constructaccess');
                   7056:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7057:         return($ownername,$ownerdomain,$ownerhome);
                   7058:     }
                   7059: # No business here
                   7060:     return '';
                   7061: }
                   7062: 
1.1162    raeburn  7063: sub get_comm_blocks {
                   7064:     my ($cdom,$cnum) = @_;
                   7065:     if ($cdom eq '' || $cnum eq '') {
                   7066:         return unless ($env{'request.course.id'});
                   7067:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7068:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7069:     }
                   7070:     my %commblocks;
                   7071:     my $hashid=$cdom.'_'.$cnum;
                   7072:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7073:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7074:         %commblocks = %{$blocksref};
                   7075:     } else {
                   7076:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7077:         my $cachetime = 600;
                   7078:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7079:     }
                   7080:     return %commblocks;
                   7081: }
                   7082: 
                   7083: sub has_comm_blocking {
                   7084:     my ($priv,$symb,$uri,$blocks) = @_;
                   7085:     return unless ($env{'request.course.id'});
                   7086:     return unless ($priv eq 'bre');
                   7087:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7088:     my %commblocks;
                   7089:     if (ref($blocks) eq 'HASH') {
                   7090:         %commblocks = %{$blocks};
                   7091:     } else {
                   7092:         %commblocks = &get_comm_blocks();
                   7093:     }
                   7094:     return unless (keys(%commblocks) > 0);
                   7095:     if (!$symb) { $symb=&symbread($uri,1); }
                   7096:     my ($map,$resid,undef)=&decode_symb($symb);
                   7097:     my %tocheck = (
                   7098:                     maps      => $map,
                   7099:                     resources => $symb,
                   7100:                   );
                   7101:     my @blockers;
                   7102:     my $now = time;
1.1163    raeburn  7103:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7104:     foreach my $block (keys(%commblocks)) {
                   7105:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7106:             my ($start,$end) = ($1,$2);
                   7107:             if ($start <= $now && $end >= $now) {
                   7108:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7109:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7110:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7111:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7112:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7113:                                     push(@blockers,$block);
                   7114:                                 }
                   7115:                             }
                   7116:                         }
                   7117:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7118:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7119:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7120:                                     push(@blockers,$block);
                   7121:                                 }
                   7122:                             }
                   7123:                         }
                   7124:                     }
                   7125:                 }
                   7126:             }
                   7127:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7128:             my $item = $1;
1.1163    raeburn  7129:             my @to_test;
1.1162    raeburn  7130:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7131:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7132:                     my $check_interval;
                   7133:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7134:                         my @interval;
                   7135:                         my $type = 'map';
                   7136:                         if ($item eq 'course') {
                   7137:                             $type = 'course';
                   7138:                             @interval=&EXT("resource.0.interval");
                   7139:                         } else {
                   7140:                             if ($item =~ /___\d+___/) {
                   7141:                                 $type = 'resource';
                   7142:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7143:                                 if (ref($navmap)) {                        
                   7144:                                     my $res = $navmap->getBySymb($item); 
                   7145:                                     push(@to_test,$res);
                   7146:                                 }
1.1162    raeburn  7147:                             } else {
                   7148:                                 my $mapsymb = &symbread($item,1);
                   7149:                                 if ($mapsymb) {
                   7150:                                     if (ref($navmap)) {
                   7151:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7152:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7153:                                         foreach my $res (@to_test) {
1.1162    raeburn  7154:                                             my $symb = $res->symb();
                   7155:                                             next if ($symb eq $mapsymb);
                   7156:                                             if ($symb ne '') {
                   7157:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7158:                                                 last;
                   7159:                                             }
                   7160:                                         }
                   7161:                                     }
                   7162:                                 }
                   7163:                             }
                   7164:                         }
                   7165:                         if ($interval[0] =~ /\d+/) {
                   7166:                             my $first_access;
                   7167:                             if ($type eq 'resource') {
                   7168:                                 $first_access=&get_first_access($interval[1],$item);
                   7169:                             } elsif ($type eq 'map') {
                   7170:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7171:                             } else {
                   7172:                                 $first_access=&get_first_access($interval[1]);
                   7173:                             }
                   7174:                             if ($first_access) {
                   7175:                                 my $timesup = $first_access+$interval[0];
                   7176:                                 if ($timesup > $now) {
1.1163    raeburn  7177:                                     foreach my $res (@to_test) {
                   7178:                                         if ($res->is_problem()) {
                   7179:                                             if ($res->completable()) {
                   7180:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7181:                                                     push(@blockers,$block);
                   7182:                                                 }
                   7183:                                                 last;
                   7184:                                             }
                   7185:                                         }
1.1162    raeburn  7186:                                     }
                   7187:                                 }
                   7188:                             }
                   7189:                         }
                   7190:                     }
                   7191:                 }
                   7192:             }
                   7193:         }
                   7194:     }
                   7195:     return @blockers;
                   7196: }
                   7197: 
                   7198: sub check_docs_block {
                   7199:     my ($docsblock,$tocheck) =@_;
                   7200:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7201:         return;
                   7202:     }
                   7203:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7204:         if ($tocheck->{'maps'}) {
                   7205:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7206:                 return 1;
                   7207:             }
                   7208:         }
                   7209:     }
                   7210:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7211:         if ($tocheck->{'resources'}) {
                   7212:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7213:                 return 1;
                   7214:             }
                   7215:         }
                   7216:     }
                   7217:     return;
                   7218: }
                   7219: 
1.1133    foxr     7220: #
                   7221: #   Removes the versino from a URI and
                   7222: #   splits it in to its filename and path to the filename.
                   7223: #   Seems like File::Basename could have done this more clearly.
                   7224: #   Parameters:
                   7225: #      $uri   - input URI
                   7226: #   Returns:
                   7227: #     Two element list consisting of 
                   7228: #     $pathname  - the URI up to and excluding the trailing /
                   7229: #     $filename  - The part of the URI following the last /
                   7230: #  NOTE:
                   7231: #    Another realization of this is simply:
                   7232: #    use File::Basename;
                   7233: #    ...
                   7234: #    $uri = shift;
                   7235: #    $filename = basename($uri);
                   7236: #    $path     = dirname($uri);
                   7237: #    return ($filename, $path);
                   7238: #
                   7239: #     The implementation below is probably faster however.
                   7240: #
1.710     albertel 7241: sub split_uri_for_cond {
                   7242:     my $uri=&deversion(&declutter(shift));
                   7243:     my @uriparts=split(/\//,$uri);
                   7244:     my $filename=pop(@uriparts);
                   7245:     my $pathname=join('/',@uriparts);
                   7246:     return ($pathname,$filename);
                   7247: }
1.232     www      7248: # --------------------------------------------------- Is a resource on the map?
                   7249: 
                   7250: sub is_on_map {
1.710     albertel 7251:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7252:     #Trying to find the conditional for the file
1.620     albertel 7253:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7254: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7255:     if ($match) {
1.289     bowersj2 7256: 	return (1,$1);
                   7257:     } else {
1.434     www      7258: 	return (0,0);
1.289     bowersj2 7259:     }
1.12      www      7260: }
                   7261: 
1.427     www      7262: # --------------------------------------------------------- Get symb from alias
                   7263: 
                   7264: sub get_symb_from_alias {
                   7265:     my $symb=shift;
                   7266:     my ($map,$resid,$url)=&decode_symb($symb);
                   7267: # Already is a symb
                   7268:     if ($url) { return $symb; }
                   7269: # Must be an alias
                   7270:     my $aliassymb='';
                   7271:     my %bighash;
1.620     albertel 7272:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7273:                             &GDBM_READER(),0640)) {
                   7274:         my $rid=$bighash{'mapalias_'.$symb};
                   7275: 	if ($rid) {
                   7276: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7277: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7278: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7279: 	}
                   7280:         untie %bighash;
                   7281:     }
                   7282:     return $aliassymb;
                   7283: }
                   7284: 
1.12      www      7285: # ----------------------------------------------------------------- Define Role
                   7286: 
                   7287: sub definerole {
                   7288:   if (allowed('mcr','/')) {
                   7289:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7290:     foreach my $role (split(':',$sysrole)) {
                   7291: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7292:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7293:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7294: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7295:                return "refused:s:$crole&$cqual"; 
                   7296:             }
                   7297:         }
1.191     harris41 7298:     }
1.800     albertel 7299:     foreach my $role (split(':',$domrole)) {
                   7300: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7301:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7302:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7303: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7304:                return "refused:d:$crole&$cqual"; 
                   7305:             }
                   7306:         }
1.191     harris41 7307:     }
1.800     albertel 7308:     foreach my $role (split(':',$courole)) {
                   7309: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7310:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7311:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7312: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7313:                return "refused:c:$crole&$cqual"; 
                   7314:             }
                   7315:         }
1.191     harris41 7316:     }
1.620     albertel 7317:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7318:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7319: 	        "rolesdef_$rolename=".
                   7320:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7321:     return reply($command,$env{'user.home'});
1.12      www      7322:   } else {
                   7323:     return 'refused';
                   7324:   }
1.105     harris41 7325: }
                   7326: 
                   7327: # ---------------- Make a metadata query against the network of library servers
                   7328: 
                   7329: sub metadata_query {
1.1237    raeburn  7330:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7331:     my %rhash;
1.845     albertel 7332:     my %libserv = &all_library();
1.244     matthew  7333:     my @server_list = (defined($server_array) ? @$server_array
                   7334:                                               : keys(%libserv) );
                   7335:     for my $server (@server_list) {
1.1237    raeburn  7336:         my $domains = ''; 
                   7337:         if (ref($domains_hash) eq 'HASH') {
                   7338:             $domains = $domains_hash->{$server}; 
                   7339:         }
1.118     harris41 7340: 	unless ($custom or $customshow) {
1.1237    raeburn  7341: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7342: 	    $rhash{$server}=$reply;
                   7343: 	}
                   7344: 	else {
                   7345: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7346: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7347: 			     $server);
                   7348: 	    $rhash{$server}=$reply;
                   7349: 	}
1.112     harris41 7350:     }
1.118     harris41 7351:     return \%rhash;
1.240     www      7352: }
                   7353: 
                   7354: # ----------------------------------------- Send log queries and wait for reply
                   7355: 
                   7356: sub log_query {
                   7357:     my ($uname,$udom,$query,%filters)=@_;
                   7358:     my $uhome=&homeserver($uname,$udom);
                   7359:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7360:     my $uhost=&hostname($uhome);
1.800     albertel 7361:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7362:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7363:                        $uhome);
1.479     albertel 7364:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7365:     return get_query_reply($queryid);
                   7366: }
                   7367: 
1.818     raeburn  7368: # -------------------------- Update MySQL table for portfolio file
                   7369: 
                   7370: sub update_portfolio_table {
1.821     raeburn  7371:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7372:     if ($group ne '') {
                   7373:         $file_name =~s /^\Q$group\E//;
                   7374:     }
1.818     raeburn  7375:     my $homeserver = &homeserver($uname,$udom);
                   7376:     my $queryid=
1.821     raeburn  7377:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7378:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7379:     my $reply = &get_query_reply($queryid);
                   7380:     return $reply;
                   7381: }
                   7382: 
1.899     raeburn  7383: # -------------------------- Update MySQL allusers table
                   7384: 
                   7385: sub update_allusers_table {
                   7386:     my ($uname,$udom,$names) = @_;
                   7387:     my $homeserver = &homeserver($uname,$udom);
                   7388:     my $queryid=
                   7389:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7390:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7391:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7392:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7393:                'generation='.&escape($names->{'generation'}).'%%'.
                   7394:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7395:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7396:     return;
1.899     raeburn  7397: }
                   7398: 
1.508     raeburn  7399: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7400: 
                   7401: sub fetch_enrollment_query {
1.511     raeburn  7402:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7403:     my $homeserver;
1.547     raeburn  7404:     my $maxtries = 1;
1.508     raeburn  7405:     if ($context eq 'automated') {
                   7406:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7407:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7408:     } else {
                   7409:         $homeserver = &homeserver($cnum,$dom);
                   7410:     }
1.838     albertel 7411:     my $host=&hostname($homeserver);
1.506     raeburn  7412:     my $cmd = '';
1.1000    raeburn  7413:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7414:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7415:     }
                   7416:     $cmd =~ s/%%$//;
                   7417:     $cmd = &escape($cmd);
                   7418:     my $query = 'fetchenrollment';
1.620     albertel 7419:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7420:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7421:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7422:         return 'error: '.$queryid;
                   7423:     }
1.506     raeburn  7424:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7425:     my $tries = 1;
                   7426:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7427:         $reply = &get_query_reply($queryid);
                   7428:         $tries ++;
                   7429:     }
1.526     raeburn  7430:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7431:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7432:     } else {
1.901     albertel 7433:         my @responses = split(/:/,$reply);
1.515     raeburn  7434:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7435:             foreach my $line (@responses) {
                   7436:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7437:                 $$replyref{$key} = $value;
                   7438:             }
                   7439:         } else {
1.1117    foxr     7440:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7441:             foreach my $line (@responses) {
                   7442:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7443:                 $$replyref{$key} = $value;
                   7444:                 if ($value > 0) {
1.800     albertel 7445:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7446:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7447:                         my $destname = $pathname.'/'.$filename;
                   7448:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7449:                         if ($xml_classlist =~ /^error/) {
                   7450:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7451:                         } else {
1.506     raeburn  7452:                             if ( open(FILE,">$destname") ) {
                   7453:                                 print FILE &unescape($xml_classlist);
                   7454:                                 close(FILE);
1.526     raeburn  7455:                             } else {
                   7456:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7457:                             }
                   7458:                         }
                   7459:                     }
                   7460:                 }
                   7461:             }
                   7462:         }
                   7463:         return 'ok';
                   7464:     }
                   7465:     return 'error';
                   7466: }
                   7467: 
1.242     www      7468: sub get_query_reply {
                   7469:     my $queryid=shift;
1.1117    foxr     7470:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7471:     my $reply='';
                   7472:     for (1..100) {
                   7473: 	sleep 2;
                   7474:         if (-e $replyfile.'.end') {
1.448     albertel 7475: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7476: 		$reply = join('',<$fh>);
                   7477: 		close($fh);
1.240     www      7478: 	   } else { return 'error: reply_file_error'; }
1.242     www      7479:            return &unescape($reply);
                   7480: 	}
1.240     www      7481:     }
1.242     www      7482:     return 'timeout:'.$queryid;
1.240     www      7483: }
                   7484: 
                   7485: sub courselog_query {
1.241     www      7486: #
                   7487: # possible filters:
                   7488: # url: url or symb
                   7489: # username
                   7490: # domain
                   7491: # action: view, submit, grade
                   7492: # start: timestamp
                   7493: # end: timestamp
                   7494: #
1.240     www      7495:     my (%filters)=@_;
1.620     albertel 7496:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7497:     if ($filters{'url'}) {
                   7498: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7499:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7500:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7501:     }
1.620     albertel 7502:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7503:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7504:     return &log_query($cname,$cdom,'courselog',%filters);
                   7505: }
                   7506: 
                   7507: sub userlog_query {
1.858     raeburn  7508: #
                   7509: # possible filters:
                   7510: # action: log check role
                   7511: # start: timestamp
                   7512: # end: timestamp
                   7513: #
1.240     www      7514:     my ($uname,$udom,%filters)=@_;
                   7515:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7516: }
                   7517: 
1.506     raeburn  7518: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7519: 
                   7520: sub auto_run {
1.508     raeburn  7521:     my ($cnum,$cdom) = @_;
1.876     raeburn  7522:     my $response = 0;
                   7523:     my $settings;
                   7524:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7525:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7526:         $settings = $domconfig{'autoenroll'};
                   7527:         if ($settings->{'run'} eq '1') {
                   7528:             $response = 1;
                   7529:         }
                   7530:     } else {
1.934     raeburn  7531:         my $homeserver;
                   7532:         if (&is_course($cdom,$cnum)) {
                   7533:             $homeserver = &homeserver($cnum,$cdom);
                   7534:         } else {
                   7535:             $homeserver = &domain($cdom,'primary');
                   7536:         }
                   7537:         if ($homeserver ne 'no_host') {
                   7538:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7539:         }
1.876     raeburn  7540:     }
1.506     raeburn  7541:     return $response;
                   7542: }
1.776     albertel 7543: 
1.506     raeburn  7544: sub auto_get_sections {
1.508     raeburn  7545:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7546:     my $homeserver;
                   7547:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7548:         $homeserver = &homeserver($cnum,$cdom);
                   7549:     }
                   7550:     if (!defined($homeserver)) { 
                   7551:         if ($cdom =~ /^$match_domain$/) {
                   7552:             $homeserver = &domain($cdom,'primary');
                   7553:         }
                   7554:     }
                   7555:     my @secs;
                   7556:     if (defined($homeserver)) {
                   7557:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7558:         unless ($response eq 'refused') {
                   7559:             @secs = split(/:/,$response);
                   7560:         }
1.506     raeburn  7561:     }
                   7562:     return @secs;
                   7563: }
1.776     albertel 7564: 
1.506     raeburn  7565: sub auto_new_course {
1.1099    raeburn  7566:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7567:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7568:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7569:     return $response;
                   7570: }
1.776     albertel 7571: 
1.506     raeburn  7572: sub auto_validate_courseID {
1.508     raeburn  7573:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7574:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7575:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7576:     return $response;
                   7577: }
1.776     albertel 7578: 
1.1007    raeburn  7579: sub auto_validate_instcode {
1.1020    raeburn  7580:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7581:     my ($homeserver,$response);
                   7582:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7583:         $homeserver = &homeserver($cnum,$cdom);
                   7584:     }
                   7585:     if (!defined($homeserver)) {
                   7586:         if ($cdom =~ /^$match_domain$/) {
                   7587:             $homeserver = &domain($cdom,'primary');
                   7588:         }
                   7589:     }
1.1065    raeburn  7590:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7591:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7592:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7593:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7594: }
                   7595: 
1.506     raeburn  7596: sub auto_create_password {
1.873     raeburn  7597:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7598:     my ($homeserver,$response);
1.506     raeburn  7599:     my $create_passwd = 0;
                   7600:     my $authchk = '';
1.873     raeburn  7601:     if ($udom =~ /^$match_domain$/) {
                   7602:         $homeserver = &domain($udom,'primary');
                   7603:     }
                   7604:     if ($homeserver eq '') {
                   7605:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7606:             $homeserver = &homeserver($cnum,$cdom);
                   7607:         }
                   7608:     }
                   7609:     if ($homeserver eq '') {
                   7610:         $authchk = 'nodomain';
1.506     raeburn  7611:     } else {
1.873     raeburn  7612:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7613:         if ($response eq 'refused') {
                   7614:             $authchk = 'refused';
                   7615:         } else {
1.901     albertel 7616:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7617:         }
1.506     raeburn  7618:     }
                   7619:     return ($authparam,$create_passwd,$authchk);
                   7620: }
                   7621: 
1.706     raeburn  7622: sub auto_photo_permission {
                   7623:     my ($cnum,$cdom,$students) = @_;
                   7624:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7625:     my ($outcome,$perm_reqd,$conditions) = 
                   7626: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7627:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7628: 	return (undef,undef);
                   7629:     }
1.706     raeburn  7630:     return ($outcome,$perm_reqd,$conditions);
                   7631: }
                   7632: 
                   7633: sub auto_checkphotos {
                   7634:     my ($uname,$udom,$pid) = @_;
                   7635:     my $homeserver = &homeserver($uname,$udom);
                   7636:     my ($result,$resulttype);
                   7637:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7638: 				   &escape($uname).':'.&escape($pid),
                   7639: 				   $homeserver));
1.709     albertel 7640:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7641: 	return (undef,undef);
                   7642:     }
1.706     raeburn  7643:     if ($outcome) {
                   7644:         ($result,$resulttype) = split(/:/,$outcome);
                   7645:     } 
                   7646:     return ($result,$resulttype);
                   7647: }
                   7648: 
                   7649: sub auto_photochoice {
                   7650:     my ($cnum,$cdom) = @_;
                   7651:     my $homeserver = &homeserver($cnum,$cdom);
                   7652:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7653: 						       &escape($cdom),
                   7654: 						       $homeserver)));
1.709     albertel 7655:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7656: 	return (undef,undef);
                   7657:     }
1.706     raeburn  7658:     return ($update,$comment);
                   7659: }
                   7660: 
                   7661: sub auto_photoupdate {
                   7662:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7663:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7664:     my $host=&hostname($homeserver);
1.706     raeburn  7665:     my $cmd = '';
                   7666:     my $maxtries = 1;
1.800     albertel 7667:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7668:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7669:     }
                   7670:     $cmd =~ s/%%$//;
                   7671:     $cmd = &escape($cmd);
                   7672:     my $query = 'institutionalphotos';
                   7673:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7674:     unless ($queryid=~/^\Q$host\E\_/) {
                   7675:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7676:         return 'error: '.$queryid;
                   7677:     }
                   7678:     my $reply = &get_query_reply($queryid);
                   7679:     my $tries = 1;
                   7680:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7681:         $reply = &get_query_reply($queryid);
                   7682:         $tries ++;
                   7683:     }
                   7684:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7685:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7686:     } else {
                   7687:         my @responses = split(/:/,$reply);
                   7688:         my $outcome = shift(@responses); 
                   7689:         foreach my $item (@responses) {
                   7690:             my ($key,$value) = split(/=/,$item);
                   7691:             $$photo{$key} = $value;
                   7692:         }
                   7693:         return $outcome;
                   7694:     }
                   7695:     return 'error';
                   7696: }
                   7697: 
1.521     raeburn  7698: sub auto_instcode_format {
1.793     albertel 7699:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7700: 	$cat_order) = @_;
1.521     raeburn  7701:     my $courses = '';
1.772     raeburn  7702:     my @homeservers;
1.521     raeburn  7703:     if ($caller eq 'global') {
1.841     albertel 7704: 	my %servers = &get_servers($codedom,'library');
                   7705: 	foreach my $tryserver (keys(%servers)) {
                   7706: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7707: 		push(@homeservers,$tryserver);
                   7708: 	    }
1.584     raeburn  7709:         }
1.1022    raeburn  7710:     } elsif ($caller eq 'requests') {
                   7711:         if ($codedom =~ /^$match_domain$/) {
                   7712:             my $chome = &domain($codedom,'primary');
                   7713:             unless ($chome eq 'no_host') {
                   7714:                 push(@homeservers,$chome);
                   7715:             }
                   7716:         }
1.521     raeburn  7717:     } else {
1.772     raeburn  7718:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7719:     }
1.793     albertel 7720:     foreach my $code (keys(%{$instcodes})) {
                   7721:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7722:     }
                   7723:     chop($courses);
1.772     raeburn  7724:     my $ok_response = 0;
                   7725:     my $response;
                   7726:     while (@homeservers > 0 && $ok_response == 0) {
                   7727:         my $server = shift(@homeservers); 
                   7728:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7729:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7730:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7731: 		split(/:/,$response);
1.772     raeburn  7732:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7733:             push(@{$codetitles},&str2array($codetitles_str));
                   7734:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7735:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7736:             $ok_response = 1;
                   7737:         }
                   7738:     }
                   7739:     if ($ok_response) {
1.521     raeburn  7740:         return 'ok';
1.772     raeburn  7741:     } else {
                   7742:         return $response;
1.521     raeburn  7743:     }
                   7744: }
                   7745: 
1.792     raeburn  7746: sub auto_instcode_defaults {
                   7747:     my ($domain,$returnhash,$code_order) = @_;
                   7748:     my @homeservers;
1.841     albertel 7749: 
                   7750:     my %servers = &get_servers($domain,'library');
                   7751:     foreach my $tryserver (keys(%servers)) {
                   7752: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7753: 	    push(@homeservers,$tryserver);
                   7754: 	}
1.792     raeburn  7755:     }
1.841     albertel 7756: 
1.792     raeburn  7757:     my $response;
1.841     albertel 7758:     foreach my $server (@homeservers) {
1.792     raeburn  7759:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7760:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7761: 	
                   7762: 	foreach my $pair (split(/\&/,$response)) {
                   7763: 	    my ($name,$value)=split(/\=/,$pair);
                   7764: 	    if ($name eq 'code_order') {
                   7765: 		@{$code_order} = split(/\&/,&unescape($value));
                   7766: 	    } else {
                   7767: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7768: 	    }
                   7769: 	}
                   7770: 	return 'ok';
1.792     raeburn  7771:     }
1.841     albertel 7772: 
                   7773:     return $response;
1.1003    raeburn  7774: }
                   7775: 
                   7776: sub auto_possible_instcodes {
1.1007    raeburn  7777:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7778:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7779:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7780:         return;
                   7781:     }
1.1003    raeburn  7782:     my (@homeservers,$uhome);
                   7783:     if (defined(&domain($domain,'primary'))) {
                   7784:         $uhome=&domain($domain,'primary');
                   7785:         push(@homeservers,&domain($domain,'primary'));
                   7786:     } else {
                   7787:         my %servers = &get_servers($domain,'library');
                   7788:         foreach my $tryserver (keys(%servers)) {
                   7789:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7790:                 push(@homeservers,$tryserver);
                   7791:             }
                   7792:         }
                   7793:     }
                   7794:     my $response;
                   7795:     foreach my $server (@homeservers) {
                   7796:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7797:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7798:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7799:             split(':',$response);
                   7800:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7801:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7802:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7803:             my ($name,$value)=split('=',$item);
                   7804:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7805:         }
                   7806:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7807:             my ($name,$value)=split('=',$item);
                   7808:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7809:         }
                   7810:         return 'ok';
                   7811:     }
                   7812:     return $response;
                   7813: }
1.792     raeburn  7814: 
1.1010    raeburn  7815: sub auto_courserequest_checks {
                   7816:     my ($dom) = @_;
1.1020    raeburn  7817:     my ($homeserver,%validations);
                   7818:     if ($dom =~ /^$match_domain$/) {
                   7819:         $homeserver = &domain($dom,'primary');
                   7820:     }
                   7821:     unless ($homeserver eq 'no_host') {
                   7822:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7823:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7824:             my @items = split(/&/,$response);
                   7825:             foreach my $item (@items) {
                   7826:                 my ($key,$value) = split('=',$item);
                   7827:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7828:             }
                   7829:         }
                   7830:     }
1.1010    raeburn  7831:     return %validations; 
                   7832: }
                   7833: 
1.1020    raeburn  7834: sub auto_courserequest_validation {
                   7835:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7836:     my ($homeserver,$response);
                   7837:     if ($dom =~ /^$match_domain$/) {
                   7838:         $homeserver = &domain($dom,'primary');
                   7839:     }
                   7840:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7841:           
1.1020    raeburn  7842:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7843:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7844:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7845:                                     $homeserver));
                   7846:     }
                   7847:     return $response;
                   7848: }
                   7849: 
1.777     albertel 7850: sub auto_validate_class_sec {
1.918     raeburn  7851:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7852:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7853:     my $ownerlist;
                   7854:     if (ref($owners) eq 'ARRAY') {
                   7855:         $ownerlist = join(',',@{$owners});
                   7856:     } else {
                   7857:         $ownerlist = $owners;
                   7858:     }
1.773     raeburn  7859:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7860:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7861:     return $response;
                   7862: }
                   7863: 
1.1248    raeburn  7864: sub auto_crsreq_update {
                   7865:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
                   7866:         $code,$inbound) = @_;
                   7867:     my ($homeserver,%crsreqresponse);
                   7868:     if ($cdom =~ /^$match_domain$/) {
                   7869:         $homeserver = &domain($cdom,'primary');
                   7870:     }
                   7871:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   7872:         my $info;
                   7873:         if (ref($inbound) eq 'HASH') {
                   7874:             $info = &freeze_escape($inbound);
                   7875:         }
                   7876:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   7877:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   7878:                             &escape($ownerdomain).':'.&escape($fullname).':'.
                   7879:                             &escape($title).':'.&escape($code).':'.$info,$homeserver);
                   7880:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7881:             my @items = split(/&/,$response);
                   7882:             foreach my $item (@items) {
                   7883:                 my ($key,$value) = split('=',$item);
                   7884:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   7885:             }
                   7886:         }
                   7887:     }
                   7888:     return \%crsreqresponse;
                   7889: }
                   7890: 
1.679     raeburn  7891: # ------------------------------------------------------- Course Group routines
                   7892: 
                   7893: sub get_coursegroups {
1.809     raeburn  7894:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7895:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7896: }
                   7897: 
1.679     raeburn  7898: sub modify_coursegroup {
                   7899:     my ($cdom,$cnum,$groupsettings) = @_;
                   7900:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7901: }
                   7902: 
1.809     raeburn  7903: sub toggle_coursegroup_status {
                   7904:     my ($cdom,$cnum,$group,$action) = @_;
                   7905:     my ($from_namespace,$to_namespace);
                   7906:     if ($action eq 'delete') {
                   7907:         $from_namespace = 'coursegroups';
                   7908:         $to_namespace = 'deleted_groups';
                   7909:     } else {
                   7910:         $from_namespace = 'deleted_groups';
                   7911:         $to_namespace = 'coursegroups';
                   7912:     }
                   7913:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7914:     if (my $tmp = &error(%curr_group)) {
                   7915:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7916:         return ('read error',$tmp);
                   7917:     } else {
                   7918:         my %savedsettings = %curr_group; 
1.809     raeburn  7919:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7920:         my $deloutcome;
                   7921:         if ($result eq 'ok') {
1.809     raeburn  7922:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7923:         } else {
                   7924:             return ('write error',$result);
                   7925:         }
                   7926:         if ($deloutcome eq 'ok') {
                   7927:             return 'ok';
                   7928:         } else {
                   7929:             return ('delete error',$deloutcome);
                   7930:         }
                   7931:     }
                   7932: }
                   7933: 
1.679     raeburn  7934: sub modify_group_roles {
1.957     raeburn  7935:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7936:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7937:     my $role = 'gr/'.&escape($userprivs);
                   7938:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7939:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7940:     if ($result eq 'ok') {
                   7941:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7942:     }
1.679     raeburn  7943:     return $result;
                   7944: }
                   7945: 
                   7946: sub modify_coursegroup_membership {
                   7947:     my ($cdom,$cnum,$membership) = @_;
                   7948:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7949:     return $result;
                   7950: }
                   7951: 
1.682     raeburn  7952: sub get_active_groups {
                   7953:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7954:     my $now = time;
                   7955:     my %groups = ();
                   7956:     foreach my $key (keys(%env)) {
1.811     albertel 7957:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7958:             my ($start,$end) = split(/\./,$env{$key});
                   7959:             if (($end!=0) && ($end<$now)) { next; }
                   7960:             if (($start!=0) && ($start>$now)) { next; }
                   7961:             if ($1 eq $cdom && $2 eq $cnum) {
                   7962:                 $groups{$3} = $env{$key} ;
                   7963:             }
                   7964:         }
                   7965:     }
                   7966:     return %groups;
                   7967: }
                   7968: 
1.683     raeburn  7969: sub get_group_membership {
                   7970:     my ($cdom,$cnum,$group) = @_;
                   7971:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7972: }
                   7973: 
                   7974: sub get_users_groups {
                   7975:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7976:     my @usersgroups;
1.683     raeburn  7977:     my $cachetime=1800;
                   7978: 
                   7979:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7980:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7981:     if (defined($cached)) {
1.734     albertel 7982:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7983:     } else {  
                   7984:         $grouplist = '';
1.816     raeburn  7985:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7986:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7987:         my $access_end = $env{'course.'.$courseid.
                   7988:                               '.default_enrollment_end_date'};
                   7989:         my $now = time;
                   7990:         foreach my $key (keys(%roleshash)) {
                   7991:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7992:                 my $group = $1;
                   7993:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7994:                     my $start = $2;
                   7995:                     my $end = $1;
                   7996:                     if ($start == -1) { next; } # deleted from group
                   7997:                     if (($start!=0) && ($start>$now)) { next; }
                   7998:                     if (($end!=0) && ($end<$now)) {
                   7999:                         if ($access_end && $access_end < $now) {
                   8000:                             if ($access_end - $end < 86400) {
                   8001:                                 push(@usersgroups,$group);
1.733     raeburn  8002:                             }
                   8003:                         }
1.817     raeburn  8004:                         next;
1.733     raeburn  8005:                     }
1.817     raeburn  8006:                     push(@usersgroups,$group);
1.683     raeburn  8007:                 }
                   8008:             }
                   8009:         }
1.817     raeburn  8010:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8011:         $grouplist = join(':',@usersgroups);
                   8012:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8013:     }
1.733     raeburn  8014:     return @usersgroups;
1.683     raeburn  8015: }
                   8016: 
                   8017: sub devalidate_getgroups_cache {
                   8018:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8019:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8020: 
1.683     raeburn  8021:     my $hashid="$udom:$uname:$courseid";
                   8022:     &devalidate_cache_new('getgroups',$hashid);
                   8023: }
                   8024: 
1.12      www      8025: # ------------------------------------------------------------------ Plain Text
                   8026: 
                   8027: sub plaintext {
1.988     raeburn  8028:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8029:     if ($short =~ m{^cr/}) {
1.758     albertel 8030: 	return (split('/',$short))[-1];
                   8031:     }
1.742     raeburn  8032:     if (!defined($cid)) {
                   8033:         $cid = $env{'request.course.id'};
                   8034:     }
                   8035:     my %rolenames = (
1.1008    raeburn  8036:                       Course    => 'std',
                   8037:                       Community => 'alt1',
1.742     raeburn  8038:                     );
1.1037    raeburn  8039:     if ($cid ne '') {
                   8040:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8041:             unless ($forcedefault) {
                   8042:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8043:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8044:                 return &Apache::lonlocal::mt($roletext);
                   8045:             }
                   8046:         }
                   8047:     }
                   8048:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8049:         (defined($rolenames{$type})) && 
                   8050:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8051:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8052:     } elsif ($cid ne '') {
                   8053:         my $crstype = $env{'course.'.$cid.'.type'};
                   8054:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8055:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8056:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8057:         }
1.742     raeburn  8058:     }
1.1037    raeburn  8059:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8060: }
                   8061: 
                   8062: # ----------------------------------------------------------------- Assign Role
                   8063: 
                   8064: sub assignrole {
1.957     raeburn  8065:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8066:         $context)=@_;
1.21      www      8067:     my $mrole;
                   8068:     if ($role =~ /^cr\//) {
1.393     www      8069:         my $cwosec=$url;
1.811     albertel 8070:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8071: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8072:            my $refused = 1;
                   8073:            if ($context eq 'requestcourses') {
                   8074:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8075:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8076:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8077:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8078:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8079:                            if ($crsenv{'internal.courseowner'} eq
                   8080:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8081:                                $refused = '';
                   8082:                            }
                   8083:                        }
                   8084:                    }
                   8085:                }
                   8086:            }
                   8087:            if ($refused) {
                   8088:                &logthis('Refused custom assignrole: '.
                   8089:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8090:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8091:                return 'refused';
                   8092:            }
1.104     www      8093:         }
1.21      www      8094:         $mrole='cr';
1.678     raeburn  8095:     } elsif ($role =~ /^gr\//) {
                   8096:         my $cwogrp=$url;
1.811     albertel 8097:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8098:         unless (&allowed('mdg',$cwogrp)) {
                   8099:             &logthis('Refused group assignrole: '.
                   8100:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8101:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8102:             return 'refused';
                   8103:         }
                   8104:         $mrole='gr';
1.21      www      8105:     } else {
1.82      www      8106:         my $cwosec=$url;
1.811     albertel 8107:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8108:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8109:             my $refused;
                   8110:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8111:                 if (!(&allowed('c'.$role,$url))) {
                   8112:                     $refused = 1;
                   8113:                 }
                   8114:             } else {
                   8115:                 $refused = 1;
                   8116:             }
1.947     raeburn  8117:             if ($refused) {
1.1045    raeburn  8118:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8119:                 if (!$selfenroll && $context eq 'course') {
                   8120:                     my %crsenv;
                   8121:                     if ($role eq 'cc' || $role eq 'co') {
                   8122:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8123:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8124:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8125:                                 if ($crsenv{'internal.courseowner'} eq 
                   8126:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8127:                                     $refused = '';
                   8128:                                 }
                   8129:                             }
                   8130:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8131:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8132:                                 if ($crsenv{'internal.courseowner'} eq 
                   8133:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8134:                                     $refused = '';
                   8135:                                 }
                   8136:                             }
                   8137:                         }
                   8138:                     }
                   8139:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8140:                     $refused = '';
1.1017    raeburn  8141:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8142:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8143:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8144:                         my $wrongcc;
                   8145:                         if ($cnum =~ /^$match_community$/) {
                   8146:                             $wrongcc = 1 if ($role eq 'cc');
                   8147:                         } else {
                   8148:                             $wrongcc = 1 if ($role eq 'co');
                   8149:                         }
                   8150:                         unless ($wrongcc) {
                   8151:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8152:                             if ($crsenv{'internal.courseowner'} eq 
                   8153:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8154:                                 $refused = '';
                   8155:                             }
1.1017    raeburn  8156:                         }
                   8157:                     }
1.1183    raeburn  8158:                 } elsif ($context eq 'requestauthor') {
                   8159:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8160:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8161:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8162:                             $refused = '';
                   8163:                         } else {
                   8164:                             my %domdefaults = &get_domain_defaults($udom);
                   8165:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8166:                                 my $checkbystatus;
                   8167:                                 if ($env{'user.adv'}) { 
                   8168:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8169:                                     if ($disposition eq 'automatic') {
                   8170:                                         $refused = '';
                   8171:                                     } elsif ($disposition eq '') {
                   8172:                                         $checkbystatus = 1;
                   8173:                                     } 
                   8174:                                 } else {
                   8175:                                     $checkbystatus = 1;
                   8176:                                 }
                   8177:                                 if ($checkbystatus) {
                   8178:                                     if ($env{'environment.inststatus'}) {
                   8179:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8180:                                         foreach my $type (@inststatuses) {
                   8181:                                             if (($type ne '') &&
                   8182:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8183:                                                 $refused = '';
                   8184:                                             }
                   8185:                                         }
                   8186:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8187:                                         $refused = '';
                   8188:                                     }
                   8189:                                 }
                   8190:                             }
                   8191:                         }
                   8192:                     }
1.1017    raeburn  8193:                 }
                   8194:                 if ($refused) {
1.947     raeburn  8195:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8196:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8197: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8198:                     return 'refused';
                   8199:                 }
1.932     raeburn  8200:             }
1.1131    raeburn  8201:         } elsif ($role eq 'au') {
                   8202:             if ($url ne '/'.$udom.'/') {
                   8203:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8204:                          ' to assign author role for '.$uname.':'.$udom.
                   8205:                          ' in domain: '.$url.' refused (wrong domain).');
                   8206:                 return 'refused';
                   8207:             }
1.104     www      8208:         }
1.21      www      8209:         $mrole=$role;
                   8210:     }
1.620     albertel 8211:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8212:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8213:     if ($end) { $command.='_'.$end; }
1.21      www      8214:     if ($start) {
                   8215: 	if ($end) { 
1.81      www      8216:            $command.='_'.$start; 
1.21      www      8217:         } else {
1.81      www      8218:            $command.='_0_'.$start;
1.21      www      8219:         }
                   8220:     }
1.739     raeburn  8221:     my $origstart = $start;
                   8222:     my $origend = $end;
1.957     raeburn  8223:     my $delflag;
1.357     www      8224: # actually delete
                   8225:     if ($deleteflag) {
1.373     www      8226: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8227: # modify command to delete the role
1.620     albertel 8228:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8229:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8230: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8231: # set start and finish to negative values for userrolelog
                   8232:            $start=-1;
                   8233:            $end=-1;
1.957     raeburn  8234:            $delflag = 1;
1.357     www      8235:         }
                   8236:     }
                   8237: # send command
1.349     www      8238:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8239: # log new user role if status is ok
1.349     www      8240:     if ($answer eq 'ok') {
1.663     raeburn  8241: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8242:         if (($role eq 'cc') || ($role eq 'in') ||
                   8243:             ($role eq 'ep') || ($role eq 'ad') ||
                   8244:             ($role eq 'ta') || ($role eq 'st') ||
                   8245:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8246:             ($role eq 'co')) {
1.1200    raeburn  8247: # for course roles, perform group memberships changes triggered by role change.
                   8248:             unless ($role =~ /^gr/) {
                   8249:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8250:                                                  $origstart,$selfenroll,$context);
                   8251:             }
1.1184    raeburn  8252:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8253:                            $selfenroll,$context);
                   8254:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8255:                  ($role eq 'au') || ($role eq 'dc')) {
                   8256:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8257:                            $context);
                   8258:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8259:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8260:                              $context); 
                   8261:         }
1.1053    raeburn  8262:         if ($role eq 'cc') {
                   8263:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8264:         }
1.349     www      8265:     }
                   8266:     return $answer;
1.169     harris41 8267: }
                   8268: 
1.1053    raeburn  8269: sub autoupdate_coowners {
                   8270:     my ($url,$end,$start,$uname,$udom) = @_;
                   8271:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8272:     if (($cdom ne '') && ($cnum ne '')) {
                   8273:         my $now = time;
                   8274:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8275:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8276:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8277:             my $instcode = $coursehash{'internal.coursecode'};
                   8278:             if ($instcode ne '') {
1.1056    raeburn  8279:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8280:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8281:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8282:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8283:                         if ($result eq 'valid') {
                   8284:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8285:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8286:                                     push(@newcoowners,$coowner);
                   8287:                                 }
                   8288:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8289:                                     push(@newcoowners,$uname.':'.$udom);
                   8290:                                 }
                   8291:                                 @newcoowners = sort(@newcoowners);
                   8292:                             } else {
                   8293:                                 push(@newcoowners,$uname.':'.$udom);
                   8294:                             }
                   8295:                         } else {
                   8296:                             if ($coursehash{'internal.co-owners'}) {
                   8297:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8298:                                     unless ($coowner eq $uname.':'.$udom) {
                   8299:                                         push(@newcoowners,$coowner);
                   8300:                                     }
                   8301:                                 }
                   8302:                                 unless (@newcoowners > 0) {
                   8303:                                     $delcoowners = 1;
                   8304:                                     $coowners = '';
                   8305:                                 }
                   8306:                             }
                   8307:                         }
                   8308:                         if (@newcoowners || $delcoowners) {
                   8309:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8310:                                             $delcoowners,@newcoowners);
                   8311:                         }
                   8312:                     }
                   8313:                 }
                   8314:             }
                   8315:         }
                   8316:     }
                   8317: }
                   8318: 
                   8319: sub store_coowners {
                   8320:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8321:     my $cid = $cdom.'_'.$cnum;
                   8322:     my ($coowners,$delresult,$putresult);
                   8323:     if (@newcoowners) {
                   8324:         $coowners = join(',',@newcoowners);
                   8325:         my %coownershash = (
                   8326:                             'internal.co-owners' => $coowners,
                   8327:                            );
                   8328:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8329:         if ($putresult eq 'ok') {
                   8330:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8331:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8332:             }
                   8333:         }
                   8334:     }
                   8335:     if ($delcoowners) {
                   8336:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8337:         if ($delresult eq 'ok') {
                   8338:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8339:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8340:             }
                   8341:         }
                   8342:     }
                   8343:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8344:         my %crsinfo =
                   8345:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8346:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8347:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8348:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8349:         }
                   8350:     }
                   8351: }
                   8352: 
1.169     harris41 8353: # -------------------------------------------------- Modify user authentication
1.197     www      8354: # Overrides without validation
                   8355: 
1.169     harris41 8356: sub modifyuserauth {
                   8357:     my ($udom,$uname,$umode,$upass)=@_;
                   8358:     my $uhome=&homeserver($uname,$udom);
1.197     www      8359:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8360:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8361:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8362:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8363:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8364: 		     &escape($upass),$uhome);
1.620     albertel 8365:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8366:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8367:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8368:     &log($udom,,$uname,$uhome,
1.620     albertel 8369:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8370:                                      $env{'user.name'}.', '.$umode.
1.197     www      8371:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8372:     unless ($reply eq 'ok') {
1.197     www      8373:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8374: 	return 'error: '.$reply;
                   8375:     }   
1.170     harris41 8376:     return 'ok';
1.80      www      8377: }
                   8378: 
1.81      www      8379: # --------------------------------------------------------------- Modify a user
1.80      www      8380: 
1.81      www      8381: sub modifyuser {
1.206     matthew  8382:     my ($udom,    $uname, $uid,
                   8383:         $umode,   $upass, $first,
                   8384:         $middle,  $last,  $gene,
1.1058    raeburn  8385:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8386:     $udom= &LONCAPA::clean_domain($udom);
                   8387:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8388:     my $showcandelete = 'none';
                   8389:     if (ref($candelete) eq 'ARRAY') {
                   8390:         if (@{$candelete} > 0) {
                   8391:             $showcandelete = join(', ',@{$candelete});
                   8392:         }
                   8393:     }
1.81      www      8394:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8395:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8396: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8397:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8398:                                      ' desiredhome not specified'). 
1.620     albertel 8399:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8400:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8401:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8402:     my $newuser;
                   8403:     if ($uhome eq 'no_host') {
                   8404:         $newuser = 1;
                   8405:     }
1.80      www      8406: # ----------------------------------------------------------------- Create User
1.406     albertel 8407:     if (($uhome eq 'no_host') && 
                   8408: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8409:         my $unhome='';
1.844     albertel 8410:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8411:             $unhome = $desiredhome;
1.620     albertel 8412: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8413: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8414:         } else { # load balancing routine for determining $unhome
1.81      www      8415:             my $loadm=10000000;
1.841     albertel 8416: 	    my %servers = &get_servers($udom,'library');
                   8417: 	    foreach my $tryserver (keys(%servers)) {
                   8418: 		my $answer=reply('load',$tryserver);
                   8419: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8420: 		    $loadm=$answer;
                   8421: 		    $unhome=$tryserver;
                   8422: 		}
1.80      www      8423: 	    }
                   8424:         }
                   8425:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8426: 	    return 'error: unable to find a home server for '.$uname.
                   8427:                    ' in domain '.$udom;
1.80      www      8428:         }
                   8429:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8430:                          &escape($upass),$unhome);
                   8431: 	unless ($reply eq 'ok') {
                   8432:             return 'error: '.$reply;
                   8433:         }   
1.230     stredwic 8434:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8435:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8436: 	    return 'error: unable verify users home machine.';
1.80      www      8437:         }
1.209     matthew  8438:     }   # End of creation of new user
1.80      www      8439: # ---------------------------------------------------------------------- Add ID
                   8440:     if ($uid) {
                   8441:        $uid=~tr/A-Z/a-z/;
                   8442:        my %uidhash=&idrget($udom,$uname);
1.196     www      8443:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8444:          && (!$forceid)) {
1.80      www      8445: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8446: 	      return 'error: user id "'.$uid.'" does not match '.
                   8447:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8448:           }
                   8449:        } else {
                   8450: 	  &idput($udom,($uname => $uid));
                   8451:        }
                   8452:     }
                   8453: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8454:     my @tmp=&get('environment',
1.899     raeburn  8455: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8456:                     'permanentemail','inststatus'],
1.134     albertel 8457: 		   $udom,$uname);
1.1075    raeburn  8458:     my (%names,%oldnames);
1.313     matthew  8459:     if ($tmp[0] =~ m/^error:.*/) { 
                   8460:         %names=(); 
                   8461:     } else {
                   8462:         %names = @tmp;
1.1075    raeburn  8463:         %oldnames = %names;
1.313     matthew  8464:     }
1.388     www      8465: #
1.1058    raeburn  8466: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8467: # of users did not contain them), do not overwrite existing values
                   8468: # unless field is in $candelete array ref.  
                   8469: #
                   8470: 
                   8471:     my @fields = ('firstname','middlename','lastname','generation',
                   8472:                   'permanentemail','id');
                   8473:     my %newvalues;
                   8474:     if (ref($candelete) eq 'ARRAY') {
                   8475:         foreach my $field (@fields) {
                   8476:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8477:                 if ($field eq 'firstname') {
                   8478:                     $names{$field} = $first;
                   8479:                 } elsif ($field eq 'middlename') {
                   8480:                     $names{$field} = $middle;
                   8481:                 } elsif ($field eq 'lastname') {
                   8482:                     $names{$field} = $last;
                   8483:                 } elsif ($field eq 'generation') { 
                   8484:                     $names{$field} = $gene;
                   8485:                 } elsif ($field eq 'permanentemail') {
                   8486:                     $names{$field} = $email;
                   8487:                 } elsif ($field eq 'id') {
                   8488:                     $names{$field}  = $uid;
                   8489:                 }
                   8490:             }
                   8491:         }
                   8492:     }
1.388     www      8493:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8494:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8495:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8496:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8497:     if ($email) {
                   8498:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8499:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8500:     }
1.899     raeburn  8501:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8502:     if (defined($inststatus)) {
                   8503:         $names{'inststatus'} = '';
                   8504:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8505:         if (ref($usertypes) eq 'HASH') {
                   8506:             my @okstatuses; 
                   8507:             foreach my $item (split(/:/,$inststatus)) {
                   8508:                 if (defined($usertypes->{$item})) {
                   8509:                     push(@okstatuses,$item);  
                   8510:                 }
                   8511:             }
                   8512:             if (@okstatuses) {
                   8513:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8514:             }
                   8515:         }
                   8516:     }
1.1075    raeburn  8517:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8518:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8519:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8520:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8521:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8522:     } else {
                   8523:         $logmsg .= ' during self creation';
                   8524:     }
1.1075    raeburn  8525:     my $changed;
                   8526:     if ($newuser) {
                   8527:         $changed = 1;
                   8528:     } else {
                   8529:         foreach my $field (@fields) {
                   8530:             if ($names{$field} ne $oldnames{$field}) {
                   8531:                 $changed = 1;
                   8532:                 last;
                   8533:             }
                   8534:         }
                   8535:     }
                   8536:     unless ($changed) {
                   8537:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8538:         &logthis($logmsg);
                   8539:         return 'ok';
                   8540:     }
                   8541:     my $reply = &put('environment', \%names, $udom,$uname);
                   8542:     if ($reply ne 'ok') { 
                   8543:         return 'error: '.$reply;
                   8544:     }
1.1087    raeburn  8545:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8546:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8547:     }
1.1075    raeburn  8548:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8549:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8550:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8551:     &logthis($logmsg);
1.134     albertel 8552:     return 'ok';
1.80      www      8553: }
                   8554: 
1.81      www      8555: # -------------------------------------------------------------- Modify student
1.80      www      8556: 
1.81      www      8557: sub modifystudent {
                   8558:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8559:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8560:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8561:     if (!$cid) {
1.620     albertel 8562: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8563: 	    return 'not_in_class';
                   8564: 	}
1.80      www      8565:     }
                   8566: # --------------------------------------------------------------- Make the user
1.81      www      8567:     my $reply=&modifyuser
1.209     matthew  8568: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8569:          $desiredhome,$email,$inststatus);
1.80      www      8570:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8571:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8572:     # student's environment
1.297     matthew  8573:     $uid = undef if (!$forceid);
1.455     albertel 8574:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8575:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8576:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8577:     return $reply;
                   8578: }
                   8579: 
                   8580: sub modify_student_enrollment {
1.1216    raeburn  8581:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8582:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8583:     my ($cdom,$cnum,$chome);
                   8584:     if (!$cid) {
1.620     albertel 8585: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8586: 	    return 'not_in_class';
                   8587: 	}
1.620     albertel 8588: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8589: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8590:     } else {
                   8591: 	($cdom,$cnum)=split(/_/,$cid);
                   8592:     }
1.620     albertel 8593:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8594:     if (!$chome) {
1.457     raeburn  8595: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8596:     }
1.455     albertel 8597:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8598:     # Make sure the user exists
1.81      www      8599:     my $uhome=&homeserver($uname,$udom);
                   8600:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8601: 	return 'error: no such user';
                   8602:     }
1.297     matthew  8603:     # Get student data if we were not given enough information
                   8604:     if (!defined($first)  || $first  eq '' || 
                   8605:         !defined($last)   || $last   eq '' || 
                   8606:         !defined($uid)    || $uid    eq '' || 
                   8607:         !defined($middle) || $middle eq '' || 
                   8608:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8609:         # They did not supply us with enough data to enroll the student, so
                   8610:         # we need to pick up more information.
1.297     matthew  8611:         my %tmp = &get('environment',
1.294     matthew  8612:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8613:                        ,$udom,$uname);
                   8614: 
1.800     albertel 8615:         #foreach my $key (keys(%tmp)) {
                   8616:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8617:         #}
1.294     matthew  8618:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8619:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8620:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8621:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8622:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8623:     }
1.556     albertel 8624:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8625:     my $user = "$uname:$udom";
                   8626:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8627:     my $reply=cput('classlist',
1.1148    raeburn  8628: 		   {$user => 
1.1216    raeburn  8629: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8630: 		   $cdom,$cnum);
1.1148    raeburn  8631:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8632:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8633:     } else { 
1.81      www      8634: 	return 'error: '.$reply;
                   8635:     }
1.297     matthew  8636:     # Add student role to user
1.83      www      8637:     my $uurl='/'.$cid;
1.81      www      8638:     $uurl=~s/\_/\//g;
                   8639:     if ($usec) {
                   8640: 	$uurl.='/'.$usec;
                   8641:     }
1.1148    raeburn  8642:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8643:                              $selfenroll,$context);
                   8644:     if ($result ne 'ok') {
                   8645:         if ($old_entry{$user} ne '') {
                   8646:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8647:         } else {
                   8648:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8649:         }
                   8650:     }
                   8651:     return $result; 
1.21      www      8652: }
                   8653: 
1.556     albertel 8654: sub format_name {
                   8655:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8656:     my $name;
                   8657:     if ($first ne 'lastname') {
                   8658: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8659:     } else {
                   8660: 	if ($lastname=~/\S/) {
                   8661: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8662: 	    $name=~s/\s+,/,/;
                   8663: 	} else {
                   8664: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8665: 	}
                   8666:     }
                   8667:     $name=~s/^\s+//;
                   8668:     $name=~s/\s+$//;
                   8669:     $name=~s/\s+/ /g;
                   8670:     return $name;
                   8671: }
                   8672: 
1.84      www      8673: # ------------------------------------------------- Write to course preferences
                   8674: 
                   8675: sub writecoursepref {
                   8676:     my ($courseid,%prefs)=@_;
                   8677:     $courseid=~s/^\///;
                   8678:     $courseid=~s/\_/\//g;
                   8679:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8680:     my $chome=homeserver($cnum,$cdomain);
                   8681:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8682: 	return 'error: no such course';
                   8683:     }
                   8684:     my $cstring='';
1.800     albertel 8685:     foreach my $pref (keys(%prefs)) {
                   8686: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8687:     }
1.84      www      8688:     $cstring=~s/\&$//;
                   8689:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8690: }
                   8691: 
                   8692: # ---------------------------------------------------------- Make/modify course
                   8693: 
                   8694: sub createcourse {
1.741     raeburn  8695:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8696:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8697:     $url=&declutter($url);
                   8698:     my $cid='';
1.1028    raeburn  8699:     if ($context eq 'requestcourses') {
                   8700:         my $can_create = 0;
                   8701:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8702:         if ($udom eq $ownerdom) {
                   8703:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8704:                                   $context)) {
                   8705:                 $can_create = 1;
                   8706:             }
                   8707:         } else {
                   8708:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8709:                                            $category);
                   8710:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8711:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8712:                 if (@curr > 0) {
                   8713:                     my @options = qw(approval validate autolimit);
                   8714:                     my $optregex = join('|',@options);
                   8715:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8716:                         $can_create = 1;
                   8717:                     }
                   8718:                 }
                   8719:             }
                   8720:         }
                   8721:         if ($can_create) {
                   8722:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8723:                 unless (&allowed('ccc',$udom)) {
                   8724:                     return 'refused'; 
                   8725:                 }
1.1017    raeburn  8726:             }
                   8727:         } else {
                   8728:             return 'refused';
                   8729:         }
1.1028    raeburn  8730:     } elsif (!&allowed('ccc',$udom)) {
                   8731:         return 'refused';
1.84      www      8732:     }
1.1011    raeburn  8733: # --------------------------------------------------------------- Get Unique ID
                   8734:     my $uname;
                   8735:     if ($cnum =~ /^$match_courseid$/) {
                   8736:         my $chome=&homeserver($cnum,$udom,'true');
                   8737:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8738:             $uname = $cnum;
                   8739:         } else {
1.1038    raeburn  8740:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8741:         }
                   8742:     } else {
1.1038    raeburn  8743:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8744:     }
                   8745:     return $uname if ($uname =~ /^error/);
                   8746: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8747:     if (!defined($course_server)) {
                   8748:         if (defined(&domain($udom,'primary'))) {
                   8749:             $course_server = &domain($udom,'primary');
                   8750:         } else {
                   8751:             $course_server = $env{'user.home'}; 
                   8752:         }
                   8753:     }
                   8754:     my %host_servers =
                   8755:         &Apache::lonnet::get_servers($udom,'library');
                   8756:     unless ($host_servers{$course_server}) {
                   8757:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8758:     }
1.84      www      8759: # ------------------------------------------------------------- Make the course
                   8760:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8761:                       $course_server);
1.84      www      8762:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8763:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8764:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8765: 	return 'error: no such course';
                   8766:     }
1.271     www      8767: # ----------------------------------------------------------------- Course made
1.516     raeburn  8768: # log existence
1.1029    raeburn  8769:     my $now = time;
1.918     raeburn  8770:     my $newcourse = {
                   8771:                     $udom.'_'.$uname => {
1.921     raeburn  8772:                                      description => $description,
                   8773:                                      inst_code   => $inst_code,
                   8774:                                      owner       => $course_owner,
                   8775:                                      type        => $crstype,
1.1029    raeburn  8776:                                      creator     => $env{'user.name'}.':'.
                   8777:                                                     $env{'user.domain'},
                   8778:                                      created     => $now,
                   8779:                                      context     => $context,
1.918     raeburn  8780:                                                 },
                   8781:                     };
1.921     raeburn  8782:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8783: # set toplevel url
1.271     www      8784:     my $topurl=$url;
                   8785:     unless ($nonstandard) {
                   8786: # ------------------------------------------ For standard courses, make top url
                   8787:         my $mapurl=&clutter($url);
1.278     www      8788:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8789:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8790: <map>
                   8791: <resource id="1" type="start"></resource>
                   8792: <resource id="2" src="$mapurl"></resource>
                   8793: <resource id="3" type="finish"></resource>
                   8794: <link index="1" from="1" to="2"></link>
                   8795: <link index="2" from="2" to="3"></link>
                   8796: </map>
                   8797: ENDINITMAP
                   8798:         $topurl=&declutter(
1.638     albertel 8799:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8800:                           );
                   8801:     }
                   8802: # ----------------------------------------------------------- Write preferences
1.84      www      8803:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8804:                      ('description'              => $description,
                   8805:                       'url'                      => $topurl,
                   8806:                       'internal.creator'         => $env{'user.name'}.':'.
                   8807:                                                     $env{'user.domain'},
                   8808:                       'internal.created'         => $now,
                   8809:                       'internal.creationcontext' => $context)
                   8810:                     );
1.84      www      8811:     return '/'.$udom.'/'.$uname;
                   8812: }
                   8813: 
1.1011    raeburn  8814: # ------------------------------------------------------------------- Create ID
                   8815: sub generate_coursenum {
1.1038    raeburn  8816:     my ($udom,$crstype) = @_;
1.1011    raeburn  8817:     my $domdesc = &domain($udom);
                   8818:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8819:     my $first;
                   8820:     if ($crstype eq 'Community') {
                   8821:         $first = '0';
                   8822:     } else {
                   8823:         $first = int(1+rand(9)); 
                   8824:     } 
                   8825:     my $uname=$first.
1.1011    raeburn  8826:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8827:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8828:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8829: # ----------------------------------------------- Make sure that does not exist
                   8830:     my $uhome=&homeserver($uname,$udom,'true');
                   8831:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8832:         if ($crstype eq 'Community') {
                   8833:             $first = '0';
                   8834:         } else {
                   8835:             $first = int(1+rand(9));
                   8836:         }
                   8837:         $uname=$first.
1.1011    raeburn  8838:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8839:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8840:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8841:         $uhome=&homeserver($uname,$udom,'true');
                   8842:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8843:             return 'error: unable to generate unique course-ID';
                   8844:         }
                   8845:     }
                   8846:     return $uname;
                   8847: }
                   8848: 
1.813     albertel 8849: sub is_course {
1.1167    droeschl 8850:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8851:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8852: 
                   8853:     return unless $cdom and $cnum;
                   8854: 
                   8855:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8856:         '.');
                   8857: 
1.1219    raeburn  8858:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8859:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8860: }
                   8861: 
1.1015    raeburn  8862: sub store_userdata {
                   8863:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8864:     my $result;
1.1016    raeburn  8865:     if ($datakey ne '') {
1.1013    raeburn  8866:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8867:             if ($udom eq '' || $uname eq '') {
                   8868:                 $udom = $env{'user.domain'};
                   8869:                 $uname = $env{'user.name'};
                   8870:             }
                   8871:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8872:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8873:                 $result = 'error: no_host';
                   8874:             } else {
                   8875:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8876:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8877: 
                   8878:                 my $namevalue='';
                   8879:                 foreach my $key (keys(%{$storehash})) {
                   8880:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8881:                 }
                   8882:                 $namevalue=~s/\&$//;
1.1224    raeburn  8883:                 unless ($namespace eq 'courserequests') {
                   8884:                     $datakey = &escape($datakey);
                   8885:                 }
1.1105    raeburn  8886:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8887:                                   $namevalue,$uhome);
1.1013    raeburn  8888:             }
                   8889:         } else {
                   8890:             $result = 'error: data to store was not a hash reference'; 
                   8891:         }
                   8892:     } else {
                   8893:         $result= 'error: invalid requestkey'; 
                   8894:     }
                   8895:     return $result;
                   8896: }
                   8897: 
1.21      www      8898: # ---------------------------------------------------------- Assign Custom Role
                   8899: 
                   8900: sub assigncustomrole {
1.957     raeburn  8901:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8902:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8903:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8904: }
                   8905: 
                   8906: # ----------------------------------------------------------------- Revoke Role
                   8907: 
                   8908: sub revokerole {
1.957     raeburn  8909:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8910:     my $now=time;
1.965     raeburn  8911:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8912: }
                   8913: 
                   8914: # ---------------------------------------------------------- Revoke Custom Role
                   8915: 
                   8916: sub revokecustomrole {
1.957     raeburn  8917:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8918:     my $now=time;
1.357     www      8919:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8920:            $deleteflag,$selfenroll,$context);
1.17      www      8921: }
                   8922: 
1.533     banghart 8923: # ------------------------------------------------------------ Disk usage
1.535     albertel 8924: sub diskusage {
1.955     raeburn  8925:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8926:     $directorypath =~ s/\/$//;
                   8927:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8928:                        .&escape($getpropath).':'.&escape($uname).':'
                   8929:                        .&escape($udom),homeserver($uname,$udom));
                   8930:     if ($listing eq 'unknown_cmd') {
                   8931:         if ($getpropath) {
                   8932:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8933:         }
                   8934:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8935:     }
1.514     albertel 8936:     return $listing;
1.512     banghart 8937: }
                   8938: 
1.566     banghart 8939: sub is_locked {
1.1096    raeburn  8940:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8941:     my @check;
                   8942:     my $is_locked;
1.1093    raeburn  8943:     push (@check,$file_name);
1.613     albertel 8944:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8945: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8946:     my ($tmp)=keys(%locked);
                   8947:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8948:     
1.566     banghart 8949:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8950:         $is_locked = 'false';
                   8951:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8952:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8953:                $is_locked = 'true';
1.1096    raeburn  8954:                if (ref($which) eq 'ARRAY') {
                   8955:                    push(@{$which},$entry);
                   8956:                } else {
                   8957:                    last;
                   8958:                }
1.745     raeburn  8959:            }
                   8960:        }
1.566     banghart 8961:     } else {
                   8962:         $is_locked = 'false';
                   8963:     }
1.1093    raeburn  8964:     return $is_locked;
1.566     banghart 8965: }
                   8966: 
1.759     albertel 8967: sub declutter_portfile {
                   8968:     my ($file) = @_;
1.833     albertel 8969:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8970:     return $file;
                   8971: }
                   8972: 
1.559     banghart 8973: # ------------------------------------------------------------- Mark as Read Only
                   8974: 
                   8975: sub mark_as_readonly {
                   8976:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8977:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8978:     my ($tmp)=keys(%current_permissions);
                   8979:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8980:     foreach my $file (@{$files}) {
1.759     albertel 8981: 	$file = &declutter_portfile($file);
1.561     banghart 8982:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8983:     }
1.613     albertel 8984:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8985:     return;
                   8986: }
                   8987: 
1.572     banghart 8988: # ------------------------------------------------------------Save Selected Files
                   8989: 
                   8990: sub save_selected_files {
                   8991:     my ($user, $path, @files) = @_;
                   8992:     my $filename = $user."savedfiles";
1.573     banghart 8993:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8994:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8995:     foreach my $file (@files) {
1.620     albertel 8996:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8997:     }
                   8998:     foreach my $file (@other_files) {
1.574     banghart 8999:         print (OUT $file."\n");
1.572     banghart 9000:     }
1.574     banghart 9001:     close (OUT);
1.572     banghart 9002:     return 'ok';
                   9003: }
                   9004: 
1.574     banghart 9005: sub clear_selected_files {
                   9006:     my ($user) = @_;
                   9007:     my $filename = $user."savedfiles";
1.1117    foxr     9008:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9009:     print (OUT undef);
                   9010:     close (OUT);
                   9011:     return ("ok");    
                   9012: }
                   9013: 
1.572     banghart 9014: sub files_in_path {
                   9015:     my ($user, $path) = @_;
                   9016:     my $filename = $user."savedfiles";
                   9017:     my %return_files;
1.1117    foxr     9018:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9019:     while (my $line_in = <IN>) {
1.574     banghart 9020:         chomp ($line_in);
                   9021:         my @paths_and_file = split (m!/!, $line_in);
                   9022:         my $file_part = pop (@paths_and_file);
                   9023:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9024:         $path_part.='/';
                   9025:         my $path_and_file = $path_part.$file_part;
                   9026:         if ($path_part eq $path) {
                   9027:             $return_files{$file_part}= 'selected';
                   9028:         }
                   9029:     }
1.574     banghart 9030:     close (IN);
                   9031:     return (\%return_files);
1.572     banghart 9032: }
                   9033: 
                   9034: # called in portfolio select mode, to show files selected NOT in current directory
                   9035: sub files_not_in_path {
                   9036:     my ($user, $path) = @_;
                   9037:     my $filename = $user."savedfiles";
                   9038:     my @return_files;
                   9039:     my $path_part;
1.1117    foxr     9040:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9041:     while (my $line = <IN>) {
1.572     banghart 9042:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9043:         my @paths_and_file = split(m|/|, $line);
                   9044:         my $file_part = pop(@paths_and_file);
                   9045:         chomp($file_part);
                   9046:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9047:         $path_part .= '/';
                   9048:         my $path_and_file = $path_part.$file_part;
                   9049:         if ($path_part ne $path) {
1.800     albertel 9050:             push(@return_files, ($path_and_file));
1.572     banghart 9051:         }
                   9052:     }
1.800     albertel 9053:     close(OUT);
1.574     banghart 9054:     return (@return_files);
1.572     banghart 9055: }
                   9056: 
1.745     raeburn  9057: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9058: 
1.745     raeburn  9059: sub get_portfile_permissions {
                   9060:     my ($domain,$user) = @_;
1.613     albertel 9061:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9062:     my ($tmp)=keys(%current_permissions);
                   9063:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9064:     return \%current_permissions;
                   9065: }
                   9066: 
                   9067: #---------------------------------------------Get portfolio file access controls
                   9068: 
1.749     raeburn  9069: sub get_access_controls {
1.745     raeburn  9070:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9071:     my %access;
                   9072:     my $real_file = $file;
                   9073:     $file =~ s/\.meta$//;
1.745     raeburn  9074:     if (defined($file)) {
1.749     raeburn  9075:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9076:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9077:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9078:             }
                   9079:         }
1.745     raeburn  9080:     } else {
1.749     raeburn  9081:         foreach my $key (keys(%{$current_permissions})) {
                   9082:             if ($key =~ /\0accesscontrol$/) {
                   9083:                 if (defined($group)) {
                   9084:                     if ($key !~ m-^\Q$group\E/-) {
                   9085:                         next;
                   9086:                     }
                   9087:                 }
                   9088:                 my ($fullpath) = split(/\0/,$key);
                   9089:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9090:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9091:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9092:                     }
                   9093:                 }
                   9094:             }
                   9095:         }
                   9096:     }
                   9097:     return %access;
                   9098: }
                   9099: 
                   9100: sub modify_access_controls {
                   9101:     my ($file_name,$changes,$domain,$user)=@_;
                   9102:     my ($outcome,$deloutcome);
                   9103:     my %store_permissions;
                   9104:     my %new_values;
                   9105:     my %new_control;
                   9106:     my %translation;
                   9107:     my @deletions = ();
                   9108:     my $now = time;
                   9109:     if (exists($$changes{'activate'})) {
                   9110:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9111:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9112:             my $numnew = scalar(@newitems);
                   9113:             for (my $i=0; $i<$numnew; $i++) {
                   9114:                 my $newkey = $newitems[$i];
                   9115:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9116:                 if ($newkey =~ /^\d+:/) { 
                   9117:                     $newkey =~ s/^(\d+)/$newid/;
                   9118:                     $translation{$1} = $newid;
                   9119:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9120:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9121:                     $translation{$1} = $newid;
                   9122:                 }
1.749     raeburn  9123:                 $new_values{$file_name."\0".$newkey} = 
                   9124:                                           $$changes{'activate'}{$newitems[$i]};
                   9125:                 $new_control{$newkey} = $now;
                   9126:             }
                   9127:         }
                   9128:     }
                   9129:     my %todelete;
                   9130:     my %changed_items;
                   9131:     foreach my $action ('delete','update') {
                   9132:         if (exists($$changes{$action})) {
                   9133:             if (ref($$changes{$action}) eq 'HASH') {
                   9134:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9135:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9136:                     if ($action eq 'delete') { 
                   9137:                         $todelete{$itemnum} = 1;
                   9138:                     } else {
                   9139:                         $changed_items{$itemnum} = $key;
                   9140:                     }
                   9141:                 }
1.745     raeburn  9142:             }
                   9143:         }
1.749     raeburn  9144:     }
                   9145:     # get lock on access controls for file.
                   9146:     my $lockhash = {
                   9147:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9148:                                                        ':'.$env{'user.domain'},
                   9149:                    }; 
                   9150:     my $tries = 0;
                   9151:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9152:    
                   9153:     while (($gotlock ne 'ok') && $tries <3) {
                   9154:         $tries ++;
                   9155:         sleep 1;
                   9156:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9157:     }
                   9158:     if ($gotlock eq 'ok') {
                   9159:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9160:         my ($tmp)=keys(%curr_permissions);
                   9161:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9162:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9163:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9164:             if (ref($curr_controls) eq 'HASH') {
                   9165:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9166:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9167:                     if (defined($todelete{$itemnum})) {
                   9168:                         push(@deletions,$file_name."\0".$control_item);
                   9169:                     } else {
                   9170:                         if (defined($changed_items{$itemnum})) {
                   9171:                             $new_control{$changed_items{$itemnum}} = $now;
                   9172:                             push(@deletions,$file_name."\0".$control_item);
                   9173:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9174:                         } else {
                   9175:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9176:                         }
                   9177:                     }
1.745     raeburn  9178:                 }
                   9179:             }
                   9180:         }
1.970     raeburn  9181:         my ($group);
                   9182:         if (&is_course($domain,$user)) {
                   9183:             ($group,my $file) = split(/\//,$file_name,2);
                   9184:         }
1.749     raeburn  9185:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9186:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9187:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9188:         #  remove lock
                   9189:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9190:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9191:         my $sqlresult =
1.970     raeburn  9192:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9193:                                     $group);
1.749     raeburn  9194:     } else {
                   9195:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9196:     }
1.749     raeburn  9197:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9198: }
                   9199: 
1.827     raeburn  9200: sub make_public_indefinitely {
                   9201:     my ($requrl) = @_;
                   9202:     my $now = time;
                   9203:     my $action = 'activate';
                   9204:     my $aclnum = 0;
                   9205:     if (&is_portfolio_url($requrl)) {
                   9206:         my (undef,$udom,$unum,$file_name,$group) =
                   9207:             &parse_portfolio_url($requrl);
                   9208:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9209:         my %access_controls = &get_access_controls($current_perms,
                   9210:                                                    $group,$file_name);
                   9211:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9212:             my ($num,$scope,$end,$start) = 
                   9213:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9214:             if ($scope eq 'public') {
                   9215:                 if ($start <= $now && $end == 0) {
                   9216:                     $action = 'none';
                   9217:                 } else {
                   9218:                     $action = 'update';
                   9219:                     $aclnum = $num;
                   9220:                 }
                   9221:                 last;
                   9222:             }
                   9223:         }
                   9224:         if ($action eq 'none') {
                   9225:              return 'ok';
                   9226:         } else {
                   9227:             my %changes;
                   9228:             my $newend = 0;
                   9229:             my $newstart = $now;
                   9230:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9231:             $changes{$action}{$newkey} = {
                   9232:                 type => 'public',
                   9233:                 time => {
                   9234:                     start => $newstart,
                   9235:                     end   => $newend,
                   9236:                 },
                   9237:             };
                   9238:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9239:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9240:             return $outcome;
                   9241:         }
                   9242:     } else {
                   9243:         return 'invalid';
                   9244:     }
                   9245: }
                   9246: 
1.745     raeburn  9247: #------------------------------------------------------Get Marked as Read Only
                   9248: 
                   9249: sub get_marked_as_readonly {
                   9250:     my ($domain,$user,$what,$group) = @_;
                   9251:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9252:     my @readonly_files;
1.629     banghart 9253:     my $cmp1=$what;
                   9254:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9255:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9256:         if (defined($group)) {
                   9257:             if ($file_name !~ m-^\Q$group\E/-) {
                   9258:                 next;
                   9259:             }
                   9260:         }
1.561     banghart 9261:         if (ref($value) eq "ARRAY"){
                   9262:             foreach my $stored_what (@{$value}) {
1.629     banghart 9263:                 my $cmp2=$stored_what;
1.759     albertel 9264:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9265:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9266:                 }
1.629     banghart 9267:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9268:                     push(@readonly_files, $file_name);
1.745     raeburn  9269:                     last;
1.563     banghart 9270:                 } elsif (!defined($what)) {
                   9271:                     push(@readonly_files, $file_name);
1.745     raeburn  9272:                     last;
1.561     banghart 9273:                 }
                   9274:             }
1.745     raeburn  9275:         }
1.561     banghart 9276:     }
                   9277:     return @readonly_files;
                   9278: }
1.577     banghart 9279: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9280: 
1.577     banghart 9281: sub get_marked_as_readonly_hash {
1.745     raeburn  9282:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9283:     my %readonly_files;
1.745     raeburn  9284:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9285:         if (defined($group)) {
                   9286:             if ($file_name !~ m-^\Q$group\E/-) {
                   9287:                 next;
                   9288:             }
                   9289:         }
1.577     banghart 9290:         if (ref($value) eq "ARRAY"){
                   9291:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9292:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9293:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9294:                         if ($lock_descriptor eq 'graded') {
                   9295:                             $readonly_files{$file_name} = 'graded';
                   9296:                         } elsif ($lock_descriptor eq 'handback') {
                   9297:                             $readonly_files{$file_name} = 'handback';
                   9298:                         } else {
                   9299:                             if (!exists($readonly_files{$file_name})) {
                   9300:                                 $readonly_files{$file_name} = 'locked';
                   9301:                             }
                   9302:                         }
1.745     raeburn  9303:                     }
1.750     banghart 9304:                 } 
1.577     banghart 9305:             }
                   9306:         } 
                   9307:     }
                   9308:     return %readonly_files;
                   9309: }
1.559     banghart 9310: # ------------------------------------------------------------ Unmark as Read Only
                   9311: 
                   9312: sub unmark_as_readonly {
1.629     banghart 9313:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9314:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9315:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9316:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9317:     my $symb_crs = $what;
                   9318:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9319:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9320:     my ($tmp)=keys(%current_permissions);
                   9321:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9322:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9323:     foreach my $file (@readonly_files) {
1.759     albertel 9324: 	my $clean_file = &declutter_portfile($file);
                   9325: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9326: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9327:         my @new_locks;
                   9328:         my @del_keys;
                   9329:         if (ref($current_locks) eq "ARRAY"){
                   9330:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9331:                 my $compare=$locker;
1.749     raeburn  9332:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9333:                     $compare=join('',@{$locker});
1.746     raeburn  9334:                     if ($compare ne $symb_crs) {
                   9335:                         push(@new_locks, $locker);
                   9336:                     }
1.563     banghart 9337:                 }
                   9338:             }
1.650     albertel 9339:             if (scalar(@new_locks) > 0) {
1.563     banghart 9340:                 $current_permissions{$file} = \@new_locks;
                   9341:             } else {
                   9342:                 push(@del_keys, $file);
1.613     albertel 9343:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9344:                 delete($current_permissions{$file});
1.563     banghart 9345:             }
                   9346:         }
1.561     banghart 9347:     }
1.613     albertel 9348:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9349:     return;
                   9350: }
1.512     banghart 9351: 
1.17      www      9352: # ------------------------------------------------------------ Directory lister
                   9353: 
                   9354: sub dirlist {
1.955     raeburn  9355:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9356:     $uri=~s/^\///;
                   9357:     $uri=~s/\/$//;
1.253     stredwic 9358:     my ($udom, $uname);
1.955     raeburn  9359:     if ($getuserdir) {
1.253     stredwic 9360:         $udom = $userdomain;
                   9361:         $uname = $username;
1.955     raeburn  9362:     } else {
                   9363:         (undef,$udom,$uname)=split(/\//,$uri);
                   9364:         if(defined($userdomain)) {
                   9365:             $udom = $userdomain;
                   9366:         }
                   9367:         if(defined($username)) {
                   9368:             $uname = $username;
                   9369:         }
1.253     stredwic 9370:     }
1.955     raeburn  9371:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9372: 
1.955     raeburn  9373:     $dirRoot = $perlvar{'lonDocRoot'};
                   9374:     if (defined($getpropath)) {
                   9375:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9376:         $dirRoot =~ s/\/$//;
1.955     raeburn  9377:     } elsif (defined($getuserdir)) {
                   9378:         my $subdir=$uname.'__';
                   9379:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9380:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9381:                    ."/$udom/$subdir/$uname";
                   9382:     } elsif (defined($alternateRoot)) {
                   9383:         $dirRoot = $alternateRoot;
1.751     banghart 9384:     }
1.253     stredwic 9385: 
                   9386:     if($udom) {
                   9387:         if($uname) {
1.1135    raeburn  9388:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9389:             if ($uhome eq 'no_host') {
                   9390:                 return ([],'no_host');
                   9391:             }
1.955     raeburn  9392:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9393:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9394:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9395:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9396:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9397:             } else {
                   9398:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9399:             }
1.605     matthew  9400:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9401:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9402:                 @listing_results = split(/:/,$listing);
                   9403:             } else {
                   9404:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9405:             }
1.1135    raeburn  9406:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9407:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9408:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9409:                 return ([],$listing);
                   9410:             } else {
                   9411:                 return (\@listing_results);
1.1135    raeburn  9412:             }
1.955     raeburn  9413:         } elsif(!$alternateRoot) {
1.1136    raeburn  9414:             my (%allusers,%listerror);
1.841     albertel 9415: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9416:  	    foreach my $tryserver (keys(%servers)) {
                   9417:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9418:                                   &escape($udom),$tryserver);
                   9419:                 if ($listing eq 'unknown_cmd') {
                   9420: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9421: 				      $udom, $tryserver);
                   9422:                 } else {
                   9423:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9424:                 }
1.841     albertel 9425: 		if ($listing eq 'unknown_cmd') {
                   9426: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9427: 				      $udom, $tryserver);
                   9428: 		    @listing_results = split(/:/,$listing);
                   9429: 		} else {
                   9430: 		    @listing_results =
                   9431: 			map { &unescape($_); } split(/:/,$listing);
                   9432: 		}
1.1136    raeburn  9433:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9434:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9435:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9436:                     $listerror{$tryserver} = $listing;
                   9437:                 } else {
1.841     albertel 9438: 		    foreach my $line (@listing_results) {
                   9439: 			my ($entry) = split(/&/,$line,2);
                   9440: 			$allusers{$entry} = 1;
                   9441: 		    }
                   9442: 		}
1.253     stredwic 9443:             }
1.1136    raeburn  9444:             my @alluserslist=();
1.800     albertel 9445:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9446:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9447:             }
1.1136    raeburn  9448:             return (\@alluserslist);
1.253     stredwic 9449:         } else {
1.1136    raeburn  9450:             return ([],'missing username');
1.253     stredwic 9451:         }
1.955     raeburn  9452:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9453:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9454:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9455:         return (\@all_domains);
1.955     raeburn  9456:     } else {
1.1136    raeburn  9457:         return ([],'missing domain');
1.275     stredwic 9458:     }
                   9459: }
                   9460: 
                   9461: # --------------------------------------------- GetFileTimestamp
                   9462: # This function utilizes dirlist and returns the date stamp for
                   9463: # when it was last modified.  It will also return an error of -1
                   9464: # if an error occurs
                   9465: 
                   9466: sub GetFileTimestamp {
1.955     raeburn  9467:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9468:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9469:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9470:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9471:                                     undef,$getuserdir);
                   9472:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9473:         return -1;
                   9474:     }
                   9475:     if (ref($fileref) eq 'ARRAY') {
                   9476:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9477:         # @stats contains first the filename, then the stat output
                   9478:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9479:     } else {
                   9480:         return -1;
1.253     stredwic 9481:     }
1.26      www      9482: }
                   9483: 
1.712     albertel 9484: sub stat_file {
                   9485:     my ($uri) = @_;
1.787     albertel 9486:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9487: 
1.955     raeburn  9488:     my ($udom,$uname,$file);
1.712     albertel 9489:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9490: 	($udom,$uname,$file) =
1.811     albertel 9491: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9492: 	$file = 'userfiles/'.$file;
                   9493:     }
                   9494:     if ($uri =~ m-^/res/-) {
                   9495: 	($udom,$uname) = 
1.807     albertel 9496: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9497: 	$file = $uri;
                   9498:     }
                   9499: 
                   9500:     if (!$udom || !$uname || !$file) {
                   9501: 	# unable to handle the uri
                   9502: 	return ();
                   9503:     }
1.956     raeburn  9504:     my $getpropath;
                   9505:     if ($file =~ /^userfiles\//) {
                   9506:         $getpropath = 1;
                   9507:     }
1.1136    raeburn  9508:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9509:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9510:         return ();
                   9511:     } else {
                   9512:         if (ref($listref) eq 'ARRAY') {
                   9513:             my @stats = split('&',$listref->[0]);
                   9514: 	    shift(@stats); #filename is first
                   9515: 	    return @stats;
                   9516:         }
1.712     albertel 9517:     }
                   9518:     return ();
                   9519: }
                   9520: 
1.26      www      9521: # -------------------------------------------------------- Value of a Condition
                   9522: 
1.713     albertel 9523: # gets the value of a specific preevaluated condition
                   9524: #    stored in the string  $env{user.state.<cid>}
                   9525: # or looks up a condition reference in the bighash and if if hasn't
                   9526: # already been evaluated recurses into docondval to get the value of
                   9527: # the condition, then memoizing it to 
                   9528: #   $env{user.state.<cid>.<condition>}
1.40      www      9529: sub directcondval {
                   9530:     my $number=shift;
1.620     albertel 9531:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9532: 	&Apache::lonuserstate::evalstate();
                   9533:     }
1.713     albertel 9534:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9535: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9536:     } elsif ($number =~ /^_/) {
                   9537: 	my $sub_condition;
                   9538: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9539: 		&GDBM_READER(),0640)) {
                   9540: 	    $sub_condition=$bighash{'conditions'.$number};
                   9541: 	    untie(%bighash);
                   9542: 	}
                   9543: 	my $value = &docondval($sub_condition);
1.949     raeburn  9544: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9545: 	return $value;
                   9546:     }
1.620     albertel 9547:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9548:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9549:     } else {
                   9550:        return 2;
                   9551:     }
                   9552: }
                   9553: 
1.713     albertel 9554: # get the collection of conditions for this resource
1.26      www      9555: sub condval {
                   9556:     my $condidx=shift;
1.54      www      9557:     my $allpathcond='';
1.713     albertel 9558:     foreach my $cond (split(/\|/,$condidx)) {
                   9559: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9560: 	    $allpathcond.=
                   9561: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9562: 	}
1.191     harris41 9563:     }
1.54      www      9564:     $allpathcond=~s/\|$//;
1.713     albertel 9565:     return &docondval($allpathcond);
                   9566: }
                   9567: 
                   9568: #evaluates an expression of conditions
                   9569: sub docondval {
                   9570:     my ($allpathcond) = @_;
                   9571:     my $result=0;
                   9572:     if ($env{'request.course.id'}
                   9573: 	&& defined($allpathcond)) {
                   9574: 	my $operand='|';
                   9575: 	my @stack;
                   9576: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9577: 	    if ($chunk eq '(') {
                   9578: 		push @stack,($operand,$result);
                   9579: 	    } elsif ($chunk eq ')') {
                   9580: 		my $before=pop @stack;
                   9581: 		if (pop @stack eq '&') {
                   9582: 		    $result=$result>$before?$before:$result;
                   9583: 		} else {
                   9584: 		    $result=$result>$before?$result:$before;
                   9585: 		}
                   9586: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9587: 		$operand=$chunk;
                   9588: 	    } else {
                   9589: 		my $new=directcondval($chunk);
                   9590: 		if ($operand eq '&') {
                   9591: 		    $result=$result>$new?$new:$result;
                   9592: 		} else {
                   9593: 		    $result=$result>$new?$result:$new;
                   9594: 		}
                   9595: 	    }
                   9596: 	}
1.26      www      9597:     }
                   9598:     return $result;
1.421     albertel 9599: }
                   9600: 
                   9601: # ---------------------------------------------------- Devalidate courseresdata
                   9602: 
                   9603: sub devalidatecourseresdata {
                   9604:     my ($coursenum,$coursedomain)=@_;
                   9605:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9606:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9607: }
                   9608: 
1.763     www      9609: 
1.200     www      9610: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9611: #
                   9612: #  Parameters:
                   9613: #      $coursenum    - Number of the course.
                   9614: #      $coursedomain - Domain at which the course was created.
                   9615: #  Returns:
                   9616: #     A hash of the course parameters along (I think) with timestamps
                   9617: #     and version info.
1.877     foxr     9618: 
1.624     albertel 9619: sub get_courseresdata {
                   9620:     my ($coursenum,$coursedomain)=@_;
1.200     www      9621:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9622:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9623:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9624:     my %dumpreply;
1.417     albertel 9625:     unless (defined($cached)) {
1.624     albertel 9626: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9627: 	$result=\%dumpreply;
1.251     albertel 9628: 	my ($tmp) = keys(%dumpreply);
                   9629: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9630: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9631: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9632: 	    return $tmp;
1.416     albertel 9633: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9634: 	    $result=undef;
1.599     albertel 9635: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9636: 	}
                   9637:     }
1.624     albertel 9638:     return $result;
                   9639: }
                   9640: 
1.633     albertel 9641: sub devalidateuserresdata {
                   9642:     my ($uname,$udom)=@_;
                   9643:     my $hashid="$udom:$uname";
                   9644:     &devalidate_cache_new('userres',$hashid);
                   9645: }
                   9646: 
1.624     albertel 9647: sub get_userresdata {
                   9648:     my ($uname,$udom)=@_;
                   9649:     #most student don\'t have any data set, check if there is some data
                   9650:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9651: 
                   9652:     my $hashid="$udom:$uname";
                   9653:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9654:     if (!defined($cached)) {
                   9655: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9656: 	$result=\%resourcedata;
                   9657: 	&do_cache_new('userres',$hashid,$result,600);
                   9658:     }
                   9659:     my ($tmp)=keys(%$result);
                   9660:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9661: 	return $result;
                   9662:     }
                   9663:     #error 2 occurs when the .db doesn't exist
                   9664:     if ($tmp!~/error: 2 /) {
1.672     albertel 9665: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9666: 		 " Trying to get resource data for ".
                   9667: 		 $uname." at ".$udom.": ".
                   9668: 		 $tmp."</font>");
                   9669:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9670: 	#&EXT_cache_set($udom,$uname);
                   9671: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9672: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9673:     }
                   9674:     return $tmp;
                   9675: }
1.879     foxr     9676: #----------------------------------------------- resdata - return resource data
                   9677: #  Purpose:
                   9678: #    Return resource data for either users or for a course.
                   9679: #  Parameters:
                   9680: #     $name      - Course/user name.
                   9681: #     $domain    - Name of the domain the user/course is registered on.
                   9682: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9683: #     @which     - Array of names of resources desired.
                   9684: #  Returns:
                   9685: #     The value of the first reasource in @which that is found in the
                   9686: #     resource hash.
                   9687: #  Exceptional Conditions:
                   9688: #     If the $type passed in is not valid (not the string 'course' or 
                   9689: #     'user', an undefined  reference is returned.
                   9690: #     If none of the resources are found, an undef is returned
1.624     albertel 9691: sub resdata {
                   9692:     my ($name,$domain,$type,@which)=@_;
                   9693:     my $result;
                   9694:     if ($type eq 'course') {
                   9695: 	$result=&get_courseresdata($name,$domain);
                   9696:     } elsif ($type eq 'user') {
                   9697: 	$result=&get_userresdata($name,$domain);
                   9698:     }
                   9699:     if (!ref($result)) { return $result; }    
1.251     albertel 9700:     foreach my $item (@which) {
1.927     albertel 9701: 	if (defined($result->{$item->[0]})) {
                   9702: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9703: 	}
1.250     albertel 9704:     }
1.291     albertel 9705:     return undef;
1.200     www      9706: }
                   9707: 
1.1236    raeburn  9708: sub get_numsuppfiles {
                   9709:     my ($cnum,$cdom,$ignorecache)=@_;
                   9710:     my $hashid=$cnum.':'.$cdom;
                   9711:     my ($suppcount,$cached);
                   9712:     unless ($ignorecache) {
                   9713:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   9714:     }
                   9715:     unless (defined($cached)) {
                   9716:         my $chome=&homeserver($cnum,$cdom);
                   9717:         unless ($chome eq 'no_host') {
                   9718:             ($suppcount,my $errors) = (0,0);
                   9719:             my $suppmap = 'supplemental.sequence';
                   9720:             ($suppcount,$errors) = 
                   9721:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   9722:         }
                   9723:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   9724:     }
                   9725:     return $suppcount;
                   9726: }
                   9727: 
1.379     matthew  9728: #
                   9729: # EXT resource caching routines
                   9730: #
                   9731: 
                   9732: sub clear_EXT_cache_status {
1.383     albertel 9733:     &delenv('cache.EXT.');
1.379     matthew  9734: }
                   9735: 
                   9736: sub EXT_cache_status {
                   9737:     my ($target_domain,$target_user) = @_;
1.383     albertel 9738:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9739:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9740:         # We know already the user has no data
                   9741:         return 1;
                   9742:     } else {
                   9743:         return 0;
                   9744:     }
                   9745: }
                   9746: 
                   9747: sub EXT_cache_set {
                   9748:     my ($target_domain,$target_user) = @_;
1.383     albertel 9749:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9750:     #&appenv({$cachename => time});
1.379     matthew  9751: }
                   9752: 
1.28      www      9753: # --------------------------------------------------------- Value of a Variable
1.58      www      9754: sub EXT {
1.715     albertel 9755: 
1.1228    raeburn  9756:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      9757:     unless ($varname) { return ''; }
1.218     albertel 9758:     #get real user name/domain, courseid and symb
                   9759:     my $courseid;
1.359     albertel 9760:     my $publicuser;
1.427     www      9761:     if ($symbparm) {
                   9762: 	$symbparm=&get_symb_from_alias($symbparm);
                   9763:     }
1.218     albertel 9764:     if (!($uname && $udom)) {
1.790     albertel 9765:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9766:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9767:     } else {
1.620     albertel 9768: 	$courseid=$env{'request.course.id'};
1.218     albertel 9769:     }
1.48      www      9770:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9771:     my $rest;
1.320     albertel 9772:     if (defined($therest[0])) {
1.48      www      9773:        $rest=join('.',@therest);
                   9774:     } else {
                   9775:        $rest='';
                   9776:     }
1.320     albertel 9777: 
1.57      www      9778:     my $qualifierrest=$qualifier;
                   9779:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9780:     my $spacequalifierrest=$space;
                   9781:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9782:     if ($realm eq 'user') {
1.48      www      9783: # --------------------------------------------------------------- user.resource
                   9784: 	if ($space eq 'resource') {
1.651     albertel 9785: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9786: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9787: 		 &&
1.744     albertel 9788: 		 ($symbparm eq &symbread()) ) {	
                   9789: 		# if we are in the middle of processing the resource the
                   9790: 		# get the value we are planning on committing
                   9791:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9792:                     return $Apache::lonhomework::results{$qualifierrest};
                   9793:                 } else {
                   9794:                     return $Apache::lonhomework::history{$qualifierrest};
                   9795:                 }
1.335     albertel 9796: 	    } else {
1.359     albertel 9797: 		my %restored;
1.620     albertel 9798: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9799: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9800: 		} else {
                   9801: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9802: 		}
1.335     albertel 9803: 		return $restored{$qualifierrest};
                   9804: 	    }
1.48      www      9805: # ----------------------------------------------------------------- user.access
                   9806:         } elsif ($space eq 'access') {
1.218     albertel 9807: 	    # FIXME - not supporting calls for a specific user
1.48      www      9808:             return &allowed($qualifier,$rest);
                   9809: # ------------------------------------------ user.preferences, user.environment
                   9810:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9811: 	    if (($uname eq $env{'user.name'}) &&
                   9812: 		($udom eq $env{'user.domain'})) {
                   9813: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9814: 	    } else {
1.359     albertel 9815: 		my %returnhash;
                   9816: 		if (!$publicuser) {
                   9817: 		    %returnhash=&userenvironment($udom,$uname,
                   9818: 						 $qualifierrest);
                   9819: 		}
1.218     albertel 9820: 		return $returnhash{$qualifierrest};
                   9821: 	    }
1.48      www      9822: # ----------------------------------------------------------------- user.course
                   9823:         } elsif ($space eq 'course') {
1.218     albertel 9824: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9825:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9826: # ------------------------------------------------------------------- user.role
                   9827:         } elsif ($space eq 'role') {
1.218     albertel 9828: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9829:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9830:             if ($qualifier eq 'value') {
                   9831: 		return $role;
                   9832:             } elsif ($qualifier eq 'extent') {
                   9833:                 return $where;
                   9834:             }
                   9835: # ----------------------------------------------------------------- user.domain
                   9836:         } elsif ($space eq 'domain') {
1.218     albertel 9837:             return $udom;
1.48      www      9838: # ------------------------------------------------------------------- user.name
                   9839:         } elsif ($space eq 'name') {
1.218     albertel 9840:             return $uname;
1.48      www      9841: # ---------------------------------------------------- Any other user namespace
1.29      www      9842:         } else {
1.359     albertel 9843: 	    my %reply;
                   9844: 	    if (!$publicuser) {
                   9845: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9846: 	    }
                   9847: 	    return $reply{$qualifierrest};
1.48      www      9848:         }
1.236     www      9849:     } elsif ($realm eq 'query') {
                   9850: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9851:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9852: 						[$spacequalifierrest]);
1.620     albertel 9853: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9854:    } elsif ($realm eq 'request') {
1.48      www      9855: # ------------------------------------------------------------- request.browser
                   9856:         if ($space eq 'browser') {
1.1145    bisitz   9857:             return $env{'browser.'.$qualifier};
1.57      www      9858: # ------------------------------------------------------------ request.filename
                   9859:         } else {
1.620     albertel 9860:             return $env{'request.'.$spacequalifierrest};
1.29      www      9861:         }
1.28      www      9862:     } elsif ($realm eq 'course') {
1.48      www      9863: # ---------------------------------------------------------- course.description
1.620     albertel 9864:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9865:     } elsif ($realm eq 'resource') {
1.165     www      9866: 
1.620     albertel 9867: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9868: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9869: 	}
1.693     albertel 9870: 
1.1232    raeburn  9871:         if ($qualifier eq '') {
                   9872: 	    if ($space eq 'title') {
                   9873: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9874: 	        return &gettitle($symbparm);
                   9875: 	    }
1.693     albertel 9876: 	
1.1232    raeburn  9877: 	    if ($space eq 'map') {
                   9878: 	        my ($map) = &decode_symb($symbparm);
                   9879: 	        return &symbread($map);
                   9880: 	    }
                   9881:             if ($space eq 'maptitle') {
                   9882:                 my ($map) = &decode_symb($symbparm);
                   9883:                 return &gettitle($map);
                   9884:             }
                   9885: 	    if ($space eq 'filename') {
                   9886: 	        if ($symbparm) {
                   9887: 		    return &clutter((&decode_symb($symbparm))[2]);
                   9888: 	        }
                   9889: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 9890: 	    }
1.1232    raeburn  9891: 
1.1233    raeburn  9892:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   9893:                 if ($space eq 'visibleparts') {
                   9894:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9895:                     my $item;
                   9896:                     if (ref($navmap)) {
                   9897:                         my $res = $navmap->getBySymb($symbparm);
                   9898:                         my $parts = $res->parts();
                   9899:                         if (ref($parts) eq 'ARRAY') {
                   9900:                             $item = join(',',@{$parts});
                   9901:                         }
                   9902:                         undef($navmap);
1.1232    raeburn  9903:                     }
1.1233    raeburn  9904:                     return $item;
1.1232    raeburn  9905:                 }
                   9906:             }
                   9907:         }
1.693     albertel 9908: 
                   9909: 	my ($section, $group, @groups);
1.593     albertel 9910: 	my ($courselevelm,$courselevel);
1.1228    raeburn  9911:         if (($courseid eq '') && ($cid)) {
                   9912:             $courseid = $cid;
                   9913:         }
                   9914: 	if (($symbparm && $courseid) && 
                   9915: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      9916: 
1.218     albertel 9917: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9918: 
1.60      www      9919: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9920: 	    my $symbp=$symbparm;
1.735     albertel 9921: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9922: 
                   9923: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9924: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9925: 
1.620     albertel 9926: 	    if (($env{'user.name'} eq $uname) &&
                   9927: 		($env{'user.domain'} eq $udom)) {
                   9928: 		$section=$env{'request.course.sec'};
1.733     raeburn  9929:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9930:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9931: 	    } else {
1.539     albertel 9932: 		if (! defined($usection)) {
1.551     albertel 9933: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9934: 		} else {
                   9935: 		    $section = $usection;
                   9936: 		}
1.733     raeburn  9937:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9938: 	    }
                   9939: 
                   9940: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9941: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9942: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9943: 
1.593     albertel 9944: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9945: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9946: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9947: 
1.60      www      9948: # ----------------------------------------------------------- first, check user
1.624     albertel 9949: 
                   9950: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9951: 				       ([$courselevelr,'resource'],
                   9952: 					[$courselevelm,'map'     ],
                   9953: 					[$courselevel, 'course'  ]));
1.931     albertel 9954: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9955: 
1.594     albertel 9956: # ------------------------------------------------ second, check some of course
1.684     raeburn  9957:             my $coursereply;
1.691     raeburn  9958:             if (@groups > 0) {
                   9959:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9960:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9961:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9962:             }
1.96      www      9963: 
1.684     raeburn  9964: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9965: 				  $env{'course.'.$courseid.'.domain'},
                   9966: 				  'course',
                   9967: 				  ([$seclevelr,   'resource'],
                   9968: 				   [$seclevelm,   'map'     ],
                   9969: 				   [$seclevel,    'course'  ],
                   9970: 				   [$courselevelr,'resource']));
                   9971: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9972: 
1.60      www      9973: # ------------------------------------------------------ third, check map parms
1.218     albertel 9974: 	    my %parmhash=();
                   9975: 	    my $thisparm='';
                   9976: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9977: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9978: 		    &GDBM_READER(),0640)) {
1.218     albertel 9979: 		$thisparm=$parmhash{$symbparm};
                   9980: 		untie(%parmhash);
                   9981: 	    }
1.927     albertel 9982: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9983: 	}
1.594     albertel 9984: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9985: 
1.218     albertel 9986: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9987: 	my $filename;
                   9988: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9989: 	if ($symbparm) {
1.409     www      9990: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9991: 	} else {
1.620     albertel 9992: 	    $filename=$env{'request.filename'};
1.282     albertel 9993: 	}
                   9994: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9995: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9996: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9997: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9998: 
1.927     albertel 9999: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10000: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10001: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10002: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10003: 				     $env{'course.'.$courseid.'.domain'},
                   10004: 				     'course',
1.927     albertel 10005: 				     ([$courselevelm,'map'   ],
                   10006: 				      [$courselevel, 'course']));
                   10007: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10008: 	}
1.145     www      10009: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10010: 	unless ($space eq '0') {
1.336     albertel 10011: 	    my @parts=split(/_/,$space);
                   10012: 	    my $id=pop(@parts);
                   10013: 	    my $part=join('_',@parts);
                   10014: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10015: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10016: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10017: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10018: 	}
1.395     albertel 10019: 	if ($recurse) { return undef; }
                   10020: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10021: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10022: # ---------------------------------------------------- Any other user namespace
                   10023:     } elsif ($realm eq 'environment') {
                   10024: # ----------------------------------------------------------------- environment
1.620     albertel 10025: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10026: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10027: 	} else {
1.770     albertel 10028: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10029: 		return '';
                   10030: 	    }
1.219     albertel 10031: 	    my %returnhash=&userenvironment($udom,$uname,
                   10032: 					    $spacequalifierrest);
                   10033: 	    return $returnhash{$spacequalifierrest};
                   10034: 	}
1.28      www      10035:     } elsif ($realm eq 'system') {
1.48      www      10036: # ----------------------------------------------------------------- system.time
                   10037: 	if ($space eq 'time') {
                   10038: 	    return time;
                   10039:         }
1.696     albertel 10040:     } elsif ($realm eq 'server') {
                   10041: # ----------------------------------------------------------------- system.time
                   10042: 	if ($space eq 'name') {
                   10043: 	    return $ENV{'SERVER_NAME'};
                   10044:         }
1.28      www      10045:     }
1.48      www      10046:     return '';
1.61      www      10047: }
                   10048: 
1.927     albertel 10049: sub get_reply {
                   10050:     my ($reply_value) = @_;
1.940     raeburn  10051:     if (ref($reply_value) eq 'ARRAY') {
                   10052:         if (wantarray) {
                   10053: 	    return @$reply_value;
                   10054:         }
                   10055:         return $reply_value->[0];
                   10056:     } else {
                   10057:         return $reply_value;
1.927     albertel 10058:     }
                   10059: }
                   10060: 
1.691     raeburn  10061: sub check_group_parms {
                   10062:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10063:     my @groupitems = ();
                   10064:     my $resultitem;
1.927     albertel 10065:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10066:     foreach my $group (@{$groups}) {
                   10067:         foreach my $level (@levels) {
1.927     albertel 10068:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10069:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10070:         }
                   10071:     }
                   10072:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10073:                             $env{'course.'.$courseid.'.domain'},
                   10074:                                      'course',@groupitems);
                   10075:     return $coursereply;
                   10076: }
                   10077: 
                   10078: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10079:     my ($courseid,@groups) = @_;
                   10080:     @groups = sort(@groups);
1.691     raeburn  10081:     return @groups;
                   10082: }
                   10083: 
1.395     albertel 10084: sub packages_tab_default {
                   10085:     my ($uri,$varname)=@_;
                   10086:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10087: 
                   10088:     my (@extension,@specifics,$do_default);
                   10089:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10090: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10091: 	if ($pack_type eq 'default') {
                   10092: 	    $do_default=1;
                   10093: 	} elsif ($pack_type eq 'extension') {
                   10094: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10095: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10096: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10097: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10098: 	}
                   10099:     }
                   10100:     # first look for a package that matches the requested part id
                   10101:     foreach my $package (@specifics) {
                   10102: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10103: 	next if ($pack_part ne $part);
                   10104: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10105: 	    return $packagetab{"$pack_type&$name&default"};
                   10106: 	}
                   10107:     }
                   10108:     # look for any possible matching non extension_ package
                   10109:     foreach my $package (@specifics) {
                   10110: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10111: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10112: 	    return $packagetab{"$pack_type&$name&default"};
                   10113: 	}
1.585     albertel 10114: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10115: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10116: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10117: 	}
                   10118:     }
1.738     albertel 10119:     # look for any posible extension_ match
                   10120:     foreach my $package (@extension) {
                   10121: 	my ($package,$pack_type)=@{$package};
                   10122: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10123: 	    return $packagetab{"$pack_type&$name&default"};
                   10124: 	}
                   10125: 	if (defined($packagetab{$package."&$name&default"})) {
                   10126: 	    return $packagetab{$package."&$name&default"};
                   10127: 	}
                   10128:     }
                   10129:     # look for a global default setting
                   10130:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10131: 	return $packagetab{"default&$name&default"};
                   10132:     }
1.395     albertel 10133:     return undef;
                   10134: }
                   10135: 
1.334     albertel 10136: sub add_prefix_and_part {
                   10137:     my ($prefix,$part)=@_;
                   10138:     my $keyroot;
                   10139:     if (defined($prefix) && $prefix !~ /^__/) {
                   10140: 	# prefix that has a part already
                   10141: 	$keyroot=$prefix;
                   10142:     } elsif (defined($prefix)) {
                   10143: 	# prefix that is missing a part
                   10144: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10145:     } else {
                   10146: 	# no prefix at all
                   10147: 	if (defined($part)) { $keyroot='_'.$part; }
                   10148:     }
                   10149:     return $keyroot;
                   10150: }
                   10151: 
1.71      www      10152: # ---------------------------------------------------------------- Get metadata
                   10153: 
1.599     albertel 10154: my %metaentry;
1.1070    www      10155: my %importedpartids;
1.71      www      10156: sub metadata {
1.176     www      10157:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10158:     $uri=&declutter($uri);
1.288     albertel 10159:     # if it is a non metadata possible uri return quickly
1.529     albertel 10160:     if (($uri eq '') || 
                   10161: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10162: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10163:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10164: 	return undef;
                   10165:     }
1.1140    www      10166:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 10167: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10168: 	return undef;
1.288     albertel 10169:     }
1.73      www      10170:     my $filename=$uri;
                   10171:     $uri=~s/\.meta$//;
1.172     www      10172: #
                   10173: # Is the metadata already cached?
1.177     www      10174: # Look at timestamp of caching
1.172     www      10175: # Everything is cached by the main uri, libraries are never directly cached
                   10176: #
1.428     albertel 10177:     if (!defined($liburi)) {
1.599     albertel 10178: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10179: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10180:     }
                   10181:     {
1.1069    www      10182: # Imported parts would go here
1.1070    www      10183:         my %importedids=();
                   10184:         my @origfileimportpartids=();
1.1069    www      10185:         my $importedparts=0;
1.172     www      10186: #
                   10187: # Is this a recursive call for a library?
                   10188: #
1.599     albertel 10189: #	if (! exists($metacache{$uri})) {
                   10190: #	    $metacache{$uri}={};
                   10191: #	}
1.924     albertel 10192: 	my $cachetime = 60*60;
1.171     www      10193:         if ($liburi) {
                   10194: 	    $liburi=&declutter($liburi);
                   10195:             $filename=$liburi;
1.401     bowersj2 10196:         } else {
1.599     albertel 10197: 	    &devalidate_cache_new('meta',$uri);
                   10198: 	    undef(%metaentry);
1.401     bowersj2 10199: 	}
1.140     www      10200:         my %metathesekeys=();
1.73      www      10201:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10202: 	my $metastring;
1.1140    www      10203: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10204: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10205: 	    $metastring = 
1.929     albertel 10206: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10207: 					  ('grade_target' => 'meta'));
                   10208: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10209: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10210:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10211: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10212: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10213: 	    $metastring=&getfile($file);
1.489     albertel 10214: 	}
1.208     albertel 10215:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10216:         my $token;
1.140     www      10217:         undef %metathesekeys;
1.71      www      10218:         while ($token=$parser->get_token) {
1.339     albertel 10219: 	    if ($token->[0] eq 'S') {
                   10220: 		if (defined($token->[2]->{'package'})) {
1.172     www      10221: #
                   10222: # This is a package - get package info
                   10223: #
1.339     albertel 10224: 		    my $package=$token->[2]->{'package'};
                   10225: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10226: 		    if (defined($token->[2]->{'id'})) { 
                   10227: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10228: 		    }
1.599     albertel 10229: 		    if ($metaentry{':packages'}) {
                   10230: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10231: 		    } else {
1.599     albertel 10232: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10233: 		    }
1.736     albertel 10234: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10235: 			my $part=$keyroot;
                   10236: 			$part=~s/^\_//;
1.736     albertel 10237: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10238: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10239: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10240: 			    # ignore package.tab specified default values
                   10241:                             # here &package_tab_default() will fetch those
                   10242: 			    if ($subp eq 'default') { next; }
1.736     albertel 10243: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10244: 			    my $unikey;
                   10245: 			    if ($pack =~ /_0$/) {
                   10246: 				$unikey='parameter_0_'.$name;
                   10247: 				$part=0;
                   10248: 			    } else {
                   10249: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10250: 			    }
1.339     albertel 10251: 			    if ($subp eq 'display') {
                   10252: 				$value.=' [Part: '.$part.']';
                   10253: 			    }
1.599     albertel 10254: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10255: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10256: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10257: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10258: 			    }
1.599     albertel 10259: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10260: 				$metaentry{':'.$unikey}=
                   10261: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10262: 			    }
1.339     albertel 10263: 			}
                   10264: 		    }
                   10265: 		} else {
1.172     www      10266: #
                   10267: # This is not a package - some other kind of start tag
1.339     albertel 10268: #
                   10269: 		    my $entry=$token->[1];
1.1068    www      10270: 		    my $unikey='';
1.175     www      10271: 
1.339     albertel 10272: 		    if ($entry eq 'import') {
1.175     www      10273: #
                   10274: # Importing a library here
1.339     albertel 10275: #
1.1067    www      10276:                         my $location=$parser->get_text('/import');
                   10277:                         my $dir=$filename;
                   10278:                         $dir=~s|[^/]*$||;
                   10279:                         $location=&filelocation($dir,$location);
1.1069    www      10280:                        
1.1068    www      10281:                         my $importmode=$token->[2]->{'importmode'};
                   10282:                         if ($importmode eq 'problem') {
1.1069    www      10283: # Import as problem/response
1.1068    www      10284:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10285:                         } elsif ($importmode eq 'part') {
                   10286: # Import as part(s)
1.1069    www      10287:                            $importedparts=1;
                   10288: # We need to get the original file and the imported file to get the part order correct
                   10289: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10290: # Load and inspect original file
1.1070    www      10291:                            if ($#origfileimportpartids<0) {
                   10292:                               undef(%importedpartids);
                   10293:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10294:                               my $origfile=&getfile($origfilelocation);
                   10295:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10296:                            }
                   10297: 
1.1069    www      10298: # Load and inspect imported file
                   10299:                            my $impfile=&getfile($location);
                   10300:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10301:                            if ($#impfilepartids>=0) {
                   10302: # This problem had parts
1.1070    www      10303:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10304:                            } else {
                   10305: # Importing by turning a single problem into a problem part
                   10306: # It gets the import-tags ID as part-ID
                   10307:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10308:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10309:                            }
1.1068    www      10310:                         } else {
                   10311: # Normal import
                   10312:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10313:                            if (defined($token->[2]->{'id'})) {
                   10314:                               $unikey.='_'.$token->[2]->{'id'};
                   10315:                            }
1.1067    www      10316:                         }
                   10317: 
1.339     albertel 10318: 			if ($depthcount<20) {
1.736     albertel 10319: 			    my $metadata = 
                   10320: 				&metadata($uri,'keys', $location,$unikey,
                   10321: 					  $depthcount+1);
                   10322: 			    foreach my $meta (split(',',$metadata)) {
                   10323: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10324: 				$metathesekeys{$meta}=1;
1.339     albertel 10325: 			    }
1.1068    www      10326: 			
                   10327:                         }
1.1067    www      10328: 		    } else {
                   10329: #
                   10330: # Not importing, some other kind of non-package, non-library start tag
                   10331: # 
                   10332:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10333:                         if (defined($token->[2]->{'id'})) {
                   10334:                             $unikey.='_'.$token->[2]->{'id'};
                   10335:                         }
1.339     albertel 10336: 			if (defined($token->[2]->{'name'})) { 
                   10337: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10338: 			}
                   10339: 			$metathesekeys{$unikey}=1;
1.736     albertel 10340: 			foreach my $param (@{$token->[3]}) {
                   10341: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10342: 				$token->[2]->{$param};
1.339     albertel 10343: 			}
                   10344: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10345: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10346: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10347: 		 # only ws inside the tag, and not in default, so use default
                   10348: 		 # as value
1.599     albertel 10349: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10350: 			} elsif ( $internaltext =~ /\S/ ) {
                   10351: 		  # something interesting inside the tag
                   10352: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10353: 			} else {
1.908     albertel 10354: 		  # no interesting values, don't set a default
1.339     albertel 10355: 			}
1.172     www      10356: # end of not-a-package not-a-library import
1.339     albertel 10357: 		    }
1.172     www      10358: # end of not-a-package start tag
1.339     albertel 10359: 		}
1.172     www      10360: # the next is the end of "start tag"
1.339     albertel 10361: 	    }
                   10362: 	}
1.483     albertel 10363: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10364: 	$extension = lc($extension);
                   10365: 	if ($extension eq 'htm') { $extension='html'; }
                   10366: 
1.737     albertel 10367: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10368: 	    #no specific packages #how's our extension
                   10369: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10370: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10371: 					 \%metathesekeys);
                   10372: 	}
1.883     albertel 10373: 
                   10374: 	if (!exists($metaentry{':packages'})
                   10375: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10376: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10377: 		#no specific packages well let's get default then
                   10378: 		if ($key!~/^default&/) { next; }
1.488     albertel 10379: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10380: 					     \%metathesekeys);
                   10381: 	    }
                   10382: 	}
1.338     www      10383: # are there custom rights to evaluate
1.599     albertel 10384: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10385: 
1.338     www      10386:     #
                   10387:     # Importing a rights file here
1.339     albertel 10388:     #
                   10389: 	    unless ($depthcount) {
1.599     albertel 10390: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10391: 		my $dir=$filename;
                   10392: 		$dir=~s|[^/]*$||;
                   10393: 		$location=&filelocation($dir,$location);
1.736     albertel 10394: 		my $rights_metadata =
                   10395: 		    &metadata($uri,'keys',$location,'_rights',
                   10396: 			      $depthcount+1);
                   10397: 		foreach my $rights (split(',',$rights_metadata)) {
                   10398: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10399: 		    $metathesekeys{$rights}=1;
1.339     albertel 10400: 		}
                   10401: 	    }
                   10402: 	}
1.737     albertel 10403: 	# uniqifiy package listing
                   10404: 	my %seen;
                   10405: 	my @uniq_packages =
                   10406: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10407: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10408: 
1.1070    www      10409:         if ($importedparts) {
                   10410: # We had imported parts and need to rebuild partorder
                   10411:            $metaentry{':partorder'}='';
                   10412:            $metathesekeys{'partorder'}=1;
                   10413:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10414:                if ($origfileimportpartids[$index] eq 'part') {
                   10415: # original part, part of the problem
                   10416:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10417:                } else {
                   10418: # we have imported parts at this position
                   10419:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10420:                }
                   10421:            }
                   10422:            $metaentry{':partorder'}=~s/^\,//;
                   10423:         }
                   10424: 
1.737     albertel 10425: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10426: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10427: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10428: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10429: # this is the end of "was not already recently cached
1.71      www      10430:     }
1.599     albertel 10431:     return $metaentry{':'.$what};
1.261     albertel 10432: }
                   10433: 
1.488     albertel 10434: sub metadata_create_package_def {
1.483     albertel 10435:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10436:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10437:     if ($subp eq 'default') { next; }
                   10438:     
1.599     albertel 10439:     if (defined($metaentry{':packages'})) {
                   10440: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10441:     } else {
1.599     albertel 10442: 	$metaentry{':packages'}=$package;
1.483     albertel 10443:     }
                   10444:     my $value=$packagetab{$key};
                   10445:     my $unikey;
                   10446:     $unikey='parameter_0_'.$name;
1.599     albertel 10447:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10448:     $$metathesekeys{$unikey}=1;
1.599     albertel 10449:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10450: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10451:     }
1.599     albertel 10452:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10453: 	$metaentry{':'.$unikey}=
                   10454: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10455:     }
                   10456: }
                   10457: 
1.261     albertel 10458: sub metadata_generate_part0 {
                   10459:     my ($metadata,$metacache,$uri) = @_;
                   10460:     my %allnames;
1.737     albertel 10461:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10462: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10463: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10464: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10465: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10466: 	    $allnames{$name}=$part;
                   10467: 	  }
                   10468: 	}
                   10469:     }
                   10470:     foreach my $name (keys(%allnames)) {
                   10471:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10472:       my $key=":parameter_0_$name";
1.261     albertel 10473:       $$metacache{"$key.part"}='0';
                   10474:       $$metacache{"$key.name"}=$name;
1.428     albertel 10475:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10476: 					   $allnames{$name}.'_'.$name.
                   10477: 					   '.type'};
1.428     albertel 10478:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10479: 			     '.display'};
1.644     www      10480:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10481:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10482:       $$metacache{"$key.display"}=$olddis;
                   10483:     }
1.71      www      10484: }
                   10485: 
1.764     albertel 10486: # ------------------------------------------------------ Devalidate title cache
                   10487: 
                   10488: sub devalidate_title_cache {
                   10489:     my ($url)=@_;
                   10490:     if (!$env{'request.course.id'}) { return; }
                   10491:     my $symb=&symbread($url);
                   10492:     if (!$symb) { return; }
                   10493:     my $key=$env{'request.course.id'}."\0".$symb;
                   10494:     &devalidate_cache_new('title',$key);
                   10495: }
                   10496: 
1.1014    droeschl 10497: # ------------------------------------------------- Get the title of a course
                   10498: 
                   10499: sub current_course_title {
                   10500:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10501: }
1.301     www      10502: # ------------------------------------------------- Get the title of a resource
                   10503: 
                   10504: sub gettitle {
                   10505:     my $urlsymb=shift;
                   10506:     my $symb=&symbread($urlsymb);
1.534     albertel 10507:     if ($symb) {
1.620     albertel 10508: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10509: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10510: 	if (defined($cached)) { 
                   10511: 	    return $result;
                   10512: 	}
1.534     albertel 10513: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10514: 	my $title='';
1.907     albertel 10515: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10516: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10517: 	} else {
                   10518: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10519: 		    &GDBM_READER(),0640)) {
                   10520: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10521: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10522: 		untie(%bighash);
                   10523: 	    }
1.534     albertel 10524: 	}
                   10525: 	$title=~s/\&colon\;/\:/gs;
                   10526: 	if ($title) {
1.1159    www      10527: # Remember both $symb and $title for dynamic metadata
                   10528:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10529:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10530: # Cache this title and then return it
1.599     albertel 10531: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10532: 	}
                   10533: 	$urlsymb=$url;
                   10534:     }
                   10535:     my $title=&metadata($urlsymb,'title');
                   10536:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10537:     return $title;
1.301     www      10538: }
1.613     albertel 10539: 
1.614     albertel 10540: sub get_slot {
                   10541:     my ($which,$cnum,$cdom)=@_;
                   10542:     if (!$cnum || !$cdom) {
1.790     albertel 10543: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10544: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10545: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10546:     }
1.703     albertel 10547:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10548:     my %slotinfo;
                   10549:     if (exists($remembered{$key})) {
                   10550: 	$slotinfo{$which} = $remembered{$key};
                   10551:     } else {
                   10552: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10553: 	&Apache::lonhomework::showhash(%slotinfo);
                   10554: 	my ($tmp)=keys(%slotinfo);
                   10555: 	if ($tmp=~/^error:/) { return (); }
                   10556: 	$remembered{$key} = $slotinfo{$which};
                   10557:     }
1.616     albertel 10558:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10559: 	return %{$slotinfo{$which}};
                   10560:     }
                   10561:     return $slotinfo{$which};
1.614     albertel 10562: }
1.1150    raeburn  10563: 
                   10564: sub get_reservable_slots {
                   10565:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10566:     my $now = time;
                   10567:     my $reservable_info;
                   10568:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10569:     if (exists($remembered{$key})) {
                   10570:         $reservable_info = $remembered{$key};
                   10571:     } else {
                   10572:         my %resv;
                   10573:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10574:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10575:         $reservable_info = \%resv;
                   10576:         $remembered{$key} = $reservable_info;
                   10577:     }
                   10578:     return $reservable_info;
                   10579: }
                   10580: 
                   10581: sub get_course_slots {
                   10582:     my ($cnum,$cdom) = @_;
                   10583:     my $hashid=$cnum.':'.$cdom;
                   10584:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10585:     if (defined($cached)) {
                   10586:         if (ref($result) eq 'HASH') {
                   10587:             return %{$result};
                   10588:         }
                   10589:     } else {
                   10590:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10591:         my ($tmp) = keys(%slots);
                   10592:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  10593:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10594:             return %slots;
                   10595:         }
                   10596:     }
                   10597:     return;
                   10598: }
                   10599: 
                   10600: sub devalidate_slots_cache {
                   10601:     my ($cnum,$cdom)=@_;
                   10602:     my $hashid=$cnum.':'.$cdom;
                   10603:     &devalidate_cache_new('allslots',$hashid);
                   10604: }
                   10605: 
1.1181    raeburn  10606: sub get_coursechange {
                   10607:     my ($cdom,$cnum) = @_;
                   10608:     if ($cdom eq '' || $cnum eq '') {
                   10609:         return unless ($env{'request.course.id'});
                   10610:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10611:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10612:     }
                   10613:     my $hashid=$cdom.'_'.$cnum;
                   10614:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10615:     if ((defined($cached)) && ($change ne '')) {
                   10616:         return $change;
                   10617:     } else {
                   10618:         my %crshash;
                   10619:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10620:         if ($crshash{'internal.contentchange'} eq '') {
                   10621:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10622:             if ($change eq '') {
                   10623:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10624:                 $change = $crshash{'internal.created'};
                   10625:             }
                   10626:         } else {
                   10627:             $change = $crshash{'internal.contentchange'};
                   10628:         }
                   10629:         my $cachetime = 600;
                   10630:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10631:     }
                   10632:     return $change;
                   10633: }
                   10634: 
                   10635: sub devalidate_coursechange_cache {
                   10636:     my ($cnum,$cdom)=@_;
                   10637:     my $hashid=$cnum.':'.$cdom;
                   10638:     &devalidate_cache_new('crschange',$hashid);
                   10639: }
                   10640: 
1.31      www      10641: # ------------------------------------------------- Update symbolic store links
                   10642: 
                   10643: sub symblist {
                   10644:     my ($mapname,%newhash)=@_;
1.438     www      10645:     $mapname=&deversion(&declutter($mapname));
1.31      www      10646:     my %hash;
1.620     albertel 10647:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10648:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10649:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10650: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10651: 		next if ($url eq 'last_known'
                   10652: 			 && $env{'form.no_update_last_known'});
                   10653: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10654: 						    $newhash{$url}->[1],
                   10655: 						    $newhash{$url}->[0]);
1.191     harris41 10656:             }
1.31      www      10657:             if (untie(%hash)) {
                   10658: 		return 'ok';
                   10659:             }
                   10660:         }
                   10661:     }
                   10662:     return 'error';
1.212     www      10663: }
                   10664: 
                   10665: # --------------------------------------------------------------- Verify a symb
                   10666: 
                   10667: sub symbverify {
1.1190    raeburn  10668:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10669:     my $thisfn=$thisurl;
1.439     www      10670:     $thisfn=&declutter($thisfn);
1.215     www      10671: # direct jump to resource in page or to a sequence - will construct own symbs
                   10672:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10673: # check URL part
1.409     www      10674:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10675: 
1.431     www      10676:     unless ($url eq $thisfn) { return 0; }
1.213     www      10677: 
1.216     www      10678:     $symb=&symbclean($symb);
1.510     www      10679:     $thisurl=&deversion($thisurl);
1.439     www      10680:     $thisfn=&deversion($thisfn);
1.213     www      10681: 
                   10682:     my %bighash;
                   10683:     my $okay=0;
1.431     www      10684: 
1.620     albertel 10685:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10686:                             &GDBM_READER(),0640)) {
1.1204    raeburn  10687:         my $noclutter;
1.1032    raeburn  10688:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10689:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  10690:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10691:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10692:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10693:                 $noclutter = 1;
                   10694:             }
                   10695:         }
                   10696:         my $ids;
                   10697:         if ($noclutter) {
                   10698:             $ids=$bighash{'ids_'.$thisurl};
                   10699:         } else {
                   10700:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10701:         }
1.1102    raeburn  10702:         unless ($ids) {
                   10703:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10704:             $ids=$bighash{$idkey};
1.216     www      10705:         }
                   10706:         if ($ids) {
                   10707: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  10708:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  10709:                 $symb =~ s/\?.+$//;
1.1202    raeburn  10710:             }
1.800     albertel 10711: 	    foreach my $id (split(/\,/,$ids)) {
                   10712: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10713:                if (
                   10714:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  10715:    eq $symb) {
                   10716:                    if (ref($encstate)) {
                   10717:                        $$encstate = $bighash{'encrypted_'.$id};
                   10718:                    }
1.620     albertel 10719: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10720: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10721:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  10722: 		       $okay=1;
1.1202    raeburn  10723:                        last;
1.582     albertel 10724: 		   }
                   10725: 	       }
1.216     www      10726: 	   }
                   10727:         }
1.213     www      10728: 	untie(%bighash);
                   10729:     }
                   10730:     return $okay;
1.31      www      10731: }
                   10732: 
1.210     www      10733: # --------------------------------------------------------------- Clean-up symb
                   10734: 
                   10735: sub symbclean {
                   10736:     my $symb=shift;
1.568     albertel 10737:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10738: # remove version from map
                   10739:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10740: 
1.210     www      10741: # remove version from URL
                   10742:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10743: 
1.507     www      10744: # remove wrapper
                   10745: 
1.510     www      10746:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10747:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10748:     return $symb;
1.409     www      10749: }
                   10750: 
                   10751: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10752: 
                   10753: sub encode_symb {
                   10754:     my ($map,$resid,$url)=@_;
                   10755:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10756: }
1.409     www      10757: 
                   10758: sub decode_symb {
1.568     albertel 10759:     my $symb=shift;
                   10760:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10761:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10762:     return (&fixversion($map),$resid,&fixversion($url));
                   10763: }
                   10764: 
                   10765: sub fixversion {
                   10766:     my $fn=shift;
1.609     banghart 10767:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10768:     my %bighash;
                   10769:     my $uri=&clutter($fn);
1.620     albertel 10770:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10771: # is this cached?
1.599     albertel 10772:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10773:     if (defined($cached)) { return $result; }
                   10774: # unfortunately not cached, or expired
1.620     albertel 10775:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10776: 	    &GDBM_READER(),0640)) {
                   10777:  	if ($bighash{'version_'.$uri}) {
                   10778:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10779:  	    unless (($version eq 'mostrecent') || 
                   10780: 		    ($version==&getversion($uri))) {
1.440     www      10781:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10782:  	    }
                   10783:  	}
                   10784:  	untie %bighash;
1.413     www      10785:     }
1.599     albertel 10786:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10787: }
                   10788: 
                   10789: sub deversion {
                   10790:     my $url=shift;
                   10791:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10792:     return $url;
1.210     www      10793: }
                   10794: 
1.31      www      10795: # ------------------------------------------------------ Return symb list entry
                   10796: 
                   10797: sub symbread {
1.249     www      10798:     my ($thisfn,$donotrecurse)=@_;
1.1206    raeburn  10799:     my $cache_str;
                   10800:     if ($thisfn ne '') {
                   10801:         $cache_str='request.symbread.cached.'.$thisfn;
                   10802:         if ($env{$cache_str} ne '') {
1.1179    raeburn  10803:             return $env{$cache_str};
                   10804:         }
1.1206    raeburn  10805:     } else {
1.242     www      10806: # no filename provided? try from environment
1.620     albertel 10807:         if ($env{'request.symb'}) {
                   10808: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10809: 	}
1.620     albertel 10810: 	$thisfn=$env{'request.filename'};
1.44      www      10811:     }
1.569     albertel 10812:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10813: # is that filename actually a symb? Verify, clean, and return
                   10814:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10815: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10816: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10817: 	}
1.242     www      10818:     }
1.44      www      10819:     $thisfn=declutter($thisfn);
1.31      www      10820:     my %hash;
1.37      www      10821:     my %bighash;
                   10822:     my $syval='';
1.620     albertel 10823:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10824:         my $targetfn = $thisfn;
1.609     banghart 10825:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10826:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10827:         }
1.687     albertel 10828: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10829: 	    $targetfn=$1;
                   10830: 	}
1.620     albertel 10831:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10832:                       &GDBM_READER(),0640)) {
1.481     raeburn  10833: 	    $syval=$hash{$targetfn};
1.37      www      10834:             untie(%hash);
                   10835:         }
                   10836: # ---------------------------------------------------------- There was an entry
                   10837:         if ($syval) {
1.601     albertel 10838: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10839: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10840: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10841: 		    #return $env{$cache_str}='';
1.601     albertel 10842: 		#}    
                   10843: 		#$syval.=$1;
                   10844: 	    #}
1.37      www      10845:         } else {
                   10846: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10847:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10848:                             &GDBM_READER(),0640)) {
1.37      www      10849: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10850:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10851:               unless ($ids) { 
                   10852:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10853:               }
                   10854:               unless ($ids) {
                   10855: # alias?
                   10856: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10857:               }
1.37      www      10858:               if ($ids) {
                   10859: # ------------------------------------------------------------------- Has ID(s)
                   10860:                  my @possibilities=split(/\,/,$ids);
1.39      www      10861:                  if ($#possibilities==0) {
                   10862: # ----------------------------------------------- There is only one possibility
1.37      www      10863: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10864: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10865: 						    $resid,$thisfn);
1.249     www      10866:                  } elsif (!$donotrecurse) {
1.39      www      10867: # ------------------------------------------ There is more than one possibility
                   10868:                      my $realpossible=0;
1.800     albertel 10869:                      foreach my $id (@possibilities) {
                   10870: 			 my $file=$bighash{'src_'.$id};
1.39      www      10871:                          if (&allowed('bre',$file)) {
1.800     albertel 10872:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10873:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10874: 				$realpossible++;
1.626     albertel 10875:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10876: 						    $resid,$thisfn);
1.39      www      10877:                             }
                   10878: 			 }
1.191     harris41 10879:                      }
1.39      www      10880: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10881:                  } else {
                   10882:                      $syval='';
1.37      www      10883:                  }
                   10884: 	      }
                   10885:               untie(%bighash)
1.481     raeburn  10886:            }
1.31      www      10887:         }
1.62      www      10888:         if ($syval) {
1.620     albertel 10889: 	    return $env{$cache_str}=$syval;
1.62      www      10890:         }
1.31      www      10891:     }
1.949     raeburn  10892:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10893:     return $env{$cache_str}='';
1.31      www      10894: }
                   10895: 
                   10896: # ---------------------------------------------------------- Return random seed
                   10897: 
1.32      www      10898: sub numval {
                   10899:     my $txt=shift;
                   10900:     $txt=~tr/A-J/0-9/;
                   10901:     $txt=~tr/a-j/0-9/;
                   10902:     $txt=~tr/K-T/0-9/;
                   10903:     $txt=~tr/k-t/0-9/;
                   10904:     $txt=~tr/U-Z/0-5/;
                   10905:     $txt=~tr/u-z/0-5/;
                   10906:     $txt=~s/\D//g;
1.564     albertel 10907:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10908:     return int($txt);
1.368     albertel 10909: }
                   10910: 
1.484     albertel 10911: sub numval2 {
                   10912:     my $txt=shift;
                   10913:     $txt=~tr/A-J/0-9/;
                   10914:     $txt=~tr/a-j/0-9/;
                   10915:     $txt=~tr/K-T/0-9/;
                   10916:     $txt=~tr/k-t/0-9/;
                   10917:     $txt=~tr/U-Z/0-5/;
                   10918:     $txt=~tr/u-z/0-5/;
                   10919:     $txt=~s/\D//g;
                   10920:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10921:     my $total;
                   10922:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10923:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10924:     return int($total);
                   10925: }
                   10926: 
1.575     albertel 10927: sub numval3 {
                   10928:     use integer;
                   10929:     my $txt=shift;
                   10930:     $txt=~tr/A-J/0-9/;
                   10931:     $txt=~tr/a-j/0-9/;
                   10932:     $txt=~tr/K-T/0-9/;
                   10933:     $txt=~tr/k-t/0-9/;
                   10934:     $txt=~tr/U-Z/0-5/;
                   10935:     $txt=~tr/u-z/0-5/;
                   10936:     $txt=~s/\D//g;
                   10937:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10938:     my $total;
                   10939:     foreach my $val (@txts) { $total+=$val; }
                   10940:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10941:     return $total;
                   10942: }
                   10943: 
1.675     albertel 10944: sub digest {
                   10945:     my ($data)=@_;
                   10946:     my $digest=&Digest::MD5::md5($data);
                   10947:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10948:     my ($e,$f);
                   10949:     {
                   10950:         use integer;
                   10951:         $e=($a+$b);
                   10952:         $f=($c+$d);
                   10953:         if ($_64bit) {
                   10954:             $e=(($e<<32)>>32);
                   10955:             $f=(($f<<32)>>32);
                   10956:         }
                   10957:     }
                   10958:     if (wantarray) {
                   10959: 	return ($e,$f);
                   10960:     } else {
                   10961: 	my $g;
                   10962: 	{
                   10963: 	    use integer;
                   10964: 	    $g=($e+$f);
                   10965: 	    if ($_64bit) {
                   10966: 		$g=(($g<<32)>>32);
                   10967: 	    }
                   10968: 	}
                   10969: 	return $g;
                   10970:     }
                   10971: }
                   10972: 
1.368     albertel 10973: sub latest_rnd_algorithm_id {
1.675     albertel 10974:     return '64bit5';
1.366     albertel 10975: }
1.32      www      10976: 
1.503     albertel 10977: sub get_rand_alg {
                   10978:     my ($courseid)=@_;
1.790     albertel 10979:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10980:     if ($courseid) {
1.620     albertel 10981: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10982:     }
                   10983:     return &latest_rnd_algorithm_id();
                   10984: }
                   10985: 
1.562     albertel 10986: sub validCODE {
                   10987:     my ($CODE)=@_;
                   10988:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10989:     return 0;
                   10990: }
                   10991: 
1.491     albertel 10992: sub getCODE {
1.620     albertel 10993:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10994:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10995: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10996: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10997: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10998:     }
                   10999:     return undef;
                   11000: }
1.1133    foxr     11001: #
                   11002: #  Determines the random seed for a specific context:
                   11003: #
                   11004: # parameters:
                   11005: #   symb      - in course context the symb for the seed.
                   11006: #   course_id - The course id of the form domain_coursenum.
                   11007: #   domain    - Domain for the user.
                   11008: #   course    - Course for the user.
                   11009: #   cenv      - environment of the course.
                   11010: #
                   11011: # NOTE:
                   11012: #   All parameters are picked out of the environment if missing
                   11013: #   or not defined.
                   11014: #   If a symb cannot be determined the current time is used instead.
                   11015: #
                   11016: #  For a given well defined symb, courside, domain, username,
                   11017: #  and course environment, the seed is reproducible.
                   11018: #
1.31      www      11019: sub rndseed {
1.1133    foxr     11020:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11021:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11022:     if (!defined($symb)) {
1.366     albertel 11023: 	unless ($symb=$wsymb) { return time; }
                   11024:     }
1.1146    foxr     11025:     if (!defined $courseid) { 
                   11026: 	$courseid=$wcourseid; 
                   11027:     }
                   11028:     if (!defined $domain) { $domain=$wdomain; }
                   11029:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11030: 
                   11031:     my $which;
                   11032:     if (defined($cenv->{'rndseed'})) {
                   11033: 	$which = $cenv->{'rndseed'};
                   11034:     } else {
                   11035: 	$which =&get_rand_alg($courseid);
                   11036:     }
1.491     albertel 11037:     if (defined(&getCODE())) {
1.1133    foxr     11038: 
1.675     albertel 11039: 	if ($which eq '64bit5') {
                   11040: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11041: 	} elsif ($which eq '64bit4') {
1.575     albertel 11042: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11043: 	} else {
                   11044: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11045: 	}
1.675     albertel 11046:     } elsif ($which eq '64bit5') {
                   11047: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11048:     } elsif ($which eq '64bit4') {
                   11049: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11050:     } elsif ($which eq '64bit3') {
                   11051: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11052:     } elsif ($which eq '64bit2') {
                   11053: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11054:     } elsif ($which eq '64bit') {
                   11055: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11056:     }
                   11057:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11058: }
                   11059: 
                   11060: sub rndseed_32bit {
                   11061:     my ($symb,$courseid,$domain,$username)=@_;
                   11062:     {
                   11063: 	use integer;
                   11064: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11065: 	my $symbseed=numval($symb) << 22;
                   11066: 	my $namechck=unpack("%32C*",$username) << 17;
                   11067: 	my $nameseed=numval($username) << 12;
                   11068: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11069: 	my $courseseed=unpack("%32C*",$courseid);
                   11070: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11071: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11072: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11073: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11074: 	return $num;
                   11075:     }
                   11076: }
                   11077: 
                   11078: sub rndseed_64bit {
                   11079:     my ($symb,$courseid,$domain,$username)=@_;
                   11080:     {
                   11081: 	use integer;
                   11082: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11083: 	my $symbseed=numval($symb) << 10;
                   11084: 	my $namechck=unpack("%32S*",$username);
                   11085: 	
                   11086: 	my $nameseed=numval($username) << 21;
                   11087: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11088: 	my $courseseed=unpack("%32S*",$courseid);
                   11089: 	
                   11090: 	my $num1=$symbchck+$symbseed+$namechck;
                   11091: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11092: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11093: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11094: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11095: 	return "$num1,$num2";
1.155     albertel 11096:     }
1.366     albertel 11097: }
                   11098: 
1.443     albertel 11099: sub rndseed_64bit2 {
                   11100:     my ($symb,$courseid,$domain,$username)=@_;
                   11101:     {
                   11102: 	use integer;
                   11103: 	# strings need to be an even # of cahracters long, it it is odd the
                   11104:         # last characters gets thrown away
                   11105: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11106: 	my $symbseed=numval($symb) << 10;
                   11107: 	my $namechck=unpack("%32S*",$username.' ');
                   11108: 	
                   11109: 	my $nameseed=numval($username) << 21;
1.501     albertel 11110: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11111: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11112: 	
                   11113: 	my $num1=$symbchck+$symbseed+$namechck;
                   11114: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11115: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11116: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11117: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11118: 	return "$num1,$num2";
                   11119:     }
                   11120: }
                   11121: 
                   11122: sub rndseed_64bit3 {
                   11123:     my ($symb,$courseid,$domain,$username)=@_;
                   11124:     {
                   11125: 	use integer;
                   11126: 	# strings need to be an even # of cahracters long, it it is odd the
                   11127:         # last characters gets thrown away
                   11128: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11129: 	my $symbseed=numval2($symb) << 10;
                   11130: 	my $namechck=unpack("%32S*",$username.' ');
                   11131: 	
                   11132: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11133: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11134: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11135: 	
                   11136: 	my $num1=$symbchck+$symbseed+$namechck;
                   11137: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11138: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11139: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11140: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11141: 	
1.503     albertel 11142: 	return "$num1:$num2";
1.443     albertel 11143:     }
                   11144: }
                   11145: 
1.575     albertel 11146: sub rndseed_64bit4 {
                   11147:     my ($symb,$courseid,$domain,$username)=@_;
                   11148:     {
                   11149: 	use integer;
                   11150: 	# strings need to be an even # of cahracters long, it it is odd the
                   11151:         # last characters gets thrown away
                   11152: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11153: 	my $symbseed=numval3($symb) << 10;
                   11154: 	my $namechck=unpack("%32S*",$username.' ');
                   11155: 	
                   11156: 	my $nameseed=numval3($username) << 21;
                   11157: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11158: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11159: 	
                   11160: 	my $num1=$symbchck+$symbseed+$namechck;
                   11161: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11162: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11163: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11164: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11165: 	
1.575     albertel 11166: 	return "$num1:$num2";
                   11167:     }
                   11168: }
                   11169: 
1.675     albertel 11170: sub rndseed_64bit5 {
                   11171:     my ($symb,$courseid,$domain,$username)=@_;
                   11172:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11173:     return "$num1:$num2";
                   11174: }
                   11175: 
1.366     albertel 11176: sub rndseed_CODE_64bit {
                   11177:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11178:     {
1.366     albertel 11179: 	use integer;
1.443     albertel 11180: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11181: 	my $symbseed=numval2($symb);
1.491     albertel 11182: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11183: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11184: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11185: 	my $num1=$symbseed+$CODEchck;
                   11186: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11187: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11188: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11189: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11190: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11191: 	return "$num1:$num2";
1.366     albertel 11192:     }
                   11193: }
                   11194: 
1.575     albertel 11195: sub rndseed_CODE_64bit4 {
                   11196:     my ($symb,$courseid,$domain,$username)=@_;
                   11197:     {
                   11198: 	use integer;
                   11199: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11200: 	my $symbseed=numval3($symb);
                   11201: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11202: 	my $CODEseed=numval3(&getCODE());
                   11203: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11204: 	my $num1=$symbseed+$CODEchck;
                   11205: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11206: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11207: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11208: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11209: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11210: 	return "$num1:$num2";
                   11211:     }
                   11212: }
                   11213: 
1.675     albertel 11214: sub rndseed_CODE_64bit5 {
                   11215:     my ($symb,$courseid,$domain,$username)=@_;
                   11216:     my $code = &getCODE();
                   11217:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11218:     return "$num1:$num2";
                   11219: }
                   11220: 
1.366     albertel 11221: sub setup_random_from_rndseed {
                   11222:     my ($rndseed)=@_;
1.503     albertel 11223:     if ($rndseed =~/([,:])/) {
                   11224: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11225: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11226:     } else {
                   11227: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11228:     }
1.36      albertel 11229: }
                   11230: 
1.474     albertel 11231: sub latest_receipt_algorithm_id {
1.835     albertel 11232:     return 'receipt3';
1.474     albertel 11233: }
                   11234: 
1.480     www      11235: sub recunique {
                   11236:     my $fucourseid=shift;
                   11237:     my $unique;
1.835     albertel 11238:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11239: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11240: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11241:     } else {
                   11242: 	$unique=$perlvar{'lonReceipt'};
                   11243:     }
                   11244:     return unpack("%32C*",$unique);
                   11245: }
                   11246: 
                   11247: sub recprefix {
                   11248:     my $fucourseid=shift;
                   11249:     my $prefix;
1.835     albertel 11250:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11251: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11252: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11253:     } else {
                   11254: 	$prefix=$perlvar{'lonHostID'};
                   11255:     }
                   11256:     return unpack("%32C*",$prefix);
                   11257: }
                   11258: 
1.76      www      11259: sub ireceipt {
1.474     albertel 11260:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11261: 
                   11262:     my $return =&recprefix($fucourseid).'-';
                   11263: 
                   11264:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11265: 	$env{'request.state'} eq 'construct') {
                   11266: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11267: 	return $return;
                   11268:     }
                   11269: 
1.76      www      11270:     my $cuname=unpack("%32C*",$funame);
                   11271:     my $cudom=unpack("%32C*",$fudom);
                   11272:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11273:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11274:     my $cunique=&recunique($fucourseid);
1.474     albertel 11275:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11276:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11277: 
1.790     albertel 11278: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11279: 			       
                   11280: 	$return.= ($cunique%$cuname+
                   11281: 		   $cunique%$cudom+
                   11282: 		   $cusymb%$cuname+
                   11283: 		   $cusymb%$cudom+
                   11284: 		   $cucourseid%$cuname+
                   11285: 		   $cucourseid%$cudom+
                   11286: 		   $cpart%$cuname+
                   11287: 		   $cpart%$cudom);
                   11288:     } else {
                   11289: 	$return.= ($cunique%$cuname+
                   11290: 		   $cunique%$cudom+
                   11291: 		   $cusymb%$cuname+
                   11292: 		   $cusymb%$cudom+
                   11293: 		   $cucourseid%$cuname+
                   11294: 		   $cucourseid%$cudom);
                   11295:     }
                   11296:     return $return;
1.76      www      11297: }
                   11298: 
                   11299: sub receipt {
1.474     albertel 11300:     my ($part)=@_;
1.790     albertel 11301:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11302:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11303: }
1.260     ng       11304: 
1.790     albertel 11305: sub whichuser {
                   11306:     my ($passedsymb)=@_;
                   11307:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11308:     if (defined($env{'form.grade_symb'})) {
                   11309: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11310: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11311: 	if (!$allowed &&
                   11312: 	    exists($env{'request.course.sec'}) &&
                   11313: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11314: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11315: 			      '/'.$env{'request.course.sec'});
                   11316: 	}
                   11317: 	if ($allowed) {
                   11318: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11319: 	    $courseid=$tmp_courseid;
                   11320: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11321: 	    ($name)=&get_env_multiple('form.grade_username');
                   11322: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11323: 	}
                   11324:     }
                   11325:     if (!$passedsymb) {
                   11326: 	$symb=&symbread();
                   11327:     } else {
                   11328: 	$symb=$passedsymb;
                   11329:     }
                   11330:     $courseid=$env{'request.course.id'};
                   11331:     $domain=$env{'user.domain'};
                   11332:     $name=$env{'user.name'};
                   11333:     if ($name eq 'public' && $domain eq 'public') {
                   11334: 	if (!defined($env{'form.username'})) {
                   11335: 	    $env{'form.username'}.=time.rand(10000000);
                   11336: 	}
                   11337: 	$name.=$env{'form.username'};
                   11338:     }
                   11339:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11340: 
                   11341: }
                   11342: 
1.36      albertel 11343: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11344: # returns either the contents of the file or 
                   11345: # -1 if the file doesn't exist
1.481     raeburn  11346: #
                   11347: # if the target is a file that was uploaded via DOCS, 
                   11348: # a check will be made to see if a current copy exists on the local server,
                   11349: # if it does this will be served, otherwise a copy will be retrieved from
                   11350: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11351: # the local server.   
1.472     albertel 11352: 
1.36      albertel 11353: sub getfile {
1.538     albertel 11354:     my ($file) = @_;
1.609     banghart 11355:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11356:     &repcopy($file);
                   11357:     return &readfile($file);
                   11358: }
                   11359: 
                   11360: sub repcopy_userfile {
                   11361:     my ($file)=@_;
1.1142    raeburn  11362:     my $londocroot = $perlvar{'lonDocRoot'};
                   11363:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11364:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11365:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11366: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11367:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11368:     if (-e "$file") {
1.828     www      11369: # we already have a local copy, check it out
1.538     albertel 11370: 	my @fileinfo = stat($file);
1.828     www      11371: 	my $rtncode;
                   11372: 	my $info;
1.538     albertel 11373: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11374: 	if ($lwpresp ne 'ok') {
1.828     www      11375: # there is no such file anymore, even though we had a local copy
1.482     albertel 11376: 	    if ($rtncode eq '404') {
1.538     albertel 11377: 		unlink($file);
1.482     albertel 11378: 	    }
                   11379: 	    return -1;
                   11380: 	}
                   11381: 	if ($info < $fileinfo[9]) {
1.828     www      11382: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11383: 	    return 'ok';
1.828     www      11384: 	} else {
                   11385: # the file is outdated, get rid of it
                   11386: 	    unlink($file);
1.482     albertel 11387: 	}
1.828     www      11388:     }
                   11389: # one way or the other, at this point, we don't have the file
                   11390: # construct the correct path for the file
                   11391:     my @parts = ($cdom,$cnum); 
                   11392:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11393: 	push @parts, split(/\//,$1);
                   11394:     }
                   11395:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11396:     foreach my $part (@parts) {
                   11397: 	$path .= '/'.$part;
                   11398: 	if (!-e $path) {
                   11399: 	    mkdir($path,0770);
1.482     albertel 11400: 	}
                   11401:     }
1.828     www      11402: # now the path exists for sure
                   11403: # get a user agent
                   11404:     my $ua=new LWP::UserAgent;
                   11405:     my $transferfile=$file.'.in.transfer';
                   11406: # FIXME: this should flock
                   11407:     if (-e $transferfile) { return 'ok'; }
                   11408:     my $request;
                   11409:     $uri=~s/^\///;
1.980     raeburn  11410:     my $homeserver = &homeserver($cnum,$cdom);
                   11411:     my $protocol = $protocol{$homeserver};
                   11412:     $protocol = 'http' if ($protocol ne 'https');
                   11413:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11414:     my $response=$ua->request($request,$transferfile);
                   11415: # did it work?
                   11416:     if ($response->is_error()) {
                   11417: 	unlink($transferfile);
                   11418: 	&logthis("Userfile repcopy failed for $uri");
                   11419: 	return -1;
                   11420:     }
                   11421: # worked, rename the transfer file
                   11422:     rename($transferfile,$file);
1.607     raeburn  11423:     return 'ok';
1.481     raeburn  11424: }
                   11425: 
1.517     albertel 11426: sub tokenwrapper {
                   11427:     my $uri=shift;
1.980     raeburn  11428:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11429:     $uri=~s|^/||;
1.620     albertel 11430:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11431:     my $token=$1;
1.552     albertel 11432:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11433:     if ($udom && $uname && $file) {
                   11434: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11435:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11436:         my $homeserver = &homeserver($uname,$udom);
                   11437:         my $protocol = $protocol{$homeserver};
                   11438:         $protocol = 'http' if ($protocol ne 'https');
                   11439:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11440:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11441:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11442:     } else {
                   11443:         return '/adm/notfound.html';
                   11444:     }
                   11445: }
                   11446: 
1.828     www      11447: # call with reqtype HEAD: get last modification time
                   11448: # call with reqtype GET: get the file contents
                   11449: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11450: #
1.481     raeburn  11451: sub getuploaded {
                   11452:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11453:     $uri=~s/^\///;
1.980     raeburn  11454:     my $homeserver = &homeserver($cnum,$cdom);
                   11455:     my $protocol = $protocol{$homeserver};
                   11456:     $protocol = 'http' if ($protocol ne 'https');
                   11457:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11458:     my $ua=new LWP::UserAgent;
                   11459:     my $request=new HTTP::Request($reqtype,$uri);
                   11460:     my $response=$ua->request($request);
                   11461:     $$rtncode = $response->code;
1.482     albertel 11462:     if (! $response->is_success()) {
                   11463: 	return 'failed';
                   11464:     }      
                   11465:     if ($reqtype eq 'HEAD') {
1.486     www      11466: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11467:     } elsif ($reqtype eq 'GET') {
                   11468: 	$$info = $response->content;
1.472     albertel 11469:     }
1.482     albertel 11470:     return 'ok';
1.36      albertel 11471: }
                   11472: 
1.481     raeburn  11473: sub readfile {
                   11474:     my $file = shift;
                   11475:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11476:     my $fh;
                   11477:     open($fh,"<$file");
                   11478:     my $a='';
1.800     albertel 11479:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11480:     return $a;
                   11481: }
                   11482: 
1.36      albertel 11483: sub filelocation {
1.590     banghart 11484:     my ($dir,$file) = @_;
                   11485:     my $location;
                   11486:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11487: 
                   11488:     if ($file =~ m-^/adm/-) {
                   11489: 	$file=~s-^/adm/wrapper/-/-;
                   11490: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11491:     }
1.882     albertel 11492: 
1.1139    www      11493:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11494:         $location = $file;
1.609     banghart 11495:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11496:         my ($udom,$uname,$filename)=
1.811     albertel 11497:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11498:         my $home=&homeserver($uname,$udom);
                   11499:         my $is_me=0;
                   11500:         my @ids=&current_machine_ids();
                   11501:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11502:         if ($is_me) {
1.1117    foxr     11503:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11504:         } else {
                   11505:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11506:   	      $udom.'/'.$uname.'/'.$filename;
                   11507:         }
1.882     albertel 11508:     } elsif ($file =~ m-^/adm/-) {
                   11509: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11510:     } else {
                   11511:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11512:         $file=~s:^/(res|priv)/:/:;
                   11513:         my $space=$1;
1.590     banghart 11514:         if ( !( $file =~ m:^/:) ) {
                   11515:             $location = $dir. '/'.$file;
                   11516:         } else {
1.1142    raeburn  11517:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11518:         }
1.59      albertel 11519:     }
1.590     banghart 11520:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11521:     while ($location=~m{/\.\./}) {
                   11522: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11523: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11524: 	} else {
                   11525: 	    $location=~ s{/\.\./}{/}g;
                   11526: 	}
                   11527:     } #remove dir/..
1.590     banghart 11528:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11529:     return $location;
1.46      www      11530: }
1.36      albertel 11531: 
1.46      www      11532: sub hreflocation {
                   11533:     my ($dir,$file)=@_;
1.980     raeburn  11534:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11535: 	$file=filelocation($dir,$file);
1.700     albertel 11536:     } elsif ($file=~m-^/adm/-) {
                   11537: 	$file=~s-^/adm/wrapper/-/-;
                   11538: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11539:     }
                   11540:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11541: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11542:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11543: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11544: 	        {/uploaded/$1/$2/}x;
1.46      www      11545:     }
1.913     albertel 11546:     if ($file=~ m{^/userfiles/}) {
                   11547: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11548:     }
1.462     albertel 11549:     return $file;
1.465     albertel 11550: }
                   11551: 
1.1139    www      11552: 
                   11553: 
                   11554: 
                   11555: 
1.465     albertel 11556: sub current_machine_domains {
1.853     albertel 11557:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11558: }
                   11559: 
                   11560: sub machine_domains {
                   11561:     my ($hostname) = @_;
1.465     albertel 11562:     my @domains;
1.838     albertel 11563:     my %hostname = &all_hostnames();
1.465     albertel 11564:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11565: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11566: 	if ($hostname eq $name) {
1.844     albertel 11567: 	    push(@domains,&host_domain($id));
1.465     albertel 11568: 	}
                   11569:     }
                   11570:     return @domains;
                   11571: }
                   11572: 
                   11573: sub current_machine_ids {
1.853     albertel 11574:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11575: }
                   11576: 
                   11577: sub machine_ids {
                   11578:     my ($hostname) = @_;
                   11579:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11580:     my @ids;
1.888     albertel 11581:     my %name_to_host = &all_names();
1.889     albertel 11582:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11583: 	return @{ $name_to_host{$hostname} };
                   11584:     }
                   11585:     return;
1.31      www      11586: }
                   11587: 
1.824     raeburn  11588: sub additional_machine_domains {
                   11589:     my @domains;
                   11590:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11591:     while( my $line = <$fh>) {
                   11592:         $line =~ s/\s//g;
                   11593:         push(@domains,$line);
                   11594:     }
                   11595:     return @domains;
                   11596: }
                   11597: 
                   11598: sub default_login_domain {
                   11599:     my $domain = $perlvar{'lonDefDomain'};
                   11600:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11601:     foreach my $posdom (&current_machine_domains(),
                   11602:                         &additional_machine_domains()) {
                   11603:         if (lc($posdom) eq lc($testdomain)) {
                   11604:             $domain=$posdom;
                   11605:             last;
                   11606:         }
                   11607:     }
                   11608:     return $domain;
                   11609: }
                   11610: 
1.31      www      11611: # ------------------------------------------------------------- Declutters URLs
                   11612: 
                   11613: sub declutter {
                   11614:     my $thisfn=shift;
1.569     albertel 11615:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11616:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11617:     $thisfn=~s/^\///;
1.697     albertel 11618:     $thisfn=~s|^adm/wrapper/||;
                   11619:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11620:     $thisfn=~s/^res\///;
1.1172    bisitz   11621:     $thisfn=~s/^priv\///;
1.1032    raeburn  11622:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11623:         $thisfn=~s/\?.+$//;
                   11624:     }
1.268     www      11625:     return $thisfn;
                   11626: }
                   11627: 
                   11628: # ------------------------------------------------------------- Clutter up URLs
                   11629: 
                   11630: sub clutter {
                   11631:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11632:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11633: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11634:        $thisfn='/res'.$thisfn; 
                   11635:     }
1.1031    raeburn  11636:     if ($thisfn !~m|^/adm|) {
                   11637: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11638: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11639: 	} else {
                   11640: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11641: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11642: 	    if ($embstyle eq 'ssi'
                   11643: 		|| ($embstyle eq 'hdn')
                   11644: 		|| ($embstyle eq 'rat')
                   11645: 		|| ($embstyle eq 'prv')
                   11646: 		|| ($embstyle eq 'ign')) {
                   11647: 		#do nothing with these
                   11648: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11649: 		|| ($embstyle eq 'emb')
                   11650: 		|| ($embstyle eq 'wrp')) {
                   11651: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11652: 	    } elsif ($embstyle eq 'unk'
                   11653: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11654: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11655: 	    } else {
1.718     www      11656: #		&logthis("Got a blank emb style");
1.695     albertel 11657: 	    }
1.694     albertel 11658: 	}
                   11659:     }
1.31      www      11660:     return $thisfn;
1.12      www      11661: }
                   11662: 
1.787     albertel 11663: sub clutter_with_no_wrapper {
                   11664:     my $uri = &clutter(shift);
                   11665:     if ($uri =~ m-^/adm/-) {
                   11666: 	$uri =~ s-^/adm/wrapper/-/-;
                   11667: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11668:     }
                   11669:     return $uri;
                   11670: }
                   11671: 
1.557     albertel 11672: sub freeze_escape {
                   11673:     my ($value)=@_;
                   11674:     if (ref($value)) {
                   11675: 	$value=&nfreeze($value);
                   11676: 	return '__FROZEN__'.&escape($value);
                   11677:     }
                   11678:     return &escape($value);
                   11679: }
                   11680: 
1.11      www      11681: 
1.557     albertel 11682: sub thaw_unescape {
                   11683:     my ($value)=@_;
                   11684:     if ($value =~ /^__FROZEN__/) {
                   11685: 	substr($value,0,10,undef);
                   11686: 	$value=&unescape($value);
                   11687: 	return &thaw($value);
                   11688:     }
                   11689:     return &unescape($value);
                   11690: }
                   11691: 
1.436     albertel 11692: sub correct_line_ends {
                   11693:     my ($result)=@_;
                   11694:     $$result =~s/\r\n/\n/mg;
                   11695:     $$result =~s/\r/\n/mg;
1.415     albertel 11696: }
1.1       albertel 11697: # ================================================================ Main Program
                   11698: 
1.184     www      11699: sub goodbye {
1.204     albertel 11700:    &logthis("Starting Shut down");
1.443     albertel 11701: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11702:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11703: #converted
1.599     albertel 11704: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11705:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11706: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11707: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11708: #1.1 only
1.870     albertel 11709: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11710: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11711: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11712: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11713:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11714:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11715:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11716:    &flushcourselogs();
                   11717:    &logthis("Shutting down");
                   11718: }
                   11719: 
1.852     albertel 11720: sub get_dns {
1.1210    raeburn  11721:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11722:     if (!$ignore_cache) {
                   11723: 	my ($content,$cached)=
                   11724: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11725: 	if ($cached) {
1.1210    raeburn  11726: 	    &$func($content,$hashref);
1.869     albertel 11727: 	    return;
                   11728: 	}
                   11729:     }
                   11730: 
                   11731:     my %alldns;
1.852     albertel 11732:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11733:     foreach my $dns (<$config>) {
                   11734: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11735:         my $line = $1;
                   11736:         my ($host,$protocol) = split(/:/,$line);
                   11737:         if ($protocol ne 'https') {
                   11738:             $protocol = 'http';
                   11739:         }
                   11740: 	$alldns{$host} = $protocol;
1.869     albertel 11741:     }
                   11742:     while (%alldns) {
                   11743: 	my ($dns) = keys(%alldns);
1.852     albertel 11744: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11745:         $ua->timeout(30);
1.979     raeburn  11746: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11747: 	my $response=$ua->request($request);
1.979     raeburn  11748:         delete($alldns{$dns});
1.852     albertel 11749: 	next if ($response->is_error());
                   11750: 	my @content = split("\n",$response->content);
1.1210    raeburn  11751: 	unless ($nocache) {
1.1219    raeburn  11752: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  11753: 	}
                   11754: 	&$func(\@content,$hashref);
1.869     albertel 11755: 	return;
1.852     albertel 11756:     }
                   11757:     close($config);
1.871     albertel 11758:     my $which = (split('/',$url))[3];
                   11759:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11760:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11761:     my @content = <$config>;
1.1210    raeburn  11762:     &$func(\@content,$hashref);
                   11763:     return;
                   11764: }
                   11765: 
                   11766: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  11767: sub parse_dns_checksums_tab {
1.1210    raeburn  11768:     my ($lines,$hashref) = @_;
                   11769:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11770:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11771:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11772:     my (%chksum,%revnum);
                   11773:     if (ref($lines) eq 'ARRAY') {
                   11774:         chomp(@{$lines});
1.1238    raeburn  11775:         my $version = shift(@{$lines});
                   11776:         if ($version eq $release) {  
1.1210    raeburn  11777:             foreach my $line (@{$lines}) {
1.1238    raeburn  11778:                 my ($file,$version,$shasum) = split(/,/,$line);
                   11779:                 $chksum{$file} = $shasum;
                   11780:                 $revnum{$file} = $version;
1.1210    raeburn  11781:             }
                   11782:             if (ref($hashref) eq 'HASH') {
                   11783:                 %{$hashref} = (
                   11784:                                 sums     => \%chksum,
                   11785:                                 versions => \%revnum,
                   11786:                               );
                   11787:             }
                   11788:         }
                   11789:     }
1.869     albertel 11790:     return;
1.852     albertel 11791: }
1.1210    raeburn  11792: 
                   11793: sub fetch_dns_checksums {
1.1238    raeburn  11794:     my %checksums;
                   11795:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11796:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11797:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11798:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  11799:              \%checksums);
1.1210    raeburn  11800:     return \%checksums;
                   11801: }
                   11802: 
1.327     albertel 11803: # ------------------------------------------------------------ Read domain file
                   11804: {
1.852     albertel 11805:     my $loaded;
1.846     albertel 11806:     my %domain;
                   11807: 
1.852     albertel 11808:     sub parse_domain_tab {
                   11809: 	my ($lines) = @_;
                   11810: 	foreach my $line (@$lines) {
                   11811: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11812: 
1.846     albertel 11813: 	    chomp($line);
1.852     albertel 11814: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11815: 	    my %this_domain;
                   11816: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11817: 			       'lang_def', 'city', 'longi', 'lati',
                   11818: 			       'primary') {
                   11819: 		$this_domain{$field} = shift(@elements);
                   11820: 	    }
                   11821: 	    $domain{$name} = \%this_domain;
1.852     albertel 11822: 	}
                   11823:     }
1.864     albertel 11824: 
                   11825:     sub reset_domain_info {
                   11826: 	undef($loaded);
                   11827: 	undef(%domain);
                   11828:     }
                   11829: 
1.852     albertel 11830:     sub load_domain_tab {
1.869     albertel 11831: 	my ($ignore_cache) = @_;
                   11832: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11833: 	my $fh;
                   11834: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11835: 	    my @lines = <$fh>;
                   11836: 	    &parse_domain_tab(\@lines);
1.448     albertel 11837: 	}
1.852     albertel 11838: 	close($fh);
                   11839: 	$loaded = 1;
1.327     albertel 11840:     }
1.846     albertel 11841: 
                   11842:     sub domain {
1.852     albertel 11843: 	&load_domain_tab() if (!$loaded);
                   11844: 
1.846     albertel 11845: 	my ($name,$what) = @_;
                   11846: 	return if ( !exists($domain{$name}) );
                   11847: 
                   11848: 	if (!$what) {
                   11849: 	    return $domain{$name}{'description'};
                   11850: 	}
                   11851: 	return $domain{$name}{$what};
                   11852:     }
1.974     raeburn  11853: 
                   11854:     sub domain_info {
                   11855:         &load_domain_tab() if (!$loaded);
                   11856:         return %domain;
                   11857:     }
                   11858: 
1.327     albertel 11859: }
                   11860: 
                   11861: 
1.1       albertel 11862: # ------------------------------------------------------------- Read hosts file
                   11863: {
1.838     albertel 11864:     my %hostname;
1.844     albertel 11865:     my %hostdom;
1.845     albertel 11866:     my %libserv;
1.852     albertel 11867:     my $loaded;
1.888     albertel 11868:     my %name_to_host;
1.1074    raeburn  11869:     my %internetdom;
1.1107    raeburn  11870:     my %LC_dns_serv;
1.852     albertel 11871: 
                   11872:     sub parse_hosts_tab {
                   11873: 	my ($file) = @_;
                   11874: 	foreach my $configline (@$file) {
                   11875: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11876:             chomp($configline);
                   11877: 	    if ($configline =~ /^\^/) {
                   11878:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11879:                     $LC_dns_serv{$1} = 1;
                   11880:                 }
                   11881:                 next;
                   11882:             }
1.1074    raeburn  11883: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11884: 	    $name=~s/\s//g;
                   11885: 	    if ($id && $domain && $role && $name) {
                   11886: 		$hostname{$id}=$name;
1.888     albertel 11887: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11888: 		$hostdom{$id}=$domain;
                   11889: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11890:                 if (defined($protocol)) {
                   11891:                     if ($protocol eq 'https') {
                   11892:                         $protocol{$id} = $protocol;
                   11893:                     } else {
                   11894:                         $protocol{$id} = 'http'; 
                   11895:                     }
1.968     raeburn  11896:                 } else {
1.969     raeburn  11897:                     $protocol{$id} = 'http';
1.968     raeburn  11898:                 }
1.1074    raeburn  11899:                 if (defined($intdom)) {
                   11900:                     $internetdom{$id} = $intdom;
                   11901:                 }
1.852     albertel 11902: 	    }
                   11903: 	}
                   11904:     }
1.864     albertel 11905:     
                   11906:     sub reset_hosts_info {
1.897     albertel 11907: 	&purge_remembered();
1.864     albertel 11908: 	&reset_domain_info();
                   11909: 	&reset_hosts_ip_info();
1.892     albertel 11910: 	undef(%name_to_host);
1.864     albertel 11911: 	undef(%hostname);
                   11912: 	undef(%hostdom);
                   11913: 	undef(%libserv);
                   11914: 	undef($loaded);
                   11915:     }
1.1       albertel 11916: 
1.852     albertel 11917:     sub load_hosts_tab {
1.869     albertel 11918: 	my ($ignore_cache) = @_;
                   11919: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11920: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11921: 	my @config = <$config>;
                   11922: 	&parse_hosts_tab(\@config);
                   11923: 	close($config);
                   11924: 	$loaded=1;
1.1       albertel 11925:     }
1.852     albertel 11926: 
1.838     albertel 11927:     sub hostname {
1.852     albertel 11928: 	&load_hosts_tab() if (!$loaded);
                   11929: 
1.838     albertel 11930: 	my ($lonid) = @_;
                   11931: 	return $hostname{$lonid};
                   11932:     }
1.845     albertel 11933: 
1.838     albertel 11934:     sub all_hostnames {
1.852     albertel 11935: 	&load_hosts_tab() if (!$loaded);
                   11936: 
1.838     albertel 11937: 	return %hostname;
                   11938:     }
1.845     albertel 11939: 
1.888     albertel 11940:     sub all_names {
                   11941: 	&load_hosts_tab() if (!$loaded);
                   11942: 
                   11943: 	return %name_to_host;
                   11944:     }
                   11945: 
1.974     raeburn  11946:     sub all_host_domain {
                   11947:         &load_hosts_tab() if (!$loaded);
                   11948:         return %hostdom;
                   11949:     }
                   11950: 
1.845     albertel 11951:     sub is_library {
1.852     albertel 11952: 	&load_hosts_tab() if (!$loaded);
                   11953: 
1.845     albertel 11954: 	return exists($libserv{$_[0]});
                   11955:     }
                   11956: 
                   11957:     sub all_library {
1.852     albertel 11958: 	&load_hosts_tab() if (!$loaded);
                   11959: 
1.845     albertel 11960: 	return %libserv;
                   11961:     }
                   11962: 
1.1062    droeschl 11963:     sub unique_library {
                   11964: 	#2x reverse removes all hostnames that appear more than once
                   11965:         my %unique = reverse &all_library();
                   11966:         return reverse %unique;
                   11967:     }
                   11968: 
1.841     albertel 11969:     sub get_servers {
1.852     albertel 11970: 	&load_hosts_tab() if (!$loaded);
                   11971: 
1.841     albertel 11972: 	my ($domain,$type) = @_;
                   11973: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11974: 	                                          : %hostname;
                   11975: 	my %result;
1.842     albertel 11976: 	if (ref($domain) eq 'ARRAY') {
                   11977: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11978: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11979: 		    $result{$host} = $hostname;
                   11980: 		}
                   11981: 	    }
                   11982: 	} else {
                   11983: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11984: 		if ($hostdom{$host} eq $domain) {
                   11985: 		    $result{$host} = $hostname;
                   11986: 		}
1.841     albertel 11987: 	    }
                   11988: 	}
                   11989: 	return %result;
                   11990:     }
1.845     albertel 11991: 
1.1062    droeschl 11992:     sub get_unique_servers {
                   11993:         my %unique = reverse &get_servers(@_);
                   11994: 	return reverse %unique;
                   11995:     }
                   11996: 
1.844     albertel 11997:     sub host_domain {
1.852     albertel 11998: 	&load_hosts_tab() if (!$loaded);
                   11999: 
1.844     albertel 12000: 	my ($lonid) = @_;
                   12001: 	return $hostdom{$lonid};
                   12002:     }
                   12003: 
1.841     albertel 12004:     sub all_domains {
1.852     albertel 12005: 	&load_hosts_tab() if (!$loaded);
                   12006: 
1.841     albertel 12007: 	my %seen;
                   12008: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12009: 	return @uniq;
                   12010:     }
1.1074    raeburn  12011: 
                   12012:     sub internet_dom {
                   12013:         &load_hosts_tab() if (!$loaded);
                   12014: 
                   12015:         my ($lonid) = @_;
                   12016:         return $internetdom{$lonid};
                   12017:     }
1.1107    raeburn  12018: 
                   12019:     sub is_LC_dns {
                   12020:         &load_hosts_tab() if (!$loaded);
                   12021: 
                   12022:         my ($hostname) = @_;
                   12023:         return exists($LC_dns_serv{$hostname});
                   12024:     }
                   12025: 
1.1       albertel 12026: }
                   12027: 
1.847     albertel 12028: { 
                   12029:     my %iphost;
1.856     albertel 12030:     my %name_to_ip;
                   12031:     my %lonid_to_ip;
1.869     albertel 12032: 
1.847     albertel 12033:     sub get_hosts_from_ip {
                   12034: 	my ($ip) = @_;
                   12035: 	my %iphosts = &get_iphost();
                   12036: 	if (ref($iphosts{$ip})) {
                   12037: 	    return @{$iphosts{$ip}};
                   12038: 	}
                   12039: 	return;
1.839     albertel 12040:     }
1.864     albertel 12041:     
                   12042:     sub reset_hosts_ip_info {
                   12043: 	undef(%iphost);
                   12044: 	undef(%name_to_ip);
                   12045: 	undef(%lonid_to_ip);
                   12046:     }
1.856     albertel 12047: 
                   12048:     sub get_host_ip {
                   12049: 	my ($lonid) = @_;
                   12050: 	if (exists($lonid_to_ip{$lonid})) {
                   12051: 	    return $lonid_to_ip{$lonid};
                   12052: 	}
                   12053: 	my $name=&hostname($lonid);
                   12054:    	my $ip = gethostbyname($name);
                   12055: 	return if (!$ip || length($ip) ne 4);
                   12056: 	$ip=inet_ntoa($ip);
                   12057: 	$name_to_ip{$name}   = $ip;
                   12058: 	$lonid_to_ip{$lonid} = $ip;
                   12059: 	return $ip;
                   12060:     }
1.847     albertel 12061:     
                   12062:     sub get_iphost {
1.869     albertel 12063: 	my ($ignore_cache) = @_;
1.894     albertel 12064: 
1.869     albertel 12065: 	if (!$ignore_cache) {
                   12066: 	    if (%iphost) {
                   12067: 		return %iphost;
                   12068: 	    }
                   12069: 	    my ($ip_info,$cached)=
                   12070: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12071: 	    if ($cached) {
                   12072: 		%iphost      = %{$ip_info->[0]};
                   12073: 		%name_to_ip  = %{$ip_info->[1]};
                   12074: 		%lonid_to_ip = %{$ip_info->[2]};
                   12075: 		return %iphost;
                   12076: 	    }
                   12077: 	}
1.894     albertel 12078: 
                   12079: 	# get yesterday's info for fallback
                   12080: 	my %old_name_to_ip;
                   12081: 	my ($ip_info,$cached)=
                   12082: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12083: 	if ($cached) {
                   12084: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12085: 	}
                   12086: 
1.888     albertel 12087: 	my %name_to_host = &all_names();
                   12088: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12089: 	    my $ip;
                   12090: 	    if (!exists($name_to_ip{$name})) {
                   12091: 		$ip = gethostbyname($name);
                   12092: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12093: 		    if (defined($old_name_to_ip{$name})) {
                   12094: 			$ip = $old_name_to_ip{$name};
                   12095: 			&logthis("Can't find $name defaulting to old $ip");
                   12096: 		    } else {
                   12097: 			&logthis("Name $name no IP found");
                   12098: 			next;
                   12099: 		    }
                   12100: 		} else {
                   12101: 		    $ip=inet_ntoa($ip);
1.847     albertel 12102: 		}
                   12103: 		$name_to_ip{$name} = $ip;
                   12104: 	    } else {
                   12105: 		$ip = $name_to_ip{$name};
1.653     albertel 12106: 	    }
1.888     albertel 12107: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12108: 		$lonid_to_ip{$id} = $ip;
                   12109: 	    }
                   12110: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12111: 	}
1.1219    raeburn  12112: 	&do_cache_new('iphost','iphost',
                   12113: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12114: 		      48*60*60);
1.869     albertel 12115: 
1.847     albertel 12116: 	return %iphost;
1.598     albertel 12117:     }
                   12118: 
1.992     raeburn  12119:     #
                   12120:     #  Given a DNS returns the loncapa host name for that DNS 
                   12121:     # 
                   12122:     sub host_from_dns {
                   12123:         my ($dns) = @_;
                   12124:         my @hosts;
                   12125:         my $ip;
                   12126: 
1.993     raeburn  12127:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12128:             $ip = $name_to_ip{$dns};
                   12129:         }
                   12130:         if (!$ip) {
                   12131:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12132:             if (length($ip) == 4) { 
                   12133: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12134:             }
                   12135:         }
                   12136:         if ($ip) {
                   12137: 	    @hosts = get_hosts_from_ip($ip);
                   12138: 	    return $hosts[0];
                   12139:         }
                   12140:         return undef;
1.986     foxr     12141:     }
1.992     raeburn  12142: 
1.1074    raeburn  12143:     sub get_internet_names {
                   12144:         my ($lonid) = @_;
                   12145:         return if ($lonid eq '');
                   12146:         my ($idnref,$cached)=
                   12147:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12148:         if ($cached) {
                   12149:             return $idnref;
                   12150:         }
                   12151:         my $ip = &get_host_ip($lonid);
                   12152:         my @hosts = &get_hosts_from_ip($ip);
                   12153:         my %iphost = &get_iphost();
                   12154:         my (@idns,%seen);
                   12155:         foreach my $id (@hosts) {
                   12156:             my $dom = &host_domain($id);
                   12157:             my $prim_id = &domain($dom,'primary');
                   12158:             my $prim_ip = &get_host_ip($prim_id);
                   12159:             next if ($seen{$prim_ip});
                   12160:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12161:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12162:                     my $intdom = &internet_dom($id);
                   12163:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12164:                         push(@idns,$intdom);
                   12165:                     }
                   12166:                 }
                   12167:             }
                   12168:             $seen{$prim_ip} = 1;
                   12169:         }
1.1219    raeburn  12170:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12171:     }
                   12172: 
1.986     foxr     12173: }
                   12174: 
1.1079    raeburn  12175: sub all_loncaparevs {
1.1249    raeburn  12176:     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  12177: }
                   12178: 
1.1227    raeburn  12179: # ---------------------------------------------------------- Read loncaparev table
                   12180: {
                   12181:     sub load_loncaparevs { 
                   12182:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12183:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12184:                 while (my $configline=<$config>) {
                   12185:                     chomp($configline);
                   12186:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12187:                     $loncaparevs{$hostid}=$loncaparev;
                   12188:                 }
                   12189:                 close($config);
                   12190:             }
                   12191:         }
                   12192:     }
                   12193: }
                   12194: 
                   12195: # ---------------------------------------------------------- Read serverhostID table
                   12196: {
                   12197:     sub load_serverhomeIDs {
                   12198:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12199:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12200:                 while (my $configline=<$config>) {
                   12201:                     chomp($configline);
                   12202:                     my ($name,$id)=split(/:/,$configline);
                   12203:                     $serverhomeIDs{$name}=$id;
                   12204:                 }
                   12205:                 close($config);
                   12206:             }
                   12207:         }
                   12208:     }
                   12209: }
                   12210: 
                   12211: 
1.862     albertel 12212: BEGIN {
                   12213: 
                   12214: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12215:     unless ($readit) {
                   12216: {
                   12217:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12218:     %perlvar = (%perlvar,%{$configvars});
                   12219: }
                   12220: 
                   12221: 
1.1       albertel 12222: # ------------------------------------------------------ Read spare server file
                   12223: {
1.448     albertel 12224:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12225: 
                   12226:     while (my $configline=<$config>) {
                   12227:        chomp($configline);
1.284     matthew  12228:        if ($configline) {
1.784     albertel 12229: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12230: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12231: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12232:        }
                   12233:     }
1.448     albertel 12234:     close($config);
1.1       albertel 12235: }
1.11      www      12236: # ------------------------------------------------------------ Read permissions
                   12237: {
1.448     albertel 12238:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12239: 
                   12240:     while (my $configline=<$config>) {
1.448     albertel 12241: 	chomp($configline);
                   12242: 	if ($configline) {
                   12243: 	    my ($role,$perm)=split(/ /,$configline);
                   12244: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12245: 	}
1.11      www      12246:     }
1.448     albertel 12247:     close($config);
1.11      www      12248: }
                   12249: 
                   12250: # -------------------------------------------- Read plain texts for permissions
                   12251: {
1.448     albertel 12252:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12253: 
                   12254:     while (my $configline=<$config>) {
1.448     albertel 12255: 	chomp($configline);
                   12256: 	if ($configline) {
1.742     raeburn  12257: 	    my ($short,@plain)=split(/:/,$configline);
                   12258:             %{$prp{$short}} = ();
                   12259: 	    if (@plain > 0) {
                   12260:                 $prp{$short}{'std'} = $plain[0];
                   12261:                 for (my $i=1; $i<@plain; $i++) {
                   12262:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12263:                 }
                   12264:             }
1.448     albertel 12265: 	}
1.135     www      12266:     }
1.448     albertel 12267:     close($config);
1.135     www      12268: }
                   12269: 
                   12270: # ---------------------------------------------------------- Read package table
                   12271: {
1.448     albertel 12272:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12273: 
                   12274:     while (my $configline=<$config>) {
1.483     albertel 12275: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12276: 	chomp($configline);
                   12277: 	my ($short,$plain)=split(/:/,$configline);
                   12278: 	my ($pack,$name)=split(/\&/,$short);
                   12279: 	if ($plain ne '') {
                   12280: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12281: 	    $packagetab{$short}=$plain; 
                   12282: 	}
1.11      www      12283:     }
1.448     albertel 12284:     close($config);
1.329     matthew  12285: }
                   12286: 
1.1073    raeburn  12287: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12288: 
                   12289: &load_loncaparevs();
1.1073    raeburn  12290: 
1.1074    raeburn  12291: # ---------------------------------------------------------- Read serverhostID table
                   12292: 
1.1227    raeburn  12293: &load_serverhomeIDs();
                   12294: 
                   12295: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12296: {
                   12297:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12298:     if (-e $file) {
                   12299:         my $parser = HTML::LCParser->new($file);
                   12300:         while (my $token = $parser->get_token()) {
                   12301:             if ($token->[0] eq 'S') {
                   12302:                 my $item = $token->[1];
                   12303:                 my $name = $token->[2]{'name'};
                   12304:                 my $value = $token->[2]{'value'};
                   12305:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12306:                     my $release = $parser->get_text();
                   12307:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12308:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12309:                 }
                   12310:             }
                   12311:         }
                   12312:     }
1.1073    raeburn  12313: }
                   12314: 
1.1138    raeburn  12315: # ---------------------------------------------------------- Read managers table
                   12316: {
                   12317:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12318:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12319:             while (my $configline=<$config>) {
                   12320:                 chomp($configline);
                   12321:                 next if ($configline =~ /^\#/);
                   12322:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12323:                     $managerstab{$configline} = 1;
                   12324:                 }
                   12325:             }
                   12326:             close($config);
                   12327:         }
                   12328:     }
                   12329: }
                   12330: 
1.329     matthew  12331: # ------------- set up temporary directory
                   12332: {
1.1117    foxr     12333:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12334: 
1.11      www      12335: }
                   12336: 
1.794     albertel 12337: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12338: 				'compress_threshold'=> 20_000,
                   12339:  			        });
1.185     www      12340: 
1.281     www      12341: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12342: $dumpcount=0;
1.958     www      12343: $locknum=0;
1.22      www      12344: 
1.163     harris41 12345: &logtouch();
1.672     albertel 12346: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12347: $readit=1;
1.564     albertel 12348:     {
                   12349: 	use integer;
                   12350: 	my $test=(2**32)+1;
1.568     albertel 12351: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12352: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12353:     }
1.195     www      12354: }
1.1       albertel 12355: }
1.179     www      12356: 
1.1       albertel 12357: 1;
1.191     harris41 12358: __END__
                   12359: 
1.243     albertel 12360: =pod
                   12361: 
1.191     harris41 12362: =head1 NAME
                   12363: 
1.243     albertel 12364: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12365: 
                   12366: =head1 SYNOPSIS
                   12367: 
1.243     albertel 12368: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12369: 
                   12370:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12371: 
1.243     albertel 12372: Common parameters:
                   12373: 
                   12374: =over 4
                   12375: 
                   12376: =item *
                   12377: 
                   12378: $uname : an internal username (if $cname expecting a course Id specifically)
                   12379: 
                   12380: =item *
                   12381: 
                   12382: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12383: 
                   12384: =item *
                   12385: 
                   12386: $symb : a resource instance identifier
                   12387: 
                   12388: =item *
                   12389: 
                   12390: $namespace : the name of a .db file that contains the data needed or
                   12391: being set.
                   12392: 
                   12393: =back
                   12394: 
1.394     bowersj2 12395: =head1 OVERVIEW
1.191     harris41 12396: 
1.394     bowersj2 12397: lonnet provides subroutines which interact with the
                   12398: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12399: about classes, users, and resources.
1.243     albertel 12400: 
                   12401: For many of these objects you can also use this to store data about
                   12402: them or modify them in various ways.
1.191     harris41 12403: 
1.394     bowersj2 12404: =head2 Symbs
1.191     harris41 12405: 
1.394     bowersj2 12406: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12407: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12408: map, the resource number of the resource in the map, and the URL of
                   12409: the resource itself. The latter is somewhat redundant, but might help
                   12410: if maps change.
                   12411: 
                   12412: An example is
                   12413: 
                   12414:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12415: 
                   12416: The respective map entry is
                   12417: 
                   12418:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12419:   title="Problem 2">
                   12420:  </resource>
                   12421: 
                   12422: Symbs are used by the random number generator, as well as to store and
                   12423: restore data specific to a certain instance of for example a problem.
                   12424: 
                   12425: =head2 Storing And Retrieving Data
                   12426: 
                   12427: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12428: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12429: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12430: is is the non-critical message twin of cstore. These functions are for
                   12431: handlers to store a perl hash to a user's permanent data space in an
                   12432: easy manner, and to retrieve it again on another call. It is expected
                   12433: that a handler would use this once at the beginning to retrieve data,
                   12434: and then again once at the end to send only the new data back.
                   12435: 
                   12436: The data is stored in the user's data directory on the user's
                   12437: homeserver under the ID of the course.
                   12438: 
                   12439: The hash that is returned by restore will have all of the previous
                   12440: value for all of the elements of the hash.
                   12441: 
                   12442: Example:
                   12443: 
                   12444:  #creating a hash
                   12445:  my %hash;
                   12446:  $hash{'foo'}='bar';
                   12447: 
                   12448:  #storing it
                   12449:  &Apache::lonnet::cstore(\%hash);
                   12450: 
                   12451:  #changing a value
                   12452:  $hash{'foo'}='notbar';
                   12453: 
                   12454:  #adding a new value
                   12455:  $hash{'bar'}='foo';
                   12456:  &Apache::lonnet::cstore(\%hash);
                   12457: 
                   12458:  #retrieving the hash
                   12459:  my %history=&Apache::lonnet::restore();
                   12460: 
                   12461:  #print the hash
                   12462:  foreach my $key (sort(keys(%history))) {
                   12463:    print("\%history{$key} = $history{$key}");
                   12464:  }
                   12465: 
                   12466: Will print out:
1.191     harris41 12467: 
1.394     bowersj2 12468:  %history{1:foo} = bar
                   12469:  %history{1:keys} = foo:timestamp
                   12470:  %history{1:timestamp} = 990455579
                   12471:  %history{2:bar} = foo
                   12472:  %history{2:foo} = notbar
                   12473:  %history{2:keys} = foo:bar:timestamp
                   12474:  %history{2:timestamp} = 990455580
                   12475:  %history{bar} = foo
                   12476:  %history{foo} = notbar
                   12477:  %history{timestamp} = 990455580
                   12478:  %history{version} = 2
                   12479: 
                   12480: Note that the special hash entries C<keys>, C<version> and
                   12481: C<timestamp> were added to the hash. C<version> will be equal to the
                   12482: total number of versions of the data that have been stored. The
                   12483: C<timestamp> attribute will be the UNIX time the hash was
                   12484: stored. C<keys> is available in every historical section to list which
                   12485: keys were added or changed at a specific historical revision of a
                   12486: hash.
                   12487: 
                   12488: B<Warning>: do not store the hash that restore returns directly. This
                   12489: will cause a mess since it will restore the historical keys as if the
                   12490: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12491: 
1.394     bowersj2 12492: Calling convention:
1.191     harris41 12493: 
1.1225    raeburn  12494:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
                   12495:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191     harris41 12496: 
1.394     bowersj2 12497: For more detailed information, see lonnet specific documentation.
1.191     harris41 12498: 
1.394     bowersj2 12499: =head1 RETURN MESSAGES
1.191     harris41 12500: 
1.394     bowersj2 12501: =over 4
1.191     harris41 12502: 
1.394     bowersj2 12503: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12504: 
1.394     bowersj2 12505: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12506: when the connection is brought back up
1.191     harris41 12507: 
1.394     bowersj2 12508: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12509: for later delivery
1.191     harris41 12510: 
1.967     bisitz   12511: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12512: 
1.394     bowersj2 12513: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12514: that was requested
1.191     harris41 12515: 
1.243     albertel 12516: =back
1.191     harris41 12517: 
1.243     albertel 12518: =head1 PUBLIC SUBROUTINES
1.191     harris41 12519: 
1.243     albertel 12520: =head2 Session Environment Functions
1.191     harris41 12521: 
1.243     albertel 12522: =over 4
1.191     harris41 12523: 
1.394     bowersj2 12524: =item * 
                   12525: X<appenv()>
1.949     raeburn  12526: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12527: the user envirnoment file, and will be restored for each access this
1.620     albertel 12528: user makes during this session, also modifies the %env for the current
1.949     raeburn  12529: process. Optional rolesarrayref - if defined contains a reference to an array
                   12530: of roles which are exempt from the restriction on modifying user.role entries 
                   12531: in the user's environment.db and in %env.    
1.191     harris41 12532: 
                   12533: =item *
1.394     bowersj2 12534: X<delenv()>
1.987     raeburn  12535: B<delenv($delthis,$regexp)>: removes all items from the session
                   12536: environment file that begin with $delthis. If the 
                   12537: optional second arg - $regexp - is true, $delthis is treated as a 
                   12538: regular expression, otherwise \Q$delthis\E is used. 
                   12539: The values are also deleted from the current processes %env.
1.191     harris41 12540: 
1.795     albertel 12541: =item * get_env_multiple($name) 
                   12542: 
                   12543: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12544: values may be defined and end up as an array ref.
                   12545: 
                   12546: returns an array of values
                   12547: 
1.243     albertel 12548: =back
                   12549: 
                   12550: =head2 User Information
1.191     harris41 12551: 
1.243     albertel 12552: =over 4
1.191     harris41 12553: 
                   12554: =item *
1.394     bowersj2 12555: X<queryauthenticate()>
                   12556: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12557: authentication scheme
                   12558: 
                   12559: =item *
1.394     bowersj2 12560: X<authenticate()>
1.1073    raeburn  12561: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12562: authenticate user from domain's lib servers (first use the current
                   12563: one). C<$upass> should be the users password.
1.1073    raeburn  12564: $checkdefauth is optional (value is 1 if a check should be made to
                   12565:    authenticate user using default authentication method, and allow
                   12566:    account creation if username does not have account in the domain).
                   12567: $clientcancheckhost is optional (value is 1 if checking whether the
                   12568:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12569: 
                   12570: =item *
1.394     bowersj2 12571: X<homeserver()>
                   12572: B<homeserver($uname,$udom)>: find the server which has
                   12573: the user's directory and files (there must be only one), this caches
                   12574: the answer, and also caches if there is a borken connection.
1.191     harris41 12575: 
                   12576: =item *
1.394     bowersj2 12577: X<idget()>
                   12578: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12579: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12580: username, and only 1 username per ID in a specific domain) (returns
                   12581: hash: id=>name,id=>name)
1.191     harris41 12582: 
                   12583: =item *
1.394     bowersj2 12584: X<idrget()>
                   12585: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12586: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12587: 
                   12588: =item *
1.394     bowersj2 12589: X<idput()>
                   12590: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12591: 
                   12592: =item *
1.394     bowersj2 12593: X<rolesinit()>
1.1169    droeschl 12594: B<rolesinit($udom,$username)>: get user privileges.
                   12595: returns user role, first access and timer interval hashes
1.243     albertel 12596: 
                   12597: =item *
1.1171    droeschl 12598: X<privileged()>
                   12599: B<privileged($username,$domain)>: returns a true if user has a
                   12600: privileged and active role (i.e. su or dc), false otherwise.
                   12601: 
                   12602: =item *
1.551     albertel 12603: X<getsection()>
                   12604: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12605: course $cname, return section name/number or '' for "not in course"
                   12606: and '-1' for "no section"
                   12607: 
                   12608: =item *
1.394     bowersj2 12609: X<userenvironment()>
                   12610: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12611: passed in @what from the requested user's environment, returns a hash
                   12612: 
1.858     raeburn  12613: =item * 
                   12614: X<userlog_query()>
1.859     albertel 12615: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12616: activity.log file. %filters defines filters applied when parsing the
                   12617: log file. These can be start or end timestamps, or the type of action
                   12618: - log to look for Login or Logout events, check for Checkin or
                   12619: Checkout, role for role selection. The response is in the form
                   12620: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12621: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12622: 
1.243     albertel 12623: =back
                   12624: 
                   12625: =head2 User Roles
                   12626: 
                   12627: =over 4
                   12628: 
                   12629: =item *
                   12630: 
1.810     raeburn  12631: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12632:  F: full access
                   12633:  U,I,K: authentication modes (cxx only)
                   12634:  '': forbidden
                   12635:  1: user needs to choose course
                   12636:  2: browse allowed
1.766     albertel 12637:  A: passphrase authentication needed
1.243     albertel 12638: 
                   12639: =item *
                   12640: 
1.1192    raeburn  12641: constructaccess($url,$setpriv) : check for access to construction space URL
                   12642: 
                   12643: See if the owner domain and name in the URL match those in the
                   12644: expected environment.  If so, return three element list
                   12645: ($ownername,$ownerdomain,$ownerhome).
                   12646: 
                   12647: Otherwise return the null string.
                   12648: 
                   12649: If second argument 'setpriv' is true, it assigns the privileges,
                   12650: and returns the same three element list, unless the owner has
                   12651: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12652: in which case the null string is returned.
                   12653: 
                   12654: =item *
                   12655: 
1.243     albertel 12656: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12657: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12658: and course level
                   12659: 
                   12660: =item *
                   12661: 
1.988     raeburn  12662: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12663: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12664: $type is Course (default) or Community.
1.988     raeburn  12665: If $forcedefault evaluates to true, text returned will be default 
                   12666: text for $type. Otherwise, if this is a course, the text returned 
                   12667: will be a custom name for the role (if defined in the course's 
                   12668: environment).  If no custom name is defined the default is returned.
                   12669:    
1.832     raeburn  12670: =item *
                   12671: 
1.1219    raeburn  12672: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12673: All arguments are optional. Returns a hash of a roles, either for
                   12674: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12675: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12676: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12677: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12678: For each key, value is set to colon-separated start and end times for
                   12679: the role.  If no username and domain are specified, will default to
1.934     raeburn  12680: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12681: of role statuses (active, future or previous), roles 
                   12682: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12683: to restrict the list of roles reported. If no array ref is 
                   12684: provided for types, will default to return only active roles.
1.834     albertel 12685: 
1.1195    raeburn  12686: =item *
                   12687: 
                   12688: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  12689: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   12690: 
                   12691: Additional optional arguments are: $type (if role checking is to be restricted 
                   12692: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  12693: available roles) or future (roles available in the future), and
                   12694: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  12695: have active Domain Coordinator role in course's domain or in additional
                   12696: domains (specified in 'Domains to check for privileged users' in course
                   12697: environment -- set via:  Course Settings -> Classlists and staff listing).
                   12698: 
                   12699: =item *
                   12700: 
                   12701: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   12702: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   12703: $possdomains and $possroles are optional array refs -- to domains to check and
                   12704: roles to check.  If $possdomains is not specified, a dump will be done of the
                   12705: users' roles.db to check for a dc or su role in any domain. This can be
                   12706: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   12707: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   12708: this then allows &privileged_by_domain() to be used, which caches the identity
                   12709: of privileged users, eliminating the need for repeated calls to &dump().
                   12710: 
                   12711: =item *
                   12712: 
                   12713: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   12714: where the outer hash keys are domains specified in the $possdomains array ref,
                   12715: next inner hash keys are privileged roles specified in the $roles array ref,
                   12716: and the innermost hash contains key = value pairs for username:domain = end:start
                   12717: for active or future "privileged" users with that role in that domain. To avoid
                   12718: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   12719: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  12720: 
1.243     albertel 12721: =back
                   12722: 
                   12723: =head2 User Modification
                   12724: 
                   12725: =over 4
                   12726: 
                   12727: =item *
                   12728: 
1.957     raeburn  12729: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12730: user for the level given by URL.  Optional start and end dates (leave empty
                   12731: string or zero for "no date")
1.191     harris41 12732: 
                   12733: =item *
                   12734: 
1.243     albertel 12735: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12736: change a users, password, possible return values are: ok,
                   12737: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12738: refused
1.191     harris41 12739: 
                   12740: =item *
                   12741: 
1.243     albertel 12742: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12743: 
                   12744: =item *
                   12745: 
1.1058    raeburn  12746: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12747:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12748: 
                   12749: will update user information (firstname,middlename,lastname,generation,
                   12750: permanentemail), and if forceid is true, student/employee ID also.
                   12751: A user's institutional affiliation(s) can also be updated.
                   12752: User information fields will not be overwritten with empty entries 
                   12753: unless the field is included in the $candelete array reference.
                   12754: This array is included when a single user is modified via "Manage Users",
                   12755: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12756: 
                   12757: =item *
                   12758: 
1.286     matthew  12759: modifystudent
                   12760: 
1.957     raeburn  12761: modify a student's enrollment and identification information.
1.1235    raeburn  12762: The course id is resolved based on the current user's environment.  
                   12763: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  12764: associated with a course.
                   12765: 
1.297     matthew  12766: This call is essentially a wrapper for lonnet::modifyuser and
                   12767: lonnet::modify_student_enrollment
1.286     matthew  12768: 
                   12769: Inputs: 
                   12770: 
                   12771: =over 4
                   12772: 
1.957     raeburn  12773: =item B<$udom> Student's loncapa domain
1.286     matthew  12774: 
1.957     raeburn  12775: =item B<$uname> Student's loncapa login name
1.286     matthew  12776: 
1.964     bisitz   12777: =item B<$uid> Student/Employee ID
1.286     matthew  12778: 
1.957     raeburn  12779: =item B<$umode> Student's authentication mode
1.286     matthew  12780: 
1.957     raeburn  12781: =item B<$upass> Student's password
1.286     matthew  12782: 
1.957     raeburn  12783: =item B<$first> Student's first name
1.286     matthew  12784: 
1.957     raeburn  12785: =item B<$middle> Student's middle name
1.286     matthew  12786: 
1.957     raeburn  12787: =item B<$last> Student's last name
1.286     matthew  12788: 
1.957     raeburn  12789: =item B<$gene> Student's generation
1.286     matthew  12790: 
1.957     raeburn  12791: =item B<$usec> Student's section in course
1.286     matthew  12792: 
                   12793: =item B<$end> Unix time of the roles expiration
                   12794: 
                   12795: =item B<$start> Unix time of the roles start date
                   12796: 
                   12797: =item B<$forceid> If defined, allow $uid to be changed
                   12798: 
                   12799: =item B<$desiredhome> server to use as home server for student
                   12800: 
1.957     raeburn  12801: =item B<$email> Student's permanent e-mail address
                   12802: 
                   12803: =item B<$type> Type of enrollment (auto or manual)
                   12804: 
1.963     raeburn  12805: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12806: 
                   12807: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12808: 
1.963     raeburn  12809: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12810: 
1.963     raeburn  12811: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12812: 
1.1216    raeburn  12813: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12814: 
                   12815: =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  12816: 
1.286     matthew  12817: =back
1.297     matthew  12818: 
                   12819: =item *
                   12820: 
                   12821: modify_student_enrollment
                   12822: 
1.1235    raeburn  12823: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  12824: 'role.request.course' must be defined for this function to proceed.
                   12825: 
                   12826: Inputs:
                   12827: 
                   12828: =over 4
                   12829: 
1.1235    raeburn  12830: =item $udom, student's domain
1.297     matthew  12831: 
1.1235    raeburn  12832: =item $uname, student's name
1.297     matthew  12833: 
1.1235    raeburn  12834: =item $uid, student's user id
1.297     matthew  12835: 
1.1235    raeburn  12836: =item $first, student's first name
1.297     matthew  12837: 
                   12838: =item $middle
                   12839: 
                   12840: =item $last
                   12841: 
                   12842: =item $gene
                   12843: 
                   12844: =item $usec
                   12845: 
                   12846: =item $end
                   12847: 
                   12848: =item $start
                   12849: 
1.957     raeburn  12850: =item $type
                   12851: 
                   12852: =item $locktype
                   12853: 
                   12854: =item $cid
                   12855: 
                   12856: =item $selfenroll
                   12857: 
                   12858: =item $context
                   12859: 
1.1216    raeburn  12860: =item $credits, number of credits student will earn from this class
                   12861: 
1.297     matthew  12862: =back
                   12863: 
1.191     harris41 12864: 
                   12865: =item *
                   12866: 
1.243     albertel 12867: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12868: custom role; give a custom role to a user for the level given by URL.  Specify
                   12869: name and domain of role author, and role name
1.191     harris41 12870: 
                   12871: =item *
                   12872: 
1.243     albertel 12873: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12874: 
                   12875: =item *
                   12876: 
1.243     albertel 12877: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12878: 
                   12879: =back
                   12880: 
                   12881: =head2 Course Infomation
                   12882: 
                   12883: =over 4
1.191     harris41 12884: 
                   12885: =item *
                   12886: 
1.1118    foxr     12887: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12888: specified course id, including all environment settings for the
                   12889: course, the description of the course will be in the hash under the
                   12890: key 'description'
1.191     harris41 12891: 
1.1118    foxr     12892: $options is an optional parameter that if supplied is a hash reference that controls
                   12893: what how this function works.  It has the following key/values:
                   12894: 
                   12895: =over 4
                   12896: 
                   12897: =item freshen_cache
                   12898: 
                   12899: If defined, and the environment cache for the course is valid, it is 
                   12900: returned in the returned hash.
                   12901: 
                   12902: =item one_time
                   12903: 
                   12904: If defined, the last cache time is set to _now_
                   12905: 
                   12906: =item user
                   12907: 
                   12908: If defined, the supplied username is used instead of the current user.
                   12909: 
                   12910: 
                   12911: =back
                   12912: 
1.191     harris41 12913: =item *
                   12914: 
1.624     albertel 12915: resdata($name,$domain,$type,@which) : request for current parameter
                   12916: setting for a specific $type, where $type is either 'course' or 'user',
                   12917: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  12918: answers for 10 minutes.
1.243     albertel 12919: 
1.877     foxr     12920: =item *
                   12921: 
                   12922: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12923: data base, returning a hash that is keyed by the resource name and has
                   12924: values that are the resource value.  I believe that the timestamps and
                   12925: versions are also returned.
                   12926: 
1.1236    raeburn  12927: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   12928: supplemental content area. This routine caches the number of files for 
                   12929: 10 minutes.
                   12930: 
1.243     albertel 12931: =back
                   12932: 
                   12933: =head2 Course Modification
                   12934: 
                   12935: =over 4
1.191     harris41 12936: 
                   12937: =item *
                   12938: 
1.243     albertel 12939: writecoursepref($courseid,%prefs) : write preferences (environment
                   12940: database) for a course
1.191     harris41 12941: 
                   12942: =item *
                   12943: 
1.1011    raeburn  12944: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12945: 
                   12946: =item *
                   12947: 
1.1038    raeburn  12948: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12949: 
1.1167    droeschl 12950: =item *
                   12951: 
                   12952: is_course($courseid), is_course($cdom, $cnum)
                   12953: 
                   12954: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12955: two component version $cdom, $cnum. It checks if the specified course exists.
                   12956: 
                   12957: Returns:
                   12958:     undef if the course doesn't exist, otherwise
                   12959:     in scalar context the combined courseid.
                   12960:     in list context the two components of the course identifier, domain and 
                   12961:     courseid.    
                   12962: 
1.243     albertel 12963: =back
                   12964: 
                   12965: =head2 Resource Subroutines
                   12966: 
                   12967: =over 4
1.191     harris41 12968: 
                   12969: =item *
                   12970: 
1.243     albertel 12971: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12972: 
                   12973: =item *
                   12974: 
1.243     albertel 12975: repcopy($filename) : subscribes to the requested file, and attempts to
                   12976: replicate from the owning library server, Might return
1.607     raeburn  12977: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12978: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12979: resource. Expects the local filesystem pathname
                   12980: (/home/httpd/html/res/....)
                   12981: 
                   12982: =back
                   12983: 
                   12984: =head2 Resource Information
                   12985: 
                   12986: =over 4
1.191     harris41 12987: 
                   12988: =item *
                   12989: 
1.1228    raeburn  12990: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   12991: and returns the value of a variety of different possible values,
                   12992: $varname should be a request string, and the other parameters can be
                   12993: used to specify who and what one is asking about. Ordinarily, $cid 
                   12994: does not need to be specified, as it is retrived from 
                   12995: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   12996: within lonuserstate::loadmap() when initializing a course, before
                   12997: $env{'request.course.id'} has been set, so it needs to be provided
                   12998: in that one case.
1.243     albertel 12999: 
                   13000: Possible values for $varname are environment.lastname (or other item
                   13001: from the envirnment hash), user.name (or someother aspect about the
                   13002: user), resource.0.maxtries (or some other part and parameter of a
                   13003: resource)
1.204     albertel 13004: 
                   13005: =item *
                   13006: 
1.243     albertel 13007: directcondval($number) : get current value of a condition; reads from a state
                   13008: string
1.204     albertel 13009: 
                   13010: =item *
                   13011: 
1.243     albertel 13012: condval($condidx) : value of condition index based on state
1.204     albertel 13013: 
                   13014: =item *
                   13015: 
1.243     albertel 13016: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13017: resource's metadata, $what should be either a specific key, or either
                   13018: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13019: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13020: 
                   13021: this function automatically caches all requests
1.191     harris41 13022: 
                   13023: =item *
                   13024: 
1.243     albertel 13025: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13026: network of library servers; returns file handle of where SQL and regex results
                   13027: will be stored for query
1.191     harris41 13028: 
                   13029: =item *
                   13030: 
1.243     albertel 13031: symbread($filename) : return symbolic list entry (filename argument optional);
                   13032: returns the data handle
1.191     harris41 13033: 
                   13034: =item *
                   13035: 
1.1190    raeburn  13036: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13037: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13038: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13039: on failure, user must be in a course, as it assumes the existence of
                   13040: the course initial hash, and uses $env('request.course.id'}.  The third
                   13041: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13042: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13043: encrypted; otherwise it will be null.  
1.191     harris41 13044: 
                   13045: =item *
                   13046: 
1.243     albertel 13047: symbclean($symb) : removes versions numbers from a symb, returns the
                   13048: cleaned symb
1.191     harris41 13049: 
                   13050: =item *
                   13051: 
1.243     albertel 13052: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13053: course map, user must be in a course for it to work.
1.191     harris41 13054: 
                   13055: =item *
                   13056: 
1.243     albertel 13057: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13058: 
                   13059: =item *
                   13060: 
1.243     albertel 13061: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13062: a random seed, all arguments are optional, if they aren't sent it uses the
                   13063: environment to derive them. Note: if symb isn't sent and it can't get one
                   13064: from &symbread it will use the current time as its return value
1.191     harris41 13065: 
                   13066: =item *
                   13067: 
1.243     albertel 13068: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13069: unfakeable, receipt
1.191     harris41 13070: 
                   13071: =item *
                   13072: 
1.620     albertel 13073: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13074: 
                   13075: =item *
                   13076: 
1.243     albertel 13077: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13078: 
                   13079: =item *
                   13080: 
1.243     albertel 13081: 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 13082: 
                   13083: =item *
                   13084: 
1.243     albertel 13085: 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 13086: 
                   13087: =item *
                   13088: 
1.243     albertel 13089: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13090: 
                   13091: =item *
                   13092: 
1.243     albertel 13093: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13094: forcing spreadsheet to reevaluate the resource scores next time.
                   13095: 
1.1195    raeburn  13096: =item * 
                   13097: 
1.1196    raeburn  13098: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13099: when viewing in course context.
1.1195    raeburn  13100: 
1.1196    raeburn  13101:  input: six args -- filename (decluttered), course number, course domain,
                   13102:                     url, symb (if registered) and group (if this is a 
                   13103:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13104: 
1.1196    raeburn  13105:  output: array of five scalars --
1.1195    raeburn  13106:          $cfile -- url for file editing if editable on current server
                   13107:          $home -- homeserver of resource (i.e., for author if published,
                   13108:                                           or course if uploaded.).
                   13109:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13110:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13111:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13112: 
                   13113: =item *
                   13114: 
                   13115: is_course_upload($file,$cnum,$cdom)
                   13116: 
                   13117: Used in course context to determine if current file was uploaded to 
                   13118: the course (i.e., would be found in /userfiles/docs on the course's 
                   13119: homeserver.
                   13120: 
                   13121:   input: 3 args -- filename (decluttered), course number and course domain.
                   13122:   output: boolean -- 1 if file was uploaded.
                   13123: 
1.243     albertel 13124: =back
                   13125: 
                   13126: =head2 Storing/Retreiving Data
                   13127: 
                   13128: =over 4
1.191     harris41 13129: 
                   13130: =item *
                   13131: 
1.243     albertel 13132: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13133: for this url; hashref needs to be given and should be a \%hashname; the
                   13134: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13135: be derived from the env
1.191     harris41 13136: 
                   13137: =item *
                   13138: 
1.243     albertel 13139: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13140: uses critical subroutine
1.191     harris41 13141: 
                   13142: =item *
                   13143: 
1.243     albertel 13144: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13145: all args are optional
1.191     harris41 13146: 
                   13147: =item *
                   13148: 
1.717     albertel 13149: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13150: dumps the complete (or key matching regexp) namespace into a hash
                   13151: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13152: normally &store()ed into
                   13153: 
                   13154: $range should be either an integer '100' (give me the first 100
                   13155:                                            matching records)
                   13156:               or be  two integers sperated by a - with no spaces
                   13157:                  '30-50' (give me the 30th through the 50th matching
                   13158:                           records)
                   13159: 
                   13160: 
                   13161: =item *
                   13162: 
                   13163: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13164: replaces a &store() version of data with a replacement set of data
                   13165: for a particular resource in a namespace passed in the $storehash hash 
                   13166: reference
                   13167: 
                   13168: =item *
                   13169: 
1.243     albertel 13170: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13171: works very similar to store/cstore, but all data is stored in a
                   13172: temporary location and can be reset using tmpreset, $storehash should
                   13173: be a hash reference, returns nothing on success
1.191     harris41 13174: 
                   13175: =item *
                   13176: 
1.243     albertel 13177: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13178: similar to restore, but all data is stored in a temporary location and
                   13179: can be reset using tmpreset. Returns a hash of values on success,
                   13180: error string otherwise.
1.191     harris41 13181: 
                   13182: =item *
                   13183: 
1.243     albertel 13184: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13185: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13186: 
                   13187: =item *
                   13188: 
1.243     albertel 13189: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13190: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13191: 
                   13192: =item *
                   13193: 
1.243     albertel 13194: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13195: namesp ($udom and $uname are optional)
1.191     harris41 13196: 
                   13197: =item *
                   13198: 
1.702     albertel 13199: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13200: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13201: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13202: 
1.702     albertel 13203: $range should be either an integer '100' (give me the first 100
                   13204:                                            matching records)
                   13205:               or be  two integers sperated by a - with no spaces
                   13206:                  '30-50' (give me the 30th through the 50th matching
                   13207:                           records)
1.449     matthew  13208: =item *
                   13209: 
                   13210: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13211: $store can be a scalar, an array reference, or if the amount to be 
                   13212: incremented is > 1, a hash reference.
                   13213: 
                   13214: ($udom and $uname are optional)
1.191     harris41 13215: 
                   13216: =item *
                   13217: 
1.243     albertel 13218: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13219: ($udom and $uname are optional)
1.191     harris41 13220: 
                   13221: =item *
                   13222: 
1.243     albertel 13223: cput($namespace,$storehash,$udom,$uname) : critical put
                   13224: ($udom and $uname are optional)
1.191     harris41 13225: 
                   13226: =item *
                   13227: 
1.748     albertel 13228: newput($namespace,$storehash,$udom,$uname) :
                   13229: 
                   13230: Attempts to store the items in the $storehash, but only if they don't
                   13231: currently exist, if this succeeds you can be certain that you have 
                   13232: successfully created a new key value pair in the $namespace db.
                   13233: 
                   13234: 
                   13235: Args:
                   13236:  $namespace: name of database to store values to
                   13237:  $storehash: hashref to store to the db
                   13238:  $udom: (optional) domain of user containing the db
                   13239:  $uname: (optional) name of user caontaining the db
                   13240: 
                   13241: Returns:
                   13242:  'ok' -> succeeded in storing all keys of $storehash
                   13243:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13244:                         least <key> already existed in the db (other
                   13245:                         requested keys may also already exist)
1.967     bisitz   13246:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13247:  'con_lost' -> unable to contact request server
                   13248:  'refused' -> action was not allowed by remote machine
                   13249: 
                   13250: 
                   13251: =item *
                   13252: 
1.243     albertel 13253: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13254: reference filled in from namesp (encrypts the return communication)
                   13255: ($udom and $uname are optional)
1.191     harris41 13256: 
                   13257: =item *
                   13258: 
1.243     albertel 13259: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13260: critical subroutine
                   13261: 
1.806     raeburn  13262: =item *
                   13263: 
1.860     raeburn  13264: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13265: array reference filled in from namespace found in domain level on either
                   13266: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13267: 
                   13268: =item *
                   13269: 
1.860     raeburn  13270: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13271: domain level either on specified domain server ($uhome) or primary domain 
                   13272: server ($udom and $uhome are optional)
1.806     raeburn  13273: 
1.943     raeburn  13274: =item * 
                   13275: 
1.1240    raeburn  13276: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13277: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13278: the target domain.
                   13279: 
                   13280: May also include additional key => value pairs for the following groups:
                   13281: 
                   13282: =over
                   13283: 
                   13284: =item
                   13285: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13286: 
                   13287: =over
                   13288: 
                   13289: =item defaultquota, authorquota
                   13290: 
                   13291: =back
                   13292: 
                   13293: =item
                   13294: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13295: portfolio for users).
                   13296: 
                   13297: =over
                   13298: 
                   13299: =item
                   13300: aboutme, blog, webdav, portfolio
                   13301: 
                   13302: =back
                   13303: 
                   13304: =item
                   13305: requestcourses: ability to request courses, and how requests are processed.
                   13306: 
                   13307: =over
                   13308: 
                   13309: =item
1.1246    raeburn  13310: official, unofficial, community, textbook
1.1240    raeburn  13311: 
                   13312: =back
                   13313: 
                   13314: =item
                   13315: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13316: 
                   13317: =over
                   13318: 
                   13319: =item
                   13320: inststatustypes, inststatusorder
                   13321: 
                   13322: =back
                   13323: 
                   13324: =item
                   13325: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13326: for course's uploaded content.
                   13327: 
                   13328: =over
                   13329: 
                   13330: =item
1.1246    raeburn  13331: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   13332: communityquota, textbookquota
1.1240    raeburn  13333: 
                   13334: =back
                   13335: 
                   13336: =item
                   13337: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13338: on your servers.
                   13339: 
                   13340: =over
                   13341: 
                   13342: =item 
                   13343: remotesessions, hostedsessions
                   13344: 
                   13345: =back
                   13346: 
                   13347: =back
                   13348: 
                   13349: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13350: utility to create a configuration.db file on a domain's primary library server 
                   13351: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13352: -- corresponding values are authentication type (internal, krb4, krb5,
                   13353: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13354: will be available. Values are retrieved from cache (if current), unless the
                   13355: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13356: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13357: 
                   13358: Typical usage:
1.943     raeburn  13359: 
1.1240    raeburn  13360: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13361: 
1.243     albertel 13362: =back
                   13363: 
                   13364: =head2 Network Status Functions
                   13365: 
                   13366: =over 4
1.191     harris41 13367: 
                   13368: =item *
                   13369: 
1.1137    raeburn  13370: dirlist() : return directory list based on URI (first arg).
                   13371: 
                   13372: Inputs: 1 required, 5 optional.
                   13373: 
                   13374: =over
                   13375: 
                   13376: =item 
                   13377: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13378: 
                   13379: =item
                   13380: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13381: 
                   13382: =item
                   13383: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13384: 
                   13385: =item
                   13386: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13387: 
                   13388: =item
                   13389: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13390: 
                   13391: =item 
                   13392: $alternateRoot - path to prepend in place of path from $uri.
                   13393: 
                   13394: =back
                   13395: 
                   13396: Returns: Array of up to two items.
                   13397: 
                   13398: =over
                   13399: 
                   13400: a reference to an array of files/subdirectories
                   13401: 
                   13402: =over
                   13403: 
                   13404: Each element in the array of files/subdirectories is a & separated list of
                   13405: item name and the result of running stat on the item.  If dirlist was requested
                   13406: for a file instead of a directory, the item name will be ''. For a directory 
                   13407: listing, if the item is a metadata file, the element will end &N&M 
                   13408: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13409: default copyright set (1).  
                   13410: 
                   13411: =back
                   13412: 
                   13413: a scalar containing error condition (if encountered).
                   13414: 
                   13415: =over
                   13416: 
                   13417: =item 
                   13418: no_host (no homeserver identified for $username:$domain).
                   13419: 
                   13420: =item 
                   13421: no_such_host (server contacted for listing not identified as valid host).
                   13422: 
                   13423: =item 
                   13424: con_lost (connection to remote server failed).
                   13425: 
                   13426: =item 
                   13427: refused (invalid $username:$domain received on lond side).
                   13428: 
                   13429: =item 
                   13430: no_such_dir (directory at specified path on lond side does not exist). 
                   13431: 
                   13432: =item 
                   13433: empty (directory at specified path on lond side is empty).
                   13434: 
                   13435: =over
                   13436: 
                   13437: This is currently not encountered because the &ls3, &ls2, 
                   13438: &ls (_handler) routines on the lond side do not filter out
                   13439: . and .. from a directory listing. 
                   13440: 
                   13441: =back
                   13442: 
                   13443: =back
                   13444: 
                   13445: =back
1.191     harris41 13446: 
                   13447: =item *
                   13448: 
1.243     albertel 13449: spareserver() : find server with least workload from spare.tab
                   13450: 
1.986     foxr     13451: 
                   13452: =item *
                   13453: 
                   13454: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13455: if there is no corresponding loncapa host.
                   13456: 
1.243     albertel 13457: =back
                   13458: 
1.986     foxr     13459: 
1.243     albertel 13460: =head2 Apache Request
                   13461: 
                   13462: =over 4
1.191     harris41 13463: 
                   13464: =item *
                   13465: 
1.243     albertel 13466: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13467: localhost, posts hash
                   13468: 
                   13469: =back
                   13470: 
                   13471: =head2 Data to String to Data
                   13472: 
                   13473: =over 4
1.191     harris41 13474: 
                   13475: =item *
                   13476: 
1.243     albertel 13477: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13478: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13479: 
                   13480: =item *
                   13481: 
1.243     albertel 13482: hashref2str($hashref) : convert a hashref into a string complete with
                   13483: escaping and '=' and '&' separators, supports elements that are
                   13484: arrayrefs and hashrefs
1.191     harris41 13485: 
                   13486: =item *
                   13487: 
1.243     albertel 13488: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13489: with escaping and '&' separators, supports elements that are arrayrefs
                   13490: and hashrefs
1.191     harris41 13491: 
                   13492: =item *
                   13493: 
1.243     albertel 13494: str2hash($string) : convert string to hash using unescaping and
                   13495: splitting on '=' and '&', supports elements that are arrayrefs and
                   13496: hashrefs
1.191     harris41 13497: 
                   13498: =item *
                   13499: 
1.243     albertel 13500: str2array($string) : convert string to hash using unescaping and
                   13501: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13502: 
                   13503: =back
                   13504: 
                   13505: =head2 Logging Routines
                   13506: 
                   13507: 
                   13508: These routines allow one to make log messages in the lonnet.log and
                   13509: lonnet.perm logfiles.
1.191     harris41 13510: 
1.1119    foxr     13511: =over 4
                   13512: 
1.191     harris41 13513: =item *
                   13514: 
1.243     albertel 13515: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13516: 
                   13517: =item *
                   13518: 
1.243     albertel 13519: logthis() : append message to the normal lonnet.log file, it gets
                   13520: preiodically rolled over and deleted.
1.191     harris41 13521: 
                   13522: =item *
                   13523: 
1.243     albertel 13524: logperm() : append a permanent message to lonnet.perm.log, this log
                   13525: file never gets deleted by any automated portion of the system, only
                   13526: messages of critical importance should go in here.
                   13527: 
1.1119    foxr     13528: 
1.243     albertel 13529: =back
                   13530: 
                   13531: =head2 General File Helper Routines
                   13532: 
                   13533: =over 4
1.191     harris41 13534: 
                   13535: =item *
                   13536: 
1.481     raeburn  13537: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13538: (a) files in /uploaded
                   13539:   (i) If a local copy of the file exists - 
                   13540:       compares modification date of local copy with last-modified date for 
                   13541:       definitive version stored on home server for course. If local copy is 
                   13542:       stale, requests a new version from the home server and stores it. 
                   13543:       If the original has been removed from the home server, then local copy 
                   13544:       is unlinked.
                   13545:   (ii) If local copy does not exist -
                   13546:       requests the file from the home server and stores it. 
                   13547:   
                   13548:   If $caller is 'uploadrep':  
                   13549:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13550:     for request for files originally uploaded via DOCS. 
                   13551:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13552:   
                   13553:   Otherwise:
                   13554:      This indicates a call from the content generation phase of the request.
                   13555:      -  returns the entire contents of the file or -1.
                   13556:      
                   13557: (b) files in /res
                   13558:    - returns the entire contents of a file or -1; 
                   13559:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13560: 
1.712     albertel 13561: 
                   13562: =item *
                   13563: 
                   13564: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13565:                   reference
                   13566: 
                   13567: returns either a stat() list of data about the file or an empty list
                   13568: if the file doesn't exist or couldn't find out about it (connection
                   13569: problems or user unknown)
                   13570: 
1.191     harris41 13571: =item *
                   13572: 
1.243     albertel 13573: filelocation($dir,$file) : returns file system location of a file
                   13574: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13575: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13576: and a file of ../bob will become /a/bob)
1.191     harris41 13577: 
                   13578: =item *
                   13579: 
                   13580: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13581: filelocation except for hrefs
                   13582: 
                   13583: =item *
                   13584: 
                   13585: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13586: 
1.243     albertel 13587: =back
                   13588: 
1.608     albertel 13589: =head2 Usererfile file routines (/uploaded*)
                   13590: 
                   13591: =over 4
                   13592: 
                   13593: =item *
                   13594: 
                   13595: userfileupload(): main rotine for putting a file in a user or course's
                   13596:                   filespace, arguments are,
                   13597: 
1.620     albertel 13598:  formname - required - this is the name of the element in $env where the
1.608     albertel 13599:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13600:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13601:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13602:  context - if coursedoc, store the file in the course of the active role
                   13603:              of the current user; 
                   13604:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13605:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13606:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13607:          if undefined, it will be placed in "unknown"
                   13608: 
                   13609:  (This routine calls clean_filename() to remove any dangerous
                   13610:  characters from the filename, and then calls finuserfileupload() to
                   13611:  complete the transaction)
                   13612: 
                   13613:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13614:  and /adm/notfound.html if unsuccessful
                   13615: 
                   13616: =item *
                   13617: 
                   13618: clean_filename(): routine for cleaing a filename up for storage in
                   13619:                  userfile space, argument is:
                   13620: 
                   13621:  filename - proposed filename
                   13622: 
                   13623: returns: the new clean filename
                   13624: 
                   13625: =item *
                   13626: 
1.1090    raeburn  13627: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13628: userspace, probably shouldn't be called directly
                   13629: 
                   13630:   docuname: username or courseid of destination for the file
                   13631:   docudom: domain of user/course of destination for the file
                   13632:   formname: same as for userfileupload()
1.1090    raeburn  13633:   fname: filename (including subdirectories) for the file
                   13634:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13635:   allfiles: reference to hash used to store objects found by parser
                   13636:   codebase: reference to hash used for codebases of java objects found by parser
                   13637:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13638:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13639:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13640:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13641:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13642:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13643:   mimetype: reference to scalar to accommodate mime type determined
                   13644:             from File::MMagic if $parser = parse.
1.608     albertel 13645: 
                   13646:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13647:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13648:  was 'overwrite').
                   13649:  
1.608     albertel 13650: 
                   13651: =item *
                   13652: 
                   13653: renameuserfile(): renames an existing userfile to a new name
                   13654: 
                   13655:   Args:
                   13656:    docuname: username or courseid of destination for the file
                   13657:    docudom: domain of user/course of destination for the file
                   13658:    old: current file name (including any subdirs under userfiles)
                   13659:    new: desired file name (including any subdirs under userfiles)
                   13660: 
                   13661: =item *
                   13662: 
                   13663: mkdiruserfile(): creates a directory is a userfiles dir
                   13664: 
                   13665:   Args:
                   13666:    docuname: username or courseid of destination for the file
                   13667:    docudom: domain of user/course of destination for the file
                   13668:    dir: dir to create (including any subdirs under userfiles)
                   13669: 
                   13670: =item *
                   13671: 
                   13672: removeuserfile(): removes a file that exists in userfiles
                   13673: 
                   13674:   Args:
                   13675:    docuname: username or courseid of destination for the file
                   13676:    docudom: domain of user/course of destination for the file
                   13677:    fname: filname to delete (including any subdirs under userfiles)
                   13678: 
                   13679: =item *
                   13680: 
                   13681: removeuploadedurl(): convience function for removeuserfile()
                   13682: 
                   13683:   Args:
                   13684:    url:  a full /uploaded/... url to delete
                   13685: 
1.747     albertel 13686: =item * 
                   13687: 
                   13688: get_portfile_permissions():
                   13689:   Args:
                   13690:     domain: domain of user or course contain the portfolio files
                   13691:     user: name of user or num of course contain the portfolio files
                   13692:   Returns:
                   13693:     hashref of a dump of the proper file_permissions.db
                   13694:    
                   13695: 
                   13696: =item * 
                   13697: 
                   13698: get_access_controls():
                   13699: 
                   13700: Args:
                   13701:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13702:   group: (optional) the group you want the files associated with
                   13703:   file: (optional) the file you want access info on
                   13704: 
                   13705: Returns:
1.749     raeburn  13706:     a hash (keys are file names) of hashes containing
                   13707:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13708:         values are XML containing access control settings (see below) 
1.747     albertel 13709: 
                   13710: Internal notes:
                   13711: 
1.749     raeburn  13712:  access controls are stored in file_permissions.db as key=value pairs.
                   13713:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13714:         where scope -> public,guest,course,group,domains or users.
                   13715:               end -> UNIX time for end of access (0 -> no end date)
                   13716:               start -> UNIX time for start of access
                   13717: 
                   13718:     value -> XML description of access control
                   13719:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13720:             <start></start>
                   13721:             <end></end>
                   13722: 
                   13723:             <password></password>  for scope type = guest
                   13724: 
                   13725:             <domain></domain>     for scope type = course or group
                   13726:             <number></number>
                   13727:             <roles id="">
                   13728:              <role></role>
                   13729:              <access></access>
                   13730:              <section></section>
                   13731:              <group></group>
                   13732:             </roles>
                   13733: 
                   13734:             <dom></dom>         for scope type = domains
                   13735: 
                   13736:             <users>             for scope type = users
                   13737:              <user>
                   13738:               <uname></uname>
                   13739:               <udom></udom>
                   13740:              </user>
                   13741:             </users>
                   13742:            </scope> 
                   13743:               
                   13744:  Access data is also aggregated for each file in an additional key=value pair:
                   13745:  key -> path to file/file_name\0accesscontrol 
                   13746:  value -> reference to hash
                   13747:           hash contains key = value pairs
                   13748:           where key = uniqueID:scope_end_start
                   13749:                 value = UNIX time record was last updated
                   13750: 
                   13751:           Used to improve speed of look-ups of access controls for each file.  
                   13752:  
                   13753:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13754: 
1.1198    raeburn  13755: =item *
                   13756: 
1.749     raeburn  13757: modify_access_controls():
                   13758: 
                   13759: Modifies access controls for a portfolio file
                   13760: Args
                   13761: 1. file name
                   13762: 2. reference to hash of required changes,
                   13763: 3. domain
                   13764: 4. username
                   13765:   where domain,username are the domain of the portfolio owner 
                   13766:   (either a user or a course) 
                   13767: 
                   13768: Returns:
                   13769: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13770: 2. result of deletions ('ok' or 'error', with error message).
                   13771: 3. reference to hash of any new or updated access controls.
                   13772: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13773:    key = integer (inbound ID)
1.1198    raeburn  13774:    value = uniqueID
                   13775: 
                   13776: =item *
                   13777: 
                   13778: get_timebased_id():
                   13779: 
                   13780: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   13781: course via the Course Editor (e.g., folders, composite pages, 
                   13782: group bulletin boards).
                   13783: 
                   13784: Args: (first three required; six others optional)
                   13785: 
                   13786: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13787:    docssequence, or name of group
                   13788: 
                   13789: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13790:    e.g., num, boardids
                   13791: 
                   13792: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   13793:    file will be named nohist_namespace.db
                   13794: 
                   13795: 4. cdom: domain of course; default is current course domain from %env
                   13796: 
                   13797: 5. cnum: course number; default is current course number from %env
                   13798: 
                   13799: 6. idtype: set to concat if an additional digit is to be appended to the 
                   13800:    unix timestamp to form the suffix, if the plain timestamp is already
                   13801:    in use.  Default is to not do this, but simply increment the unix 
                   13802:    timestamp by 1 until a unique key is obtained.
                   13803: 
                   13804: 7. who: holder of locking key; defaults to user:domain for user.
                   13805: 
                   13806: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   13807:    retrying); default is 3.
                   13808: 
                   13809: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   13810: 
                   13811: Returns:
                   13812: 
                   13813: 1. suffix obtained (numeric)
                   13814: 
                   13815: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13816: 
                   13817: 3. error: contains (localized) error message if an error occurred.
                   13818: 
1.747     albertel 13819: 
1.608     albertel 13820: =back
                   13821: 
1.243     albertel 13822: =head2 HTTP Helper Routines
                   13823: 
                   13824: =over 4
                   13825: 
1.191     harris41 13826: =item *
                   13827: 
                   13828: escape() : unpack non-word characters into CGI-compatible hex codes
                   13829: 
                   13830: =item *
                   13831: 
                   13832: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13833: 
1.243     albertel 13834: =back
                   13835: 
                   13836: =head1 PRIVATE SUBROUTINES
                   13837: 
                   13838: =head2 Underlying communication routines (Shouldn't call)
                   13839: 
                   13840: =over 4
                   13841: 
                   13842: =item *
                   13843: 
                   13844: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13845: 
                   13846: =item *
                   13847: 
                   13848: reply() : uses subreply to send a message to remote machine, logs all failures
                   13849: 
                   13850: =item *
                   13851: 
                   13852: critical() : passes a critical message to another server; if cannot
                   13853: get through then place message in connection buffer directory and
                   13854: returns con_delayed, if incapable of saving message, returns
                   13855: con_failed
                   13856: 
                   13857: =item *
                   13858: 
                   13859: reconlonc() : tries to reconnect lonc client processes.
                   13860: 
                   13861: =back
                   13862: 
                   13863: =head2 Resource Access Logging
                   13864: 
                   13865: =over 4
                   13866: 
                   13867: =item *
                   13868: 
                   13869: flushcourselogs() : flush (save) buffer logs and access logs
                   13870: 
                   13871: =item *
                   13872: 
                   13873: courselog($what) : save message for course in hash
                   13874: 
                   13875: =item *
                   13876: 
                   13877: courseacclog($what) : save message for course using &courselog().  Perform
                   13878: special processing for specific resource types (problems, exams, quizzes, etc).
                   13879: 
1.191     harris41 13880: =item *
                   13881: 
                   13882: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13883: as a PerlChildExitHandler
1.243     albertel 13884: 
                   13885: =back
                   13886: 
                   13887: =head2 Other
                   13888: 
                   13889: =over 4
                   13890: 
                   13891: =item *
                   13892: 
                   13893: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13894: 
                   13895: =back
                   13896: 
                   13897: =cut
1.877     foxr     13898: 

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