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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1311  ! raeburn     4: # $Id: lonnet.pm,v 1.1310 2016/05/30 04:48:23 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.1289    damieng    95: use Time::HiRes qw( sleep 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.1288    damieng   108: my $max_connection_retries = 20;     # 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.
1.1289    damieng   378: 	sleep(0.1);
1.549     foxr      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.1289    damieng   396:         sleep(0.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:     if ($lonid) {
1.1295    raeburn   426:         my $hostname = &hostname($lonid);
1.891     albertel  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.1295    raeburn   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') {
1.1295    raeburn   472: 	&reconlonc($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:             }
1.1288    damieng   489:             sleep 1;
1.1       albertel  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'} }) {
1.1279    raeburn   852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    853:                                              $try_server));
1.1123    raeburn   854: 	        ($spare_server, $lowest_load) =
                    855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:             }
1.1083    raeburn   857:         }
1.784     albertel  858: 
1.1123    raeburn   859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    860: 
                    861:         if (!$found_server) {
                    862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   864:                     next unless (&spare_can_host($udom,$uint_dom,
                    865:                                                  $remotesessions,$try_server));
1.1123    raeburn   866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
1.1253    raeburn   889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    890: 
                    891:     if ($required) {
                    892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    895:         if (($major eq '' && $minor eq '') ||
                    896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    897:             return ($spare_server,$lowest_load);
                    898:         }
                    899:     }
1.784     albertel  900: 
                    901:     my $loadans     = &reply('load',    $try_server);
                    902:     my $userloadans = &reply('userload',$try_server);
                    903: 
                    904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  906:     }
                    907: 
                    908:     my $load;
                    909:     if ($loadans =~ /\d/) {
                    910: 	if ($userloadans =~ /\d/) {
                    911: 	    #both are numbers, pick the bigger one
                    912: 	    $load = ($loadans > $userloadans) ? $loadans 
                    913: 		                              : $userloadans;
1.411     albertel  914: 	} else {
1.784     albertel  915: 	    $load = $loadans;
1.411     albertel  916: 	}
1.784     albertel  917:     } else {
                    918: 	$load = $userloadans;
                    919:     }
                    920: 
                    921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    922: 	$spare_server = $try_server;
                    923: 	$lowest_load  = $load;
1.370     albertel  924:     }
1.784     albertel  925:     return ($spare_server,$lowest_load);
1.202     matthew   926: }
1.914     albertel  927: 
                    928: # --------------------------- ask offload servers if user already has a session
                    929: sub find_existing_session {
                    930:     my ($udom,$uname) = @_;
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
                    938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    941:             }
                    942:         }
1.914     albertel  943:     }
                    944:     return;
                    945: }
                    946: 
                    947: # -------------------------------- ask if server already has a session for user
                    948: sub has_user_session {
                    949:     my ($lonid,$udom,$uname) = @_;
                    950:     my $result = &reply(join(':','userhassession',
                    951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    952:     return 1 if ($result eq 'ok');
                    953: 
                    954:     return 0;
                    955: }
                    956: 
1.1076    raeburn   957: # --------- determine least loaded server in a user's domain which allows login
                    958: 
                    959: sub choose_server {
1.1259    raeburn   960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   962:     my %servers = &get_servers($udom);
1.1076    raeburn   963:     my $lowest_load = 30000;
1.1259    raeburn   964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    965:     if ($skiploadbal) {
                    966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    967:         unless (defined($cached)) {
                    968:             my $cachetime = 60*60*24;
                    969:             my %domconfig =
                    970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    973:                                            $cachetime);
                    974:             }
                    975:         }
                    976:     }
1.1076    raeburn   977:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn   978:         if ($skiploadbal) {
                    979:             if (ref($balancers) eq 'HASH') {
                    980:                 next if (exists($balancers->{$lonhost}));
                    981:             }
                    982:         }   
1.1115    raeburn   983:         my $loginvia;
                    984:         if ($checkloginvia) {
                    985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   986:             if ($loginvia) {
                    987:                 my ($server,$path) = split(/:/,$loginvia);
                    988:                 ($login_host, $lowest_load) =
1.1253    raeburn   989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   990:                 if ($login_host eq $server) {
                    991:                     $portal_path = $path;
1.1151    raeburn   992:                     $isredirect = 1;
1.1116    raeburn   993:                 }
                    994:             } else {
                    995:                 ($login_host, $lowest_load) =
1.1253    raeburn   996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $lonhost) {
                    998:                     $portal_path = '';
1.1151    raeburn   999:                     $isredirect = ''; 
1.1116    raeburn  1000:                 }
                   1001:             }
                   1002:         } else {
1.1076    raeburn  1003:             ($login_host, $lowest_load) =
1.1253    raeburn  1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1005:         }
                   1006:     }
                   1007:     if ($login_host ne '') {
1.1116    raeburn  1008:         $hostname = &hostname($login_host);
1.1076    raeburn  1009:     }
1.1151    raeburn  1010:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1011: }
                   1012: 
1.202     matthew  1013: # --------------------------------------------- Try to change a user's password
                   1014: 
                   1015: sub changepass {
1.799     raeburn  1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1017:     $currentpass = &escape($currentpass);
                   1018:     $newpass     = &escape($newpass);
1.1030    raeburn  1019:     my $lonhost = $perlvar{'lonHostID'};
                   1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1021: 		       $server);
                   1022:     if (! $answer) {
                   1023: 	&logthis("No reply on password change request to $server ".
                   1024: 		 "by $uname in domain $udom.");
                   1025:     } elsif ($answer =~ "^ok") {
                   1026:         &logthis("$uname in $udom successfully changed their password ".
                   1027: 		 "on $server.");
                   1028:     } elsif ($answer =~ "^pwchange_failure") {
                   1029: 	&logthis("$uname in $udom was unable to change their password ".
                   1030: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1031: 		 "or pwchange");
                   1032:     } elsif ($answer =~ "^non_authorized") {
                   1033:         &logthis("$uname in $udom did not get their password correct when ".
                   1034: 		 "attempting to change it on $server.");
                   1035:     } elsif ($answer =~ "^auth_mode_error") {
                   1036:         &logthis("$uname in $udom attempted to change their password despite ".
                   1037: 		 "not being locally or internally authenticated on $server.");
                   1038:     } elsif ($answer =~ "^unknown_user") {
                   1039:         &logthis("$uname in $udom attempted to change their password ".
                   1040: 		 "on $server but were unable to because $server is not ".
                   1041: 		 "their home server.");
                   1042:     } elsif ($answer =~ "^refused") {
                   1043: 	&logthis("$server refused to change $uname in $udom password because ".
                   1044: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1045:     } elsif ($answer =~ "invalid_client") {
                   1046:         &logthis("$server refused to change $uname in $udom password because ".
                   1047:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1048:     }
                   1049:     return $answer;
1.1       albertel 1050: }
                   1051: 
1.169     harris41 1052: # ----------------------- Try to determine user's current authentication scheme
                   1053: 
                   1054: sub queryauthenticate {
                   1055:     my ($uname,$udom)=@_;
1.456     albertel 1056:     my $uhome=&homeserver($uname,$udom);
                   1057:     if (!$uhome) {
                   1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1059: 	return 'no_host';
                   1060:     }
                   1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1064:     }
1.456     albertel 1065:     return $answer;
1.169     harris41 1066: }
                   1067: 
1.1       albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1069: 
1.1       albertel 1070: sub authenticate {
1.1073    raeburn  1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1072:     $upass=&escape($upass);
                   1073:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1074:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1075:     my $newhome;
1.836     www      1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1077: # Maybe the machine was offline and only re-appeared again recently?
                   1078:         &reconlonc();
                   1079: # One more
1.952     raeburn  1080: 	$uhome=&homeserver($uname,$udom,1);
                   1081:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1082:             if (defined(&domain($udom,'primary'))) {
                   1083:                 $newhome=&domain($udom,'primary');
                   1084:             }
                   1085:             if ($newhome ne '') {
                   1086:                 $uhome = $newhome;
                   1087:             }
                   1088:         }
1.836     www      1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1091: 	    return 'no_host';
                   1092:         }
1.1       albertel 1093:     }
1.1073    raeburn  1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1095:     if ($answer eq 'authorized') {
1.952     raeburn  1096:         if ($newhome) {
                   1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1098:             return 'no_account_on_host'; 
                   1099:         } else {
                   1100:             &logthis("User $uname at $udom authorized by $uhome");
                   1101:             return $uhome;
                   1102:         }
1.471     albertel 1103:     }
                   1104:     if ($answer eq 'non_authorized') {
                   1105: 	&logthis("User $uname at $udom rejected by $uhome");
                   1106: 	return 'no_host'; 
1.9       www      1107:     }
1.471     albertel 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1109:     return 'no_host';
                   1110: }
                   1111: 
1.1073    raeburn  1112: sub can_host_session {
1.1074    raeburn  1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1114:     my $canhost = 1;
1.1074    raeburn  1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1116:     if (ref($remotesessions) eq 'HASH') {
                   1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1119:                 $canhost = 0;
                   1120:             } else {
                   1121:                 $canhost = 1;
                   1122:             }
                   1123:         }
                   1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 1;
                   1127:             } else {
                   1128:                 $canhost = 0;
                   1129:             }
                   1130:         }
                   1131:         if ($canhost) {
                   1132:             if ($remotesessions->{'version'} ne '') {
                   1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1134:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1136:                         my $major = $1;
                   1137:                         my $minor = $2;
                   1138:                         if (($major < $reqmajor ) ||
                   1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1140:                             $canhost = 0;
                   1141:                         }
                   1142:                     } else {
                   1143:                         $canhost = 0;
                   1144:                     }
                   1145:                 }
                   1146:             }
                   1147:         }
                   1148:     }
                   1149:     if ($canhost) {
                   1150:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1154:                 if (($uint_dom ne '') && 
                   1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1156:                     $canhost = 0;
                   1157:                 } else {
                   1158:                     $canhost = 1;
                   1159:                 }
                   1160:             }
                   1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1162:                 if (($uint_dom ne '') && 
                   1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1164:                     $canhost = 1;
                   1165:                 } else {
                   1166:                     $canhost = 0;
                   1167:                 }
                   1168:             }
                   1169:         }
                   1170:     }
                   1171:     return $canhost;
                   1172: }
                   1173: 
1.1083    raeburn  1174: sub spare_can_host {
                   1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1176:     my $canhost=1;
1.1279    raeburn  1177:     my $try_server_hostname = &hostname($try_server);
                   1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1179:     my $serverhomedom = &host_domain($serverhomeID);
                   1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1183:             $canhost = 0;
                   1184:         }
                   1185:     }
                   1186:     if (($canhost) && ($uint_dom)) {
                   1187:         my @intdoms;
                   1188:         my $internet_names = &get_internet_names($try_server);
                   1189:         if (ref($internet_names) eq 'ARRAY') {
                   1190:             @intdoms = @{$internet_names};
                   1191:         }
                   1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1195:                                          $remotesessions,
                   1196:                                          $defdomdefaults{'hostedsessions'});
                   1197:         }
1.1083    raeburn  1198:     }
                   1199:     return $canhost;
                   1200: }
                   1201: 
1.1123    raeburn  1202: sub this_host_spares {
                   1203:     my ($dom) = @_;
1.1126    raeburn  1204:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1205:     my @hosts = &current_machine_ids();
                   1206:     foreach my $lonhost (@hosts) {
                   1207:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1208:             $dom_in_use = $dom;
                   1209:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1210:             last;
                   1211:         }
                   1212:     }
1.1126    raeburn  1213:     if ($dom_in_use ne '') {
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:     }
                   1216:     if (ref($result) ne 'HASH') {
                   1217:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1218:         $dom_in_use = &host_domain($lonhost_in_use);
                   1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1220:         if (ref($result) ne 'HASH') {
                   1221:             $result = \%spareid;
                   1222:         }
                   1223:     }
                   1224:     return $result;
                   1225: }
                   1226: 
                   1227: sub spares_for_offload  {
                   1228:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1230:     if (defined($cached)) {
                   1231:         return $result;
                   1232:     } else {
1.1126    raeburn  1233:         my $cachetime = 60*60*24;
                   1234:         my %domconfig =
                   1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1240:                 }
                   1241:             }
                   1242:         }
                   1243:     }
1.1126    raeburn  1244:     return;
1.1123    raeburn  1245: }
                   1246: 
1.1129    raeburn  1247: sub get_lonbalancer_config {
                   1248:     my ($servers) = @_;
                   1249:     my ($currbalancer,$currtargets);
                   1250:     if (ref($servers) eq 'HASH') {
                   1251:         foreach my $server (keys(%{$servers})) {
                   1252:             my %what = (
                   1253:                          spareid => 1,
                   1254:                          perlvar => 1,
                   1255:                        );
                   1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1257:             if ($result eq 'ok') {
                   1258:                 if (ref($returnhash) eq 'HASH') {
                   1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1261:                             $currbalancer = $server;
                   1262:                             $currtargets = {};
                   1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1266:                                 }
                   1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1269:                                 }
                   1270:                             }
                   1271:                             last;
                   1272:                         }
                   1273:                     }
                   1274:                 }
                   1275:             }
                   1276:         }
                   1277:     }
                   1278:     return ($currbalancer,$currtargets);
                   1279: }
                   1280: 
                   1281: sub check_loadbalancing {
                   1282:     my ($uname,$udom) = @_;
1.1191    raeburn  1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1284:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1285:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1286:     my @hosts = &current_machine_ids();
1.1129    raeburn  1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1290:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1291:     my $domneedscache;
1.1129    raeburn  1292:     my $cachetime = 60*60*24;
                   1293: 
                   1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1295:         $dom_in_use = $udom;
                   1296:         $homeintdom = 1;
                   1297:     } else {
                   1298:         $dom_in_use = $serverhomedom;
                   1299:     }
                   1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1301:     unless (defined($cached)) {
                   1302:         my %domconfig =
                   1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1306:         } else {
                   1307:             $domneedscache = $dom_in_use;
1.1129    raeburn  1308:         }
                   1309:     }
                   1310:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1311:         ($is_balancer,$currtargets,$currrules) = 
                   1312:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1313:         if ($is_balancer) {
                   1314:             if (ref($currrules) eq 'HASH') {
                   1315:                 if ($homeintdom) {
                   1316:                     if ($uname ne '') {
                   1317:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1318:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1319:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1320:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1321:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1322:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1323:                             }
                   1324:                         }
                   1325:                         if ($rule_in_effect eq '') {
                   1326:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1327:                             if ($userenv{'inststatus'} ne '') {
                   1328:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1329:                                 my ($othertitle,$usertypes,$types) =
                   1330:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1331:                                 if (ref($types) eq 'ARRAY') {
                   1332:                                     foreach my $type (@{$types}) {
                   1333:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1334:                                             if (exists($currrules->{$type})) {
                   1335:                                                 $rule_in_effect = $currrules->{$type};
                   1336:                                             }
                   1337:                                         }
                   1338:                                     }
                   1339:                                 }
                   1340:                             } else {
                   1341:                                 if (exists($currrules->{'default'})) {
                   1342:                                     $rule_in_effect = $currrules->{'default'};
                   1343:                                 }
                   1344:                             }
                   1345:                         }
                   1346:                     } else {
                   1347:                         if (exists($currrules->{'default'})) {
                   1348:                             $rule_in_effect = $currrules->{'default'};
                   1349:                         }
                   1350:                     }
                   1351:                 } else {
                   1352:                     if ($currrules->{'_LC_external'} ne '') {
                   1353:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1354:                     }
                   1355:                 }
                   1356:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1357:                                                        $uname,$udom);
                   1358:             }
                   1359:         }
                   1360:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1361:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1362:         unless (defined($cached)) {
                   1363:             my %domconfig =
                   1364:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1365:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1366:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1367:             } else {
                   1368:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1369:             }
                   1370:         }
                   1371:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1372:             ($is_balancer,$currtargets,$currrules) = 
                   1373:                 &check_balancer_result($result,@hosts);
                   1374:             if ($is_balancer) {
1.1129    raeburn  1375:                 if (ref($currrules) eq 'HASH') {
                   1376:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1377:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1378:                     }
                   1379:                 }
                   1380:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1381:                                                        $uname,$udom);
                   1382:             }
                   1383:         } else {
                   1384:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1385:                 $is_balancer = 1;
                   1386:                 $offloadto = &this_host_spares($dom_in_use);
                   1387:             }
1.1307    raeburn  1388:             unless (defined($cached)) {
                   1389:                 $domneedscache = $serverhomedom;
                   1390:             }
1.1129    raeburn  1391:         }
                   1392:     } else {
                   1393:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1394:             $is_balancer = 1;
                   1395:             $offloadto = &this_host_spares($dom_in_use);
                   1396:         }
1.1307    raeburn  1397:         unless (defined($cached)) {
                   1398:             $domneedscache = $serverhomedom;
                   1399:         }
                   1400:     }
                   1401:     if ($domneedscache) {
                   1402:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1403:     }
1.1176    raeburn  1404:     if ($is_balancer) {
                   1405:         my $lowest_load = 30000;
                   1406:         if (ref($offloadto) eq 'HASH') {
                   1407:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1408:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1409:                     ($otherserver,$lowest_load) =
                   1410:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1411:                 }
1.1129    raeburn  1412:             }
1.1176    raeburn  1413:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1414: 
1.1176    raeburn  1415:             if (!$found_server) {
                   1416:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1417:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1418:                         ($otherserver,$lowest_load) =
                   1419:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1420:                     }
                   1421:                 }
                   1422:             }
                   1423:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1424:             if (@{$offloadto} == 1) {
                   1425:                 $otherserver = $offloadto->[0];
                   1426:             } elsif (@{$offloadto} > 1) {
                   1427:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1428:                     ($otherserver,$lowest_load) =
                   1429:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1430:                 }
                   1431:             }
                   1432:         }
1.1176    raeburn  1433:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1434:             $is_balancer = 0;
                   1435:             if ($uname ne '' && $udom ne '') {
                   1436:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1437:                     
                   1438:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1439:                              'user.loadbalcheck.time' => time});
                   1440:                 }
1.1129    raeburn  1441:             }
                   1442:         }
                   1443:     }
                   1444:     return ($is_balancer,$otherserver);
                   1445: }
                   1446: 
1.1191    raeburn  1447: sub check_balancer_result {
                   1448:     my ($result,@hosts) = @_;
                   1449:     my ($is_balancer,$currtargets,$currrules);
                   1450:     if (ref($result) eq 'HASH') {
                   1451:         if ($result->{'lonhost'} ne '') {
                   1452:             my $currbalancer = $result->{'lonhost'};
                   1453:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1454:                 $is_balancer = 1;
                   1455:                 $currtargets = $result->{'targets'};
                   1456:                 $currrules = $result->{'rules'};
                   1457:             }
                   1458:         } else {
                   1459:             foreach my $key (keys(%{$result})) {
                   1460:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1461:                     (ref($result->{$key}) eq 'HASH')) {
                   1462:                     $is_balancer = 1;
                   1463:                     $currrules = $result->{$key}{'rules'};
                   1464:                     $currtargets = $result->{$key}{'targets'};
                   1465:                     last;
                   1466:                 }
                   1467:             }
                   1468:         }
                   1469:     }
                   1470:     return ($is_balancer,$currtargets,$currrules);
                   1471: }
                   1472: 
1.1129    raeburn  1473: sub get_loadbalancer_targets {
                   1474:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1475:     my $offloadto;
1.1175    raeburn  1476:     if ($rule_in_effect eq 'none') {
                   1477:         return [$perlvar{'lonHostID'}];
                   1478:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1479:         $offloadto = $currtargets;
                   1480:     } else {
                   1481:         if ($rule_in_effect eq 'homeserver') {
                   1482:             my $homeserver = &homeserver($uname,$udom);
                   1483:             if ($homeserver ne 'no_host') {
                   1484:                 $offloadto = [$homeserver];
                   1485:             }
                   1486:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1487:             my %domconfig =
                   1488:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1489:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1490:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1491:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1492:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1493:                     }
                   1494:                 }
                   1495:             } else {
1.1178    raeburn  1496:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1497:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1498:                 if (&hostname($remotebalancer) ne '') {
                   1499:                     $offloadto = [$remotebalancer];
                   1500:                 }
                   1501:             }
                   1502:         } elsif (&hostname($rule_in_effect) ne '') {
                   1503:             $offloadto = [$rule_in_effect];
                   1504:         }
                   1505:     }
                   1506:     return $offloadto;
                   1507: }
                   1508: 
1.1127    raeburn  1509: sub internet_dom_servers {
                   1510:     my ($dom) = @_;
                   1511:     my (%uniqservers,%servers);
                   1512:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1513:     my @machinedoms = &machine_domains($primaryserver);
                   1514:     foreach my $mdom (@machinedoms) {
                   1515:         my %currservers = %servers;
                   1516:         my %server = &get_servers($mdom);
                   1517:         %servers = (%currservers,%server);
                   1518:     }
                   1519:     my %by_hostname;
                   1520:     foreach my $id (keys(%servers)) {
                   1521:         push(@{$by_hostname{$servers{$id}}},$id);
                   1522:     }
                   1523:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1524:         if (@{$by_hostname{$hostname}} > 1) {
                   1525:             my $match = 0;
                   1526:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1527:                 if (&host_domain($id) eq $dom) {
                   1528:                     $uniqservers{$id} = $hostname;
                   1529:                     $match = 1;
                   1530:                 }
                   1531:             }
                   1532:             unless ($match) {
                   1533:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1534:             }
                   1535:         } else {
                   1536:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1537:         }
                   1538:     }
                   1539:     return %uniqservers;
                   1540: }
                   1541: 
1.1       albertel 1542: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1543: 
1.599     albertel 1544: my %homecache;
1.1       albertel 1545: sub homeserver {
1.230     stredwic 1546:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1547:     my $index="$uname:$udom";
1.426     albertel 1548: 
1.599     albertel 1549:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1550: 
                   1551:     my %servers = &get_servers($udom,'library');
                   1552:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1553:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1554: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1555: 
                   1556: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1557: 	if ($answer eq 'found') {
                   1558: 	    delete($badServerCache{$tryserver}); 
                   1559: 	    return $homecache{$index}=$tryserver;
                   1560: 	} elsif ($answer eq 'no_host') {
                   1561: 	    $badServerCache{$tryserver}=1;
                   1562: 	}
1.1       albertel 1563:     }    
                   1564:     return 'no_host';
1.70      www      1565: }
                   1566: 
1.1300    raeburn  1567: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1568: 
                   1569: sub idget {
1.1300    raeburn  1570:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1571:     my %returnhash=();
1.1300    raeburn  1572:     my @ids=(); 
                   1573:     if (ref($idsref) eq 'ARRAY') {
                   1574:         @ids = @{$idsref};
                   1575:     } else {
                   1576:         return %returnhash; 
                   1577:     }
                   1578:     if ($namespace eq '') {
                   1579:         $namespace = 'ids';
                   1580:     }
1.70      www      1581:     
1.841     albertel 1582:     my %servers = &get_servers($udom,'library');
                   1583:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1584: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1585: 	if ($namespace eq 'ids') {
                   1586: 	    $idlist=~tr/A-Z/a-z/;
                   1587: 	}
                   1588: 	my $reply;
                   1589: 	if ($namespace eq 'ids') {
                   1590: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1591: 	} else {
                   1592: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1593: 	}
1.841     albertel 1594: 	my @answer=();
                   1595: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1596: 	    @answer=split(/\&/,$reply);
                   1597: 	}                    ;
                   1598: 	my $i;
                   1599: 	for ($i=0;$i<=$#ids;$i++) {
                   1600: 	    if ($answer[$i]) {
1.1299    raeburn  1601: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1602: 	    }
1.841     albertel 1603: 	}
1.1300    raeburn  1604:     }
1.70      www      1605:     return %returnhash;
                   1606: }
                   1607: 
                   1608: # ------------------------------------- Find the IDs behind a list of usernames
                   1609: 
                   1610: sub idrget {
                   1611:     my ($udom,@unames)=@_;
                   1612:     my %returnhash=();
1.800     albertel 1613:     foreach my $uname (@unames) {
                   1614:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1615:     }
1.70      www      1616:     return %returnhash;
                   1617: }
                   1618: 
1.1300    raeburn  1619: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1620: 
                   1621: sub idput {
1.1300    raeburn  1622:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1623:     my %servers=();
1.1300    raeburn  1624:     my %ids=();
                   1625:     my %byid = ();
                   1626:     if (ref($idsref) eq 'HASH') {
                   1627:         %ids=%{$idsref};
                   1628:     }
                   1629:     if ($namespace eq '') {
                   1630:         $namespace = 'ids'; 
                   1631:     }
1.800     albertel 1632:     foreach my $uname (keys(%ids)) {
                   1633: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1634:         if ($uhom eq '') {
                   1635:             $uhom=&homeserver($uname,$udom);
                   1636:         }
1.70      www      1637:         if ($uhom ne 'no_host') {
1.800     albertel 1638:             my $esc_unam=&escape($uname);
1.1300    raeburn  1639:             if ($namespace eq 'ids') {
                   1640:                 my $id=&escape($ids{$uname});
                   1641:                 $id=~tr/A-Z/a-z/;
                   1642:                 my $esc_unam=&escape($uname);
                   1643:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1644:             } else {
1.1300    raeburn  1645:                 my @currids = split(/,/,$ids{$uname});
                   1646:                 foreach my $id (@currids) {
                   1647:                     $byid{$uhom}{$id} .= $uname.',';
                   1648:                 }
                   1649:             }
                   1650:         }
                   1651:     }
                   1652:     if ($namespace eq 'clickers') {
                   1653:         foreach my $server (keys(%byid)) {
                   1654:             if (ref($byid{$server}) eq 'HASH') {
                   1655:                 foreach my $id (keys(%{$byid{$server}})) {
                   1656:                     $byid{$server} =~ s/,$//;
                   1657:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1658:                 }
1.70      www      1659:             }
                   1660:         }
1.191     harris41 1661:     }
1.800     albertel 1662:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1663:         $servers{$server} =~ s/\&$//;
                   1664:         if ($namespace eq 'ids') {     
                   1665:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1666:         } else {
                   1667:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1668:         }
1.191     harris41 1669:     }
1.344     www      1670: }
                   1671: 
1.1300    raeburn  1672: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1673: 
                   1674: sub iddel {
1.1300    raeburn  1675:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1676:     my %result=();
1.1300    raeburn  1677:     my %ids=();
                   1678:     my %byid = ();
                   1679:     if (ref($idshashref) eq 'HASH') {
                   1680:         %ids=%{$idshashref};
                   1681:     } else {
1.1231    raeburn  1682:         return %result;
                   1683:     }
1.1300    raeburn  1684:     if ($namespace eq '') {
                   1685:         $namespace = 'ids';
                   1686:     }
1.1231    raeburn  1687:     my %servers=();
1.1300    raeburn  1688:     while (my ($id,$unamestr) = each(%ids)) {
                   1689:         if ($namespace eq 'ids') {
                   1690:             my $uhom = $uhome;
                   1691:             if ($uhom eq '') { 
                   1692:                 $uhom=&homeserver($unamestr,$udom);
                   1693:             }
                   1694:             if ($uhom ne 'no_host') {
                   1695:                 $servers{$uhom}.='&'.&escape($id);
                   1696:             }
                   1697:          } else {
                   1698:             my @curritems = split(/,/,$ids{$id});
                   1699:             foreach my $uname (@curritems) {
                   1700:                 my $uhom = $uhome;
                   1701:                 if ($uhom eq '') {
                   1702:                     $uhom=&homeserver($uname,$udom);
                   1703:                 }
                   1704:                 if ($uhom ne 'no_host') { 
                   1705:                     $byid{$uhom}{$id} .= $uname.',';
                   1706:                 }
                   1707:             }
1.1231    raeburn  1708:         }
1.1300    raeburn  1709:     }
                   1710:     if ($namespace eq 'clickers') {
                   1711:         foreach my $server (keys(%byid)) {
                   1712:             if (ref($byid{$server}) eq 'HASH') {
                   1713:                 foreach my $id (keys(%{$byid{$server}})) {
                   1714:                     $byid{$server}{$id} =~ s/,$//;
                   1715:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1716:                 }
1.1231    raeburn  1717:             }
                   1718:         }
                   1719:     }
                   1720:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1721:         $servers{$server} =~ s/\&$//;
                   1722:         if ($namespace eq 'ids') {
                   1723:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1724:         } elsif ($namespace eq 'clickers') {
                   1725:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1726:         }
1.1231    raeburn  1727:     }
                   1728:     return %result;
                   1729: }
                   1730: 
1.1300    raeburn  1731: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1732: 
                   1733: sub updateclickers {
                   1734:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1735:     my %clickers;
                   1736:     if (ref($idshashref) eq 'HASH') {
                   1737:         %clickers=%{$idshashref};
                   1738:     } else {
                   1739:         return;
                   1740:     }
                   1741:     my $items='';
                   1742:     foreach my $item (keys(%clickers)) {
                   1743:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1744:     }
                   1745:     $items=~s/\&$//;
                   1746:     my $request = "updateclickers:$udom:$action:$items";
                   1747:     if ($critical) {
                   1748:         return &critical($request,$uhome);
                   1749:     } else {
                   1750:         return &reply($request,$uhome);
                   1751:     }
                   1752: }
                   1753: 
1.1023    raeburn  1754: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1755: sub dump_dom {
1.1165    droeschl 1756:     my ($namespace, $udom, $regexp) = @_;
                   1757: 
                   1758:     $udom ||= $env{'user.domain'};
                   1759: 
                   1760:     return () unless $udom;
                   1761: 
                   1762:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1763: }
                   1764: 
1.1023    raeburn  1765: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1766: 
                   1767: sub get_dom {
1.860     raeburn  1768:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1769:     return if ($udom eq 'public');
1.806     raeburn  1770:     my $items='';
                   1771:     foreach my $item (@$storearr) {
                   1772:         $items.=&escape($item).'&';
                   1773:     }
                   1774:     $items=~s/\&$//;
1.860     raeburn  1775:     if (!$udom) {
                   1776:         $udom=$env{'user.domain'};
1.1267    raeburn  1777:         return if ($udom eq 'public');
1.860     raeburn  1778:         if (defined(&domain($udom,'primary'))) {
                   1779:             $uhome=&domain($udom,'primary');
                   1780:         } else {
1.874     albertel 1781:             undef($uhome);
1.860     raeburn  1782:         }
                   1783:     } else {
                   1784:         if (!$uhome) {
                   1785:             if (defined(&domain($udom,'primary'))) {
                   1786:                 $uhome=&domain($udom,'primary');
                   1787:             }
                   1788:         }
                   1789:     }
                   1790:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1791:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1792:         my %returnhash;
1.875     albertel 1793:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1794:             return %returnhash;
                   1795:         }
1.806     raeburn  1796:         my @pairs=split(/\&/,$rep);
                   1797:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1798:             return @pairs;
                   1799:         }
                   1800:         my $i=0;
                   1801:         foreach my $item (@$storearr) {
                   1802:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1803:             $i++;
                   1804:         }
                   1805:         return %returnhash;
                   1806:     } else {
1.880     banghart 1807:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1808:     }
                   1809: }
                   1810: 
                   1811: # -------------------------------------------- put items in domain db files 
                   1812: 
                   1813: sub put_dom {
1.860     raeburn  1814:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1815:     if (!$udom) {
                   1816:         $udom=$env{'user.domain'};
                   1817:         if (defined(&domain($udom,'primary'))) {
                   1818:             $uhome=&domain($udom,'primary');
                   1819:         } else {
1.874     albertel 1820:             undef($uhome);
1.860     raeburn  1821:         }
                   1822:     } else {
                   1823:         if (!$uhome) {
                   1824:             if (defined(&domain($udom,'primary'))) {
                   1825:                 $uhome=&domain($udom,'primary');
                   1826:             }
                   1827:         }
                   1828:     } 
                   1829:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1830:         my $items='';
                   1831:         foreach my $item (keys(%$storehash)) {
                   1832:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1833:         }
                   1834:         $items=~s/\&$//;
                   1835:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1836:     } else {
1.860     raeburn  1837:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1838:     }
                   1839: }
                   1840: 
1.1023    raeburn  1841: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1842: sub newput_dom {
1.1023    raeburn  1843:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1844:     my $result;
                   1845:     if (!$udom) {
                   1846:         $udom=$env{'user.domain'};
                   1847:     }
1.1023    raeburn  1848:     if ($udom) {
                   1849:         my $uname = &get_domainconfiguser($udom);
                   1850:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1851:     }
                   1852:     return $result;
                   1853: }
                   1854: 
1.1023    raeburn  1855: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1856: sub del_dom {
1.1023    raeburn  1857:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1858:     if (ref($storearr) eq 'ARRAY') {
                   1859:         if (!$udom) {
                   1860:             $udom=$env{'user.domain'};
                   1861:         }
1.1023    raeburn  1862:         if ($udom) {
                   1863:             my $uname = &get_domainconfiguser($udom); 
                   1864:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1865:         }
                   1866:     }
                   1867: }
                   1868: 
1.1023    raeburn  1869: # ----------------------------------construct domainconfig user for a domain 
                   1870: sub get_domainconfiguser {
                   1871:     my ($udom) = @_;
                   1872:     return $udom.'-domainconfig';
                   1873: }
                   1874: 
1.837     raeburn  1875: sub retrieve_inst_usertypes {
                   1876:     my ($udom) = @_;
                   1877:     my (%returnhash,@order);
1.989     raeburn  1878:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1879:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1880:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1881:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1882:     } else {
                   1883:         if (defined(&domain($udom,'primary'))) {
                   1884:             my $uhome=&domain($udom,'primary');
                   1885:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1886:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1887:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1888:                 return (\%returnhash,\@order);
                   1889:             }
                   1890:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1891:             my @pairs=split(/\&/,$hashitems);
                   1892:             foreach my $item (@pairs) {
                   1893:                 my ($key,$value)=split(/=/,$item,2);
                   1894:                 $key = &unescape($key);
                   1895:                 next if ($key =~ /^error: 2 /);
                   1896:                 $returnhash{$key}=&thaw_unescape($value);
                   1897:             }
                   1898:             my @esc_order = split(/\&/,$orderitems);
                   1899:             foreach my $item (@esc_order) {
                   1900:                 push(@order,&unescape($item));
                   1901:             }
                   1902:         } else {
1.1256    raeburn  1903:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1904:         }
1.1256    raeburn  1905:         return (\%returnhash,\@order);
1.837     raeburn  1906:     }
                   1907: }
                   1908: 
1.868     raeburn  1909: sub is_domainimage {
                   1910:     my ($url) = @_;
1.1306    raeburn  1911:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1912:         if (&domain($1) ne '') {
                   1913:             return '1';
                   1914:         }
                   1915:     }
                   1916:     return;
                   1917: }
                   1918: 
1.899     raeburn  1919: sub inst_directory_query {
                   1920:     my ($srch) = @_;
                   1921:     my $udom = $srch->{'srchdomain'};
                   1922:     my %results;
                   1923:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1924:     my $outcome;
1.899     raeburn  1925:     if ($homeserver ne '') {
1.904     albertel 1926: 	my $queryid=&reply("querysend:instdirsearch:".
                   1927: 			   &escape($srch->{'srchby'}).':'.
                   1928: 			   &escape($srch->{'srchterm'}).':'.
                   1929: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1930: 	my $host=&hostname($homeserver);
                   1931: 	if ($queryid !~/^\Q$host\E\_/) {
                   1932: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1933: 	    return;
                   1934: 	}
                   1935: 	my $response = &get_query_reply($queryid);
                   1936: 	my $maxtries = 5;
                   1937: 	my $tries = 1;
                   1938: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1939: 	    $response = &get_query_reply($queryid);
                   1940: 	    $tries ++;
                   1941: 	}
                   1942: 
                   1943:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1944:             if ($response eq 'unavailable') {
                   1945:                 $outcome = $response;
                   1946:             } else {
                   1947:                 $outcome = 'ok';
                   1948:                 my @matches = split(/\n/,$response);
                   1949:                 foreach my $match (@matches) {
                   1950:                     my ($key,$value) = split(/=/,$match);
                   1951:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1952:                 }
1.899     raeburn  1953:             }
                   1954:         }
                   1955:     }
1.909     raeburn  1956:     return ($outcome,%results);
1.899     raeburn  1957: }
                   1958: 
                   1959: sub usersearch {
                   1960:     my ($srch) = @_;
                   1961:     my $dom = $srch->{'srchdomain'};
                   1962:     my %results;
                   1963:     my %libserv = &all_library();
                   1964:     my $query = 'usersearch';
                   1965:     foreach my $tryserver (keys(%libserv)) {
                   1966:         if (&host_domain($tryserver) eq $dom) {
                   1967:             my $host=&hostname($tryserver);
                   1968:             my $queryid=
1.911     raeburn  1969:                 &reply("querysend:".&escape($query).':'.
                   1970:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1971:                        &escape($srch->{'srchtype'}).':'.
                   1972:                        &escape($srch->{'srchterm'}),$tryserver);
                   1973:             if ($queryid !~/^\Q$host\E\_/) {
                   1974:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1975:                 next;
1.899     raeburn  1976:             }
                   1977:             my $reply = &get_query_reply($queryid);
                   1978:             my $maxtries = 1;
                   1979:             my $tries = 1;
                   1980:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1981:                 $reply = &get_query_reply($queryid);
                   1982:                 $tries ++;
                   1983:             }
                   1984:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1985:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1986:             } else {
1.911     raeburn  1987:                 my @matches;
                   1988:                 if ($reply =~ /\n/) {
                   1989:                     @matches = split(/\n/,$reply);
                   1990:                 } else {
                   1991:                     @matches = split(/\&/,$reply);
                   1992:                 }
1.899     raeburn  1993:                 foreach my $match (@matches) {
                   1994:                     my ($uname,$udom,%userhash);
1.911     raeburn  1995:                     foreach my $entry (split(/:/,$match)) {
                   1996:                         my ($key,$value) =
                   1997:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1998:                         $userhash{$key} = $value;
                   1999:                         if ($key eq 'username') {
                   2000:                             $uname = $value;
                   2001:                         } elsif ($key eq 'domain') {
                   2002:                             $udom = $value;
1.911     raeburn  2003:                         }
1.899     raeburn  2004:                     }
                   2005:                     $results{$uname.':'.$udom} = \%userhash;
                   2006:                 }
                   2007:             }
                   2008:         }
                   2009:     }
                   2010:     return %results;
                   2011: }
                   2012: 
1.912     raeburn  2013: sub get_instuser {
                   2014:     my ($udom,$uname,$id) = @_;
                   2015:     my $homeserver = &domain($udom,'primary');
                   2016:     my ($outcome,%results);
                   2017:     if ($homeserver ne '') {
                   2018:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2019:                            &escape($id).':'.&escape($udom),$homeserver);
                   2020:         my $host=&hostname($homeserver);
                   2021:         if ($queryid !~/^\Q$host\E\_/) {
                   2022:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2023:             return;
                   2024:         }
                   2025:         my $response = &get_query_reply($queryid);
                   2026:         my $maxtries = 5;
                   2027:         my $tries = 1;
                   2028:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2029:             $response = &get_query_reply($queryid);
                   2030:             $tries ++;
                   2031:         }
                   2032:         if (!&error($response) && $response ne 'refused') {
                   2033:             if ($response eq 'unavailable') {
                   2034:                 $outcome = $response;
                   2035:             } else {
                   2036:                 $outcome = 'ok';
                   2037:                 my @matches = split(/\n/,$response);
                   2038:                 foreach my $match (@matches) {
                   2039:                     my ($key,$value) = split(/=/,$match);
                   2040:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2041:                 }
                   2042:             }
                   2043:         }
                   2044:     }
                   2045:     my %userinfo;
                   2046:     if (ref($results{$uname}) eq 'HASH') {
                   2047:         %userinfo = %{$results{$uname}};
                   2048:     } 
                   2049:     return ($outcome,%userinfo);
                   2050: }
                   2051: 
1.1290    raeburn  2052: sub get_multiple_instusers {
                   2053:     my ($udom,$users,$caller) = @_;
                   2054:     my ($outcome,$results);
                   2055:     if (ref($users) eq 'HASH') {
                   2056:         my $count = keys(%{$users}); 
                   2057:         my $requested = &freeze_escape($users);
                   2058:         my $homeserver = &domain($udom,'primary');
                   2059:         if ($homeserver ne '') {
                   2060:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2061:             my $host=&hostname($homeserver);
                   2062:             if ($queryid !~/^\Q$host\E\_/) {
                   2063:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2064:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2065:                 return ($outcome,$results);
                   2066:             }
                   2067:             my $response = &get_query_reply($queryid);
                   2068:             my $maxtries = 5;
                   2069:             if ($count > 100) {
                   2070:                 $maxtries = 1+int($count/20);
                   2071:             }
                   2072:             my $tries = 1;
                   2073:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2074:                 $response = &get_query_reply($queryid);
                   2075:                 $tries ++;
                   2076:             }
                   2077:             if ($response eq '') {
                   2078:                 $results = {};
                   2079:                 foreach my $key (keys(%{$users})) {
                   2080:                     my ($uname,$id);
                   2081:                     if ($caller eq 'id') {
                   2082:                         $id = $key;
                   2083:                     } else {
                   2084:                         $uname = $key;
                   2085:                     }
                   2086:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2087:                     $outcome = $resp;
1.1290    raeburn  2088:                     if ($resp eq 'ok') {
                   2089:                         %{$results} = (%{$results}, %info);
                   2090:                     } else {
                   2091:                         last;
                   2092:                     }
                   2093:                 }
                   2094:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2095:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2096:                     $outcome = $response;
                   2097:                 } else {
1.1291    raeburn  2098:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2099:                     if ($outcome eq 'ok') {
                   2100:                         $results = &thaw_unescape($userdata); 
                   2101:                     }
                   2102:                 }
                   2103:             }
                   2104:         }
                   2105:     }
                   2106:     return ($outcome,$results);
                   2107: }
                   2108: 
1.912     raeburn  2109: sub inst_rulecheck {
1.923     raeburn  2110:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2111:     my %returnhash;
                   2112:     if ($udom ne '') {
                   2113:         if (ref($rules) eq 'ARRAY') {
                   2114:             @{$rules} = map {&escape($_);} (@{$rules});
                   2115:             my $rulestr = join(':',@{$rules});
                   2116:             my $homeserver=&domain($udom,'primary');
                   2117:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2118:                 my $response;
                   2119:                 if ($item eq 'username') {                
                   2120:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2121:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2122:                                               $homeserver));
1.923     raeburn  2123:                 } elsif ($item eq 'id') {
                   2124:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2125:                                               ':'.&escape($id).':'.$rulestr,
                   2126:                                               $homeserver));
1.945     raeburn  2127:                 } elsif ($item eq 'selfcreate') {
                   2128:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2129:                                                &escape($udom).':'.&escape($uname).
                   2130:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2131:                 }
1.912     raeburn  2132:                 if ($response ne 'refused') {
                   2133:                     my @pairs=split(/\&/,$response);
                   2134:                     foreach my $item (@pairs) {
                   2135:                         my ($key,$value)=split(/=/,$item,2);
                   2136:                         $key = &unescape($key);
                   2137:                         next if ($key =~ /^error: 2 /);
                   2138:                         $returnhash{$key}=&thaw_unescape($value);
                   2139:                     }
                   2140:                 }
                   2141:             }
                   2142:         }
                   2143:     }
                   2144:     return %returnhash;
                   2145: }
                   2146: 
                   2147: sub inst_userrules {
1.923     raeburn  2148:     my ($udom,$check) = @_;
1.912     raeburn  2149:     my (%ruleshash,@ruleorder);
                   2150:     if ($udom ne '') {
                   2151:         my $homeserver=&domain($udom,'primary');
                   2152:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2153:             my $response;
                   2154:             if ($check eq 'id') {
                   2155:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2156:                                  $homeserver);
1.943     raeburn  2157:             } elsif ($check eq 'email') {
                   2158:                 $response=&reply('instemailrules:'.&escape($udom),
                   2159:                                  $homeserver);
1.923     raeburn  2160:             } else {
                   2161:                 $response=&reply('instuserrules:'.&escape($udom),
                   2162:                                  $homeserver);
                   2163:             }
1.912     raeburn  2164:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2165:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2166:                 ($response ne 'no_such_host')) {
                   2167:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2168:                 my @pairs=split(/\&/,$hashitems);
                   2169:                 foreach my $item (@pairs) {
                   2170:                     my ($key,$value)=split(/=/,$item,2);
                   2171:                     $key = &unescape($key);
                   2172:                     next if ($key =~ /^error: 2 /);
                   2173:                     $ruleshash{$key}=&thaw_unescape($value);
                   2174:                 }
                   2175:                 my @esc_order = split(/\&/,$orderitems);
                   2176:                 foreach my $item (@esc_order) {
                   2177:                     push(@ruleorder,&unescape($item));
                   2178:                 }
                   2179:             }
                   2180:         }
                   2181:     }
                   2182:     return (\%ruleshash,\@ruleorder);
                   2183: }
                   2184: 
1.976     raeburn  2185: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2186: 
                   2187: sub get_domain_defaults {
1.1240    raeburn  2188:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2189:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2190:     my $cachetime = 60*60*24;
1.1240    raeburn  2191:     unless ($ignore_cache) {
                   2192:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2193:         if (defined($cached)) {
                   2194:             if (ref($result) eq 'HASH') {
                   2195:                 return %{$result};
                   2196:             }
1.943     raeburn  2197:         }
                   2198:     }
                   2199:     my %domdefaults;
                   2200:     my %domconfig =
1.989     raeburn  2201:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2202:                                   'requestcourses','inststatus',
1.1183    raeburn  2203:                                   'coursedefaults','usersessions',
1.1258    raeburn  2204:                                   'requestauthor','selfenrollment',
                   2205:                                   'coursecategories'],$domain);
1.1305    raeburn  2206:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2207:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2208:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2209:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2210:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2211:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2212:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2213:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2214:     } else {
                   2215:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2216:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2217:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2218:     }
1.976     raeburn  2219:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2220:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2221:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2222:         } else {
                   2223:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2224:         }
1.1177    raeburn  2225:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2226:         foreach my $item (@usertools) {
                   2227:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2228:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2229:             }
                   2230:         }
1.1229    raeburn  2231:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2232:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2233:         }
1.976     raeburn  2234:     }
1.985     raeburn  2235:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2236:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2237:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2238:         }
                   2239:     }
1.1183    raeburn  2240:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2241:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2242:     }
1.989     raeburn  2243:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2244:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2245:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2246:         }
                   2247:     }
1.1047    raeburn  2248:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2249:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2250:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2251:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2252:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2253:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2254:         }
1.1254    raeburn  2255:         foreach my $type (@coursetypes) {
                   2256:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2257:                 unless ($type eq 'community') {
                   2258:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2259:                 }
                   2260:             }
                   2261:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2262:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2263:             }
1.1277    raeburn  2264:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2265:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2266:                     $domdefaults{$type.'postsubtimeout'} = 
                   2267:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2268:                 }
                   2269:             }
1.1230    raeburn  2270:         }
1.1286    raeburn  2271:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2272:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2273:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2274:                 if (@clonecodes) {
                   2275:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2276:                 }
                   2277:             }
                   2278:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2279:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2280:         }
1.1047    raeburn  2281:     }
1.1073    raeburn  2282:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2283:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2284:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2285:         }
                   2286:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2287:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2288:         }
1.1279    raeburn  2289:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2290:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2291:         }
1.1073    raeburn  2292:     }
1.1254    raeburn  2293:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2294:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2295:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2296:                             'approval','limit');
                   2297:             foreach my $type (@coursetypes) {
                   2298:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2299:                     my @mgrdc = ();
                   2300:                     foreach my $item (@settings) {
                   2301:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2302:                             push(@mgrdc,$item);
                   2303:                         }
                   2304:                     }
                   2305:                     if (@mgrdc) {
                   2306:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2307:                     }
                   2308:                 }
                   2309:             }
                   2310:         }
                   2311:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2312:             foreach my $type (@coursetypes) {
                   2313:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2314:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2315:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2316:                     }
                   2317:                 }
                   2318:             }
                   2319:         }
                   2320:     }
1.1258    raeburn  2321:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2322:         $domdefaults{'catauth'} = 'std';
                   2323:         $domdefaults{'catunauth'} = 'std';
                   2324:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2325:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2326:         }
                   2327:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2328:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2329:         }
                   2330:     }
1.1219    raeburn  2331:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2332:     return %domdefaults;
                   2333: }
                   2334: 
1.1311  ! raeburn  2335: sub course_portal_url {
        !          2336:     my ($cnum,$cdom) = @_;
        !          2337:     my $chome = &homeserver($cnum,$cdom);
        !          2338:     my $hostname = &hostname($chome);
        !          2339:     my $protocol = $protocol{$chome};
        !          2340:     $protocol = 'http' if ($protocol ne 'https');
        !          2341:     my %domdefaults = &get_domain_defaults($cdom);
        !          2342:     my $firsturl;
        !          2343:     if ($domdefaults{'portal_def'}) {
        !          2344:         $firsturl = $domdefaults{'portal_def'};
        !          2345:     } else {
        !          2346:         $firsturl = $protocol.'://'.$hostname;
        !          2347:     }
        !          2348:     return $firsturl;
        !          2349: }
        !          2350: 
1.344     www      2351: # --------------------------------------------------- Assign a key to a student
                   2352: 
                   2353: sub assign_access_key {
1.364     www      2354: #
                   2355: # a valid key looks like uname:udom#comments
                   2356: # comments are being appended
                   2357: #
1.498     www      2358:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2359:     $kdom=
1.620     albertel 2360:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2361:     $knum=
1.620     albertel 2362:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2363:     $cdom=
1.620     albertel 2364:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2365:     $cnum=
1.620     albertel 2366:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2367:     $udom=$env{'user.name'} unless (defined($udom));
                   2368:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2369:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2370:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2371:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2372:                                                   # assigned to this person
                   2373:                                                   # - this should not happen,
1.345     www      2374:                                                   # unless something went wrong
                   2375:                                                   # the first time around
                   2376: # ready to assign
1.364     www      2377:         $logentry=$1.'; '.$logentry;
1.496     www      2378:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2379:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2380: # key now belongs to user
1.346     www      2381: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2382:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2383:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2384:                 return 'ok';
                   2385:             } else {
                   2386:                 return 
                   2387:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2388: 	    }
                   2389:         } else {
                   2390:             return 'error: Could not assign key, try again later.';
                   2391:         }
1.364     www      2392:     } elsif (!$existing{$ckey}) {
1.345     www      2393: # the key does not exist
                   2394: 	return 'error: The key does not exist';
                   2395:     } else {
                   2396: # the key is somebody else's
                   2397: 	return 'error: The key is already in use';
                   2398:     }
1.344     www      2399: }
                   2400: 
1.364     www      2401: # ------------------------------------------ put an additional comment on a key
                   2402: 
                   2403: sub comment_access_key {
                   2404: #
                   2405: # a valid key looks like uname:udom#comments
                   2406: # comments are being appended
                   2407: #
                   2408:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2409:     $cdom=
1.620     albertel 2410:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2411:     $cnum=
1.620     albertel 2412:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2413:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2414:     if ($existing{$ckey}) {
                   2415:         $existing{$ckey}.='; '.$logentry;
                   2416: # ready to assign
1.367     www      2417:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2418:                                                  $cdom,$cnum) eq 'ok') {
                   2419: 	    return 'ok';
                   2420:         } else {
                   2421: 	    return 'error: Count not store comment.';
                   2422:         }
                   2423:     } else {
                   2424: # the key does not exist
                   2425: 	return 'error: The key does not exist';
                   2426:     }
                   2427: }
                   2428: 
1.344     www      2429: # ------------------------------------------------------ Generate a set of keys
                   2430: 
                   2431: sub generate_access_keys {
1.364     www      2432:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2433:     $cdom=
1.620     albertel 2434:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2435:     $cnum=
1.620     albertel 2436:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2437:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2438:     unless (($cdom) && ($cnum)) { return 0; }
                   2439:     if ($number>10000) { return 0; }
                   2440:     sleep(2); # make sure don't get same seed twice
                   2441:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2442:     my $total=0;
                   2443:     for (my $i=1;$i<=$number;$i++) {
                   2444:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2445:                   sprintf("%lx",int(100000*rand)).'-'.
                   2446:                   sprintf("%lx",int(100000*rand));
                   2447:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2448:        $newkey=~s/0/h/g; # and also 0 and O
                   2449:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2450:        if ($existing{$newkey}) {
                   2451:            $i--;
                   2452:        } else {
1.364     www      2453: 	  if (&put('accesskeys',
                   2454:               { $newkey => '# generated '.localtime().
1.620     albertel 2455:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2456:                            '; '.$logentry },
                   2457: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2458:               $total++;
                   2459: 	  }
                   2460:        }
                   2461:     }
1.620     albertel 2462:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2463:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2464:     return $total;
                   2465: }
                   2466: 
                   2467: # ------------------------------------------------------- Validate an accesskey
                   2468: 
                   2469: sub validate_access_key {
                   2470:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2471:     $cdom=
1.620     albertel 2472:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2473:     $cnum=
1.620     albertel 2474:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2475:     $udom=$env{'user.domain'} unless (defined($udom));
                   2476:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2477:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2478:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2479: }
                   2480: 
                   2481: # ------------------------------------- Find the section of student in a course
1.652     albertel 2482: sub devalidate_getsection_cache {
                   2483:     my ($udom,$unam,$courseid)=@_;
                   2484:     my $hashid="$udom:$unam:$courseid";
                   2485:     &devalidate_cache_new('getsection',$hashid);
                   2486: }
1.298     matthew  2487: 
1.815     albertel 2488: sub courseid_to_courseurl {
                   2489:     my ($courseid) = @_;
                   2490:     #already url style courseid
                   2491:     return $courseid if ($courseid =~ m{^/});
                   2492: 
                   2493:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2494: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2495: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2496: 	return "/$cdom/$cnum";
                   2497:     }
                   2498: 
                   2499:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2500:     if (exists($courseinfo{'num'})) {
                   2501: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2502:     }
                   2503: 
                   2504:     return undef;
                   2505: }
                   2506: 
1.298     matthew  2507: sub getsection {
                   2508:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2509:     my $cachetime=1800;
1.551     albertel 2510: 
                   2511:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2512:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2513:     if (defined($cached)) { return $result; }
                   2514: 
1.298     matthew  2515:     my %Pending; 
                   2516:     my %Expired;
                   2517:     #
                   2518:     # Each role can either have not started yet (pending), be active, 
                   2519:     #    or have expired.
                   2520:     #
                   2521:     # If there is an active role, we are done.
                   2522:     #
                   2523:     # If there is more than one role which has not started yet, 
                   2524:     #     choose the one which will start sooner
                   2525:     # If there is one role which has not started yet, return it.
                   2526:     #
                   2527:     # If there is more than one expired role, choose the one which ended last.
                   2528:     # If there is a role which has expired, return it.
                   2529:     #
1.815     albertel 2530:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2531:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2532:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2533:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2534:         my $section=$1;
                   2535:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2536:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2537:         my $now=time;
1.548     albertel 2538:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2539:             $Expired{$end}=$section;
                   2540:             next;
                   2541:         }
1.548     albertel 2542:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2543:             $Pending{$start}=$section;
                   2544:             next;
                   2545:         }
1.599     albertel 2546:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2547:     }
                   2548:     #
                   2549:     # Presumedly there will be few matching roles from the above
                   2550:     # loop and the sorting time will be negligible.
                   2551:     if (scalar(keys(%Pending))) {
                   2552:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2553:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2554:     } 
                   2555:     if (scalar(keys(%Expired))) {
                   2556:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2557:         my $time = pop(@sorted);
1.599     albertel 2558:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2559:     }
1.599     albertel 2560:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2561: }
1.70      www      2562: 
1.599     albertel 2563: sub save_cache {
                   2564:     &purge_remembered();
1.722     albertel 2565:     #&Apache::loncommon::validate_page();
1.620     albertel 2566:     undef(%env);
1.780     albertel 2567:     undef($env_loaded);
1.599     albertel 2568: }
1.452     albertel 2569: 
1.599     albertel 2570: my $to_remember=-1;
                   2571: my %remembered;
                   2572: my %accessed;
                   2573: my $kicks=0;
                   2574: my $hits=0;
1.849     albertel 2575: sub make_key {
                   2576:     my ($name,$id) = @_;
1.872     albertel 2577:     if (length($id) > 65 
                   2578: 	&& length(&escape($id)) > 200) {
                   2579: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2580:     }
1.849     albertel 2581:     return &escape($name.':'.$id);
                   2582: }
                   2583: 
1.599     albertel 2584: sub devalidate_cache_new {
                   2585:     my ($name,$id,$debug) = @_;
                   2586:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2587:     $id=&make_key($name,$id);
1.599     albertel 2588:     $memcache->delete($id);
                   2589:     delete($remembered{$id});
                   2590:     delete($accessed{$id});
                   2591: }
                   2592: 
                   2593: sub is_cached_new {
                   2594:     my ($name,$id,$debug) = @_;
1.849     albertel 2595:     $id=&make_key($name,$id);
1.599     albertel 2596:     if (exists($remembered{$id})) {
1.1133    foxr     2597: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2598: 	$accessed{$id}=[&gettimeofday()];
                   2599: 	$hits++;
                   2600: 	return ($remembered{$id},1);
                   2601:     }
                   2602:     my $value = $memcache->get($id);
                   2603:     if (!(defined($value))) {
                   2604: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2605: 	return (undef,undef);
1.416     albertel 2606:     }
1.599     albertel 2607:     if ($value eq '__undef__') {
                   2608: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2609: 	$value=undef;
                   2610:     }
                   2611:     &make_room($id,$value,$debug);
                   2612:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2613:     return ($value,1);
                   2614: }
                   2615: 
                   2616: sub do_cache_new {
                   2617:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2618:     $id=&make_key($name,$id);
1.599     albertel 2619:     my $setvalue=$value;
                   2620:     if (!defined($setvalue)) {
                   2621: 	$setvalue='__undef__';
                   2622:     }
1.623     albertel 2623:     if (!defined($time) ) {
                   2624: 	$time=600;
                   2625:     }
1.599     albertel 2626:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2627:     my $result = $memcache->set($id,$setvalue,$time);
                   2628:     if (! $result) {
1.872     albertel 2629: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2630: 	$memcache->disconnect_all();
1.872     albertel 2631:     }
1.600     albertel 2632:     # need to make a copy of $value
1.919     albertel 2633:     &make_room($id,$value,$debug);
1.599     albertel 2634:     return $value;
                   2635: }
                   2636: 
                   2637: sub make_room {
                   2638:     my ($id,$value,$debug)=@_;
1.919     albertel 2639: 
                   2640:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2641:                                     : $value;
1.599     albertel 2642:     if ($to_remember<0) { return; }
                   2643:     $accessed{$id}=[&gettimeofday()];
                   2644:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2645:     my $to_kick;
                   2646:     my $max_time=0;
                   2647:     foreach my $other (keys(%accessed)) {
                   2648: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2649: 	    $to_kick=$other;
                   2650: 	    $max_time=&tv_interval($accessed{$other});
                   2651: 	}
                   2652:     }
                   2653:     delete($remembered{$to_kick});
                   2654:     delete($accessed{$to_kick});
                   2655:     $kicks++;
                   2656:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2657:     return;
                   2658: }
                   2659: 
1.599     albertel 2660: sub purge_remembered {
1.604     albertel 2661:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2662:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2663:     undef(%remembered);
                   2664:     undef(%accessed);
1.428     albertel 2665: }
1.70      www      2666: # ------------------------------------- Read an entry from a user's environment
                   2667: 
                   2668: sub userenvironment {
                   2669:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2670:     my $items;
                   2671:     foreach my $item (@what) {
                   2672:         $items.=&escape($item).'&';
                   2673:     }
                   2674:     $items=~s/\&$//;
1.70      www      2675:     my %returnhash=();
1.1009    raeburn  2676:     my $uhome = &homeserver($unam,$udom);
                   2677:     unless ($uhome eq 'no_host') {
                   2678:         my @answer=split(/\&/, 
                   2679:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2680:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2681:             return %returnhash;
                   2682:         }
1.1009    raeburn  2683:         my $i;
                   2684:         for ($i=0;$i<=$#what;$i++) {
                   2685: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2686:         }
1.70      www      2687:     }
                   2688:     return %returnhash;
1.1       albertel 2689: }
                   2690: 
1.617     albertel 2691: # ---------------------------------------------------------- Get a studentphoto
                   2692: sub studentphoto {
                   2693:     my ($udom,$unam,$ext) = @_;
                   2694:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2695:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2696:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2697:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2698:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2699:             } else {
                   2700:                 my ($result,$perm_reqd)=
1.707     albertel 2701: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2702:                 if ($result eq 'ok') {
                   2703:                     if (!($perm_reqd eq 'yes')) {
                   2704:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2705:                     }
                   2706:                 }
                   2707:             }
                   2708:         }
                   2709:     } else {
                   2710:         my ($result,$perm_reqd) = 
1.707     albertel 2711: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2712:         if ($result eq 'ok') {
                   2713:             if (!($perm_reqd eq 'yes')) {
                   2714:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2715:             }
                   2716:         }
                   2717:     }
                   2718:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2719: }
                   2720: 
                   2721: sub retrievestudentphoto {
                   2722:     my ($udom,$unam,$ext,$type) = @_;
                   2723:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2724:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2725:     if ($ret eq 'ok') {
                   2726:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2727:         if ($type eq 'thumbnail') {
                   2728:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2729:         }
                   2730:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2731:         return $tokenurl;
                   2732:     } else {
                   2733:         if ($type eq 'thumbnail') {
                   2734:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2735:         } else { 
                   2736:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2737:         }
1.617     albertel 2738:     }
                   2739: }
                   2740: 
1.263     www      2741: # -------------------------------------------------------------------- New chat
                   2742: 
                   2743: sub chatsend {
1.724     raeburn  2744:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2745:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2746:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2747:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2748:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2749: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2750: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2751: }
                   2752: 
                   2753: # ------------------------------------------ Find current version of a resource
                   2754: 
                   2755: sub getversion {
                   2756:     my $fname=&clutter(shift);
1.1189    raeburn  2757:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2758:     return &currentversion(&filelocation('',$fname));
                   2759: }
                   2760: 
                   2761: sub currentversion {
                   2762:     my $fname=shift;
                   2763:     my $author=$fname;
                   2764:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2765:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2766:     my $home=&homeserver($uname,$udom);
1.292     www      2767:     if ($home eq 'no_host') { 
                   2768:         return -1; 
                   2769:     }
1.1112    www      2770:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2771:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2772: 	return -1;
                   2773:     }
1.1112    www      2774:     return $answer;
1.263     www      2775: }
                   2776: 
1.1111    www      2777: #
                   2778: # Return special version number of resource if set by override, empty otherwise
                   2779: #
                   2780: sub usedversion {
                   2781:     my $fname=shift;
                   2782:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2783:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2784:     if ($urlversion) { return $urlversion; }
                   2785:     return '';
                   2786: }
                   2787: 
1.1       albertel 2788: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2789: 
1.1       albertel 2790: sub subscribe {
                   2791:     my $fname=shift;
1.761     raeburn  2792:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2793:     $fname=~s/[\n\r]//g;
1.1       albertel 2794:     my $author=$fname;
                   2795:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2796:     my ($udom,$uname)=split(/\//,$author);
                   2797:     my $home=homeserver($uname,$udom);
1.335     albertel 2798:     if ($home eq 'no_host') {
                   2799:         return 'not_found';
1.1       albertel 2800:     }
                   2801:     my $answer=reply("sub:$fname",$home);
1.64      www      2802:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2803: 	$answer.=' by '.$home;
                   2804:     }
1.1       albertel 2805:     return $answer;
                   2806: }
                   2807:     
1.8       www      2808: # -------------------------------------------------------------- Replicate file
                   2809: 
                   2810: sub repcopy {
                   2811:     my $filename=shift;
1.23      www      2812:     $filename=~s/\/+/\//g;
1.1142    raeburn  2813:     my $londocroot = $perlvar{'lonDocRoot'};
                   2814:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2815:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2816:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2817: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2818: 	return &repcopy_userfile($filename);
                   2819:     }
1.532     albertel 2820:     $filename=~s/[\n\r]//g;
1.8       www      2821:     my $transname="$filename.in.transfer";
1.828     www      2822: # FIXME: this should flock
1.607     raeburn  2823:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2824:     my $remoteurl=subscribe($filename);
1.64      www      2825:     if ($remoteurl =~ /^con_lost by/) {
                   2826: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2827:            return 'unavailable';
1.8       www      2828:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2829: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2830: 	   return 'not_found';
1.64      www      2831:     } elsif ($remoteurl =~ /^rejected by/) {
                   2832: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2833:            return 'forbidden';
1.20      www      2834:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2835:            return 'ok';
1.8       www      2836:     } else {
1.290     www      2837:         my $author=$filename;
                   2838:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2839:         my ($udom,$uname)=split(/\//,$author);
                   2840:         my $home=homeserver($uname,$udom);
                   2841:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2842:            my @parts=split(/\//,$filename);
                   2843:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2844:            if ($path ne "$londocroot/res") {
1.8       www      2845:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2846: 	       return 'bad_request';
1.8       www      2847:            }
                   2848:            my $count;
                   2849:            for ($count=5;$count<$#parts;$count++) {
                   2850:                $path.="/$parts[$count]";
                   2851:                if ((-e $path)!=1) {
                   2852: 		   mkdir($path,0777);
                   2853:                }
                   2854:            }
                   2855:            my $ua=new LWP::UserAgent;
                   2856:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2857:            my $response=$ua->request($request,$transname);
                   2858:            if ($response->is_error()) {
                   2859: 	       unlink($transname);
                   2860:                my $message=$response->status_line;
1.672     albertel 2861:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2862:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2863:                return 'unavailable';
1.8       www      2864:            } else {
1.16      www      2865: 	       if ($remoteurl!~/\.meta$/) {
                   2866:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2867:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2868:                   if ($mresponse->is_error()) {
                   2869: 		      unlink($filename.'.meta');
                   2870:                       &logthis(
1.672     albertel 2871:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2872:                   }
                   2873: 	       }
1.8       www      2874:                rename($transname,$filename);
1.607     raeburn  2875:                return 'ok';
1.8       www      2876:            }
1.290     www      2877:        }
1.8       www      2878:     }
1.330     www      2879: }
                   2880: 
                   2881: # ------------------------------------------------ Get server side include body
                   2882: sub ssi_body {
1.381     albertel 2883:     my ($filelink,%form)=@_;
1.606     matthew  2884:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2885:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2886:     }
1.953     www      2887:     my $output='';
                   2888:     my $response;
1.980     raeburn  2889:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2890:        ($output,$response)=&externalssi($filelink);
1.953     www      2891:     } else {
1.1004    droeschl 2892:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2893:        $filelink .= 'inhibitmenu=yes';
1.953     www      2894:        ($output,$response)=&ssi($filelink,%form);
                   2895:     }
1.778     albertel 2896:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2897:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2898:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2899:     if (wantarray) {
                   2900:         return ($output, $response);
                   2901:     } else {
                   2902:         return $output;
                   2903:     }
1.8       www      2904: }
                   2905: 
1.15      www      2906: # --------------------------------------------------------- Server Side Include
                   2907: 
1.782     albertel 2908: sub absolute_url {
                   2909:     my ($host_name) = @_;
                   2910:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2911:     if ($host_name eq '') {
                   2912: 	$host_name = $ENV{'SERVER_NAME'};
                   2913:     }
                   2914:     return $protocol.$host_name;
                   2915: }
                   2916: 
1.942     foxr     2917: #
                   2918: #   Server side include.
                   2919: # Parameters:
                   2920: #  fn     Possibly encrypted resource name/id.
                   2921: #  form   Hash that describes how the rendering should be done
                   2922: #         and other things.
1.944     foxr     2923: # Returns:
1.950     raeburn  2924: #   Scalar context: The content of the response.
                   2925: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2926: #     
1.15      www      2927: sub ssi {
                   2928: 
1.944     foxr     2929:     my ($fn,%form)=@_;
1.15      www      2930:     my $ua=new LWP::UserAgent;
1.23      www      2931:     my $request;
1.711     albertel 2932: 
                   2933:     $form{'no_update_last_known'}=1;
1.895     albertel 2934:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2935:     if (%form) {
1.782     albertel 2936:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2937:       $request->content(join('&',map { 
                   2938:             my $name = escape($_);
                   2939:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2940:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2941:             : &escape($form{$_}) );    
                   2942:         } keys(%form)));
1.23      www      2943:     } else {
1.782     albertel 2944:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2945:     }
                   2946: 
1.15      www      2947:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2948:     my $response= $ua->request($request);
1.1182    foxr     2949:     my $content = $response->content;
                   2950: 
                   2951: 
1.944     foxr     2952:     if (wantarray) {
1.1173    foxr     2953: 	return ($content, $response);
1.944     foxr     2954:     } else {
1.1173    foxr     2955: 	return $content;
1.942     foxr     2956:     }
1.324     www      2957: }
                   2958: 
                   2959: sub externalssi {
                   2960:     my ($url)=@_;
                   2961:     my $ua=new LWP::UserAgent;
                   2962:     my $request=new HTTP::Request('GET',$url);
                   2963:     my $response=$ua->request($request);
1.954     raeburn  2964:     if (wantarray) {
                   2965:         return ($response->content, $response);
                   2966:     } else {
                   2967:         return $response->content;
                   2968:     }
1.15      www      2969: }
1.254     www      2970: 
1.492     albertel 2971: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2972: 
                   2973: sub allowuploaded {
                   2974:     my ($srcurl,$url)=@_;
                   2975:     $url=&clutter(&declutter($url));
                   2976:     my $dir=$url;
                   2977:     $dir=~s/\/[^\/]+$//;
                   2978:     my %httpref=();
                   2979:     my $httpurl=&hreflocation('',$url);
                   2980:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2981:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2982: }
1.477     raeburn  2983: 
1.1193    raeburn  2984: #
                   2985: # Determine if the current user should be able to edit a particular resource,
                   2986: # when viewing in course context.
                   2987: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2988: #     Functions.
                   2989: # (b) When displaying folder contents in course editor, used to determine if
                   2990: #     "Edit" link will be displayed alongside resource.
                   2991: #
1.1196    raeburn  2992: #  input: six args -- filename (decluttered), course number, course domain,
                   2993: #                   url, symb (if registered) and group (if this is a group
                   2994: #                   item -- e.g., bulletin board, group page etc.).
                   2995: #  output: array of five scalars -- 
1.1193    raeburn  2996: #          $cfile -- url for file editing if editable on current server
                   2997: #          $home -- homeserver of resource (i.e., for author if published,
                   2998: #                                           or course if uploaded.).
                   2999: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3000: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3001: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3002: #
                   3003: 
                   3004: sub can_edit_resource {
1.1194    raeburn  3005:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3006:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3007: #
                   3008: # For aboutme pages user can only edit his/her own.
                   3009: #
1.1199    raeburn  3010:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3011:         my ($sdom,$sname) = ($1,$2);
                   3012:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3013:             $home = $env{'user.home'};
                   3014:             $cfile = $resurl;
                   3015:             if ($env{'form.forceedit'}) {
                   3016:                 $forceview = 1;
                   3017:             } else {
                   3018:                 $forceedit = 1;
                   3019:             }
                   3020:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3021:         } else {
                   3022:             return;
                   3023:         }
                   3024:     }
                   3025: 
                   3026:     if ($env{'request.course.id'}) {
                   3027:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3028:         if ($group ne '') {
                   3029: # if this is a group homepage or group bulletin board, check group privs
                   3030:             my $allowed = 0;
1.1197    raeburn  3031:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3032:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3033:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3034:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3035:                     $allowed = 1;
                   3036:                 }
1.1197    raeburn  3037:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3038:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3039:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3040:                     $allowed = 1;
                   3041:                 }
                   3042:             }
                   3043:             if ($allowed) {
                   3044:                 $home=&homeserver($cnum,$cdom);
                   3045:                 if ($env{'form.forceedit'}) {
                   3046:                     $forceview = 1;
                   3047:                 } else {
                   3048:                     $forceedit = 1;
                   3049:                 }
                   3050:                 $cfile = $resurl;
                   3051:             } else {
                   3052:                 return;
                   3053:             }
                   3054:         } else {
1.1208    raeburn  3055:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3056:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3057:                     return;
                   3058:                 }
                   3059:             } elsif (!$crsedit) {
1.1194    raeburn  3060: #
                   3061: # No edit allowed where CC has switched to student role.
                   3062: #
                   3063:                 return;
                   3064:             }
                   3065:         }
                   3066:     }
                   3067: 
1.1193    raeburn  3068:     if ($file ne '') {
                   3069:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3070:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3071:                 $uploaded = 1;
                   3072:                 $incourse = 1;
1.1193    raeburn  3073:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3074:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3075:                     if ($env{'form.forceedit'}) {
                   3076:                         $forceview = 1;
                   3077:                     } else {
                   3078:                         $forceedit = 1;
                   3079:                     }
1.1194    raeburn  3080:                 }
                   3081:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3082:                 $incourse = 1;
                   3083:                 if ($env{'form.forceedit'}) {
                   3084:                     $forceview = 1;
                   3085:                 } else {
                   3086:                     $forceedit = 1;
                   3087:                 }
                   3088:                 $cfile = $resurl;
                   3089:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3090:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3091:                     $incourse = 1;
                   3092:                     if ($env{'form.forceedit'}) {
                   3093:                         $forceview = 1;
                   3094:                     } else {
                   3095:                         $forceedit = 1;
                   3096:                     }
                   3097:                     $cfile = $resurl;
1.1199    raeburn  3098:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3099:                     $incourse = 1;
                   3100:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3101:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3102:                     $incourse = 1;
1.1199    raeburn  3103:                     if ($env{'form.forceedit'}) {
                   3104:                         $forceview = 1;
                   3105:                     } else {
                   3106:                         $forceedit = 1;
                   3107:                     }
                   3108:                     $cfile = $resurl;
1.1298    raeburn  3109:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3110:                     $incourse = 1;
                   3111:                     if ($env{'form.forceedit'}) {
                   3112:                         $forceview = 1;
                   3113:                     } else {
                   3114:                         $forceedit = 1;
                   3115:                     }
                   3116:                     $cfile = $resurl;
1.1208    raeburn  3117:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3118:                     $incourse = 1;
                   3119:                     if ($env{'form.forceedit'}) {
                   3120:                         $forceview = 1;
                   3121:                     } else {
                   3122:                         $forceedit = 1;
                   3123:                     }
                   3124:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3125:                 }
                   3126:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3127:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3128:                 if (&is_on_map($template)) { 
                   3129:                     $incourse = 1;
                   3130:                     $forceview = 1;
                   3131:                     $cfile = $template;
1.1193    raeburn  3132:                 }
1.1199    raeburn  3133:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3134:                     $incourse = 1;
                   3135:                     if ($env{'form.forceedit'}) {
                   3136:                         $forceview = 1;
                   3137:                     } else {
                   3138:                         $forceedit = 1;
                   3139:                     }
                   3140:                     $cfile = $resurl;
1.1298    raeburn  3141:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3142:                 $incourse = 1;
                   3143:                 if ($env{'form.forceedit'}) {
                   3144:                     $forceview = 1;
                   3145:                 } else {
                   3146:                     $forceedit = 1;
                   3147:                 }
                   3148:                 $cfile = $resurl;
1.1199    raeburn  3149:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3150:                 $incourse = 1;
                   3151:                 $forceview = 1;
                   3152:                 if ($symb) {
                   3153:                     my ($map,$id,$res)=&decode_symb($symb);
                   3154:                     $env{'request.symb'} = $symb;
                   3155:                     $cfile = &clutter($res);
                   3156:                 } else {
                   3157:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3158:                     my $escfile = &unescape($cfile);
                   3159:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3160:                         $cfile = '/adm/wrapper'.$escfile;
                   3161:                     } else {
                   3162:                         $escfile =~ s{^http://}{};
                   3163:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3164:                     }
1.1199    raeburn  3165:                 }
1.1234    raeburn  3166:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3167:                 if ($env{'form.forceedit'}) {
                   3168:                     $forceview = 1;
                   3169:                 } else {
                   3170:                     $forceedit = 1;
                   3171:                 }
                   3172:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3173:             }
                   3174:         }
1.1194    raeburn  3175:         if ($uploaded || $incourse) {
                   3176:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3177:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3178:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3179:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3180:             # Check that the user has permission to edit this resource
                   3181:             my $setpriv = 1;
                   3182:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3183:             if (defined($cfudom)) {
                   3184:                 $home=&homeserver($cfuname,$cfudom);
                   3185:                 $cfile=$file;
                   3186:             }
                   3187:         }
1.1194    raeburn  3188:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3189:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3190:             my @ids=&current_machine_ids();
                   3191:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3192:                 $switchserver=1;
                   3193:             }
                   3194:         }
                   3195:     }
1.1194    raeburn  3196:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3197: }
                   3198: 
                   3199: sub is_course_upload {
                   3200:     my ($file,$cnum,$cdom) = @_;
                   3201:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3202:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3203:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3204:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3205:         return 1;
                   3206:     }
                   3207:     return;
                   3208: }
                   3209: 
1.1194    raeburn  3210: sub in_course {
1.1195    raeburn  3211:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3212:     if ($hideprivileged) {
                   3213:         my $skipuser;
1.1219    raeburn  3214:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3215:         my @possdoms = ($cdom);  
                   3216:         if ($coursehash{'checkforpriv'}) { 
                   3217:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3218:         }
                   3219:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3220:             $skipuser = 1;
                   3221:             if ($coursehash{'nothideprivileged'}) {
                   3222:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3223:                     my $user;
                   3224:                     if ($item =~ /:/) {
                   3225:                         $user = $item;
                   3226:                     } else {
                   3227:                         $user = join(':',split(/[\@]/,$item));
                   3228:                     }
                   3229:                     if ($user eq $uname.':'.$udom) {
                   3230:                         undef($skipuser);
                   3231:                         last;
                   3232:                     }
                   3233:                 }
                   3234:             }
                   3235:             if ($skipuser) {
                   3236:                 return 0;
                   3237:             }
                   3238:         }
                   3239:     }
1.1194    raeburn  3240:     $type ||= 'any';
                   3241:     if (!defined($cdom) || !defined($cnum)) {
                   3242:         my $cid  = $env{'request.course.id'};
                   3243:         $cdom = $env{'course.'.$cid.'.domain'};
                   3244:         $cnum = $env{'course.'.$cid.'.num'};
                   3245:     }
                   3246:     my $typesref;
1.1195    raeburn  3247:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3248:         $typesref = ['active','previous','future'];
                   3249:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3250:         $typesref = [$type];
                   3251:     }
                   3252:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3253:                               $typesref,undef,[$cdom]);
                   3254:     my ($tmp) = keys(%roles);
                   3255:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3256:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3257:     if (@course_roles > 0) {
                   3258:         return 1;
                   3259:     }
                   3260:     return 0;
                   3261: }
                   3262: 
1.478     albertel 3263: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3264: # input: action, courseID, current domain, intended
1.637     raeburn  3265: #        path to file, source of file, instruction to parse file for objects,
                   3266: #        ref to hash for embedded objects,
                   3267: #        ref to hash for codebase of java objects.
1.1095    raeburn  3268: #        reference to scalar to accommodate mime type determined
                   3269: #          from File::MMagic if $parser = parse.
1.637     raeburn  3270: #
1.485     raeburn  3271: # output: url to file (if action was uploaddoc), 
                   3272: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3273: #
1.478     albertel 3274: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3275: # course.
1.477     raeburn  3276: #
1.478     albertel 3277: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3278: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3279: #          course's home server.
1.477     raeburn  3280: #
1.478     albertel 3281: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3282: #          be copied from $source (current location) to 
                   3283: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3284: #         and will then be copied to
                   3285: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3286: #         course's home server.
1.485     raeburn  3287: #
1.481     raeburn  3288: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3289: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3290: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3291: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3292: #         in course's home server.
1.637     raeburn  3293: #
1.477     raeburn  3294: 
                   3295: sub process_coursefile {
1.1095    raeburn  3296:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3297:         $mimetype)=@_;
1.477     raeburn  3298:     my $fetchresult;
1.638     albertel 3299:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3300:     if ($action eq 'propagate') {
1.638     albertel 3301:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3302: 			     $home);
1.481     raeburn  3303:     } else {
1.477     raeburn  3304:         my $fpath = '';
                   3305:         my $fname = $file;
1.478     albertel 3306:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3307:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3308:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3309:         if ($action eq 'copy') {
                   3310:             if ($source eq '') {
                   3311:                 $fetchresult = 'no source file';
                   3312:                 return $fetchresult;
                   3313:             } else {
                   3314:                 my $destination = $filepath.'/'.$fname;
                   3315:                 rename($source,$destination);
                   3316:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3317:                                  $home);
1.481     raeburn  3318:             }
                   3319:         } elsif ($action eq 'uploaddoc') {
                   3320:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3321:             print $fh $env{'form.'.$source};
1.481     raeburn  3322:             close($fh);
1.637     raeburn  3323:             if ($parser eq 'parse') {
1.1024    raeburn  3324:                 my $mm = new File::MMagic;
1.1095    raeburn  3325:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3326:                 if ($type eq 'text/html') {
1.1024    raeburn  3327:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3328:                     unless ($parse_result eq 'ok') {
                   3329:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3330:                     }
1.637     raeburn  3331:                 }
1.1095    raeburn  3332:                 if (ref($mimetype)) {
                   3333:                     $$mimetype = $type;
                   3334:                 } 
1.637     raeburn  3335:             }
1.477     raeburn  3336:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3337:                                  $home);
1.481     raeburn  3338:             if ($fetchresult eq 'ok') {
                   3339:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3340:             } else {
                   3341:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3342:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3343:                 return '/adm/notfound.html';
                   3344:             }
1.477     raeburn  3345:         }
                   3346:     }
1.485     raeburn  3347:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3348:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3349:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3350:     }
                   3351:     return $fetchresult;
                   3352: }
                   3353: 
1.637     raeburn  3354: sub build_filepath {
                   3355:     my ($fpath) = @_;
                   3356:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3357:     unless ($fpath eq '') {
                   3358:         my @parts=split('/',$fpath);
                   3359:         foreach my $part (@parts) {
                   3360:             $filepath.= '/'.$part;
                   3361:             if ((-e $filepath)!=1) {
                   3362:                 mkdir($filepath,0777);
                   3363:             }
                   3364:         }
                   3365:     }
                   3366:     return $filepath;
                   3367: }
                   3368: 
                   3369: sub store_edited_file {
1.638     albertel 3370:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3371:     my $file = $primary_url;
                   3372:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3373:     my $fpath = '';
                   3374:     my $fname = $file;
                   3375:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3376:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3377:     my $filepath = &build_filepath($fpath);
                   3378:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3379:     print $fh $content;
                   3380:     close($fh);
1.638     albertel 3381:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3382:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3383: 			  $home);
1.637     raeburn  3384:     if ($$fetchresult eq 'ok') {
                   3385:         return '/uploaded/'.$fpath.'/'.$fname;
                   3386:     } else {
1.638     albertel 3387:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3388: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3389:         return '/adm/notfound.html';
                   3390:     }
                   3391: }
                   3392: 
1.531     albertel 3393: sub clean_filename {
1.831     albertel 3394:     my ($fname,$args)=@_;
1.315     www      3395: # Replace Windows backslashes by forward slashes
1.257     www      3396:     $fname=~s/\\/\//g;
1.831     albertel 3397:     if (!$args->{'keep_path'}) {
                   3398:         # Get rid of everything but the actual filename
                   3399: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3400:     }
1.315     www      3401: # Replace spaces by underscores
                   3402:     $fname=~s/\s+/\_/g;
                   3403: # Replace all other weird characters by nothing
1.831     albertel 3404:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3405: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3406: # numbers
                   3407:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3408:     return $fname;
                   3409: }
1.1051    raeburn  3410: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3411: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3412: # image with the same aspect ratio as the original, but with dimensions which do 
                   3413: # not exceed $resizewidth and $resizeheight.
                   3414:  
1.984     neumanie 3415: sub resizeImage {
1.1051    raeburn  3416:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3417:     my $ima = Image::Magick->new;
                   3418:     my $resized;
                   3419:     if (-e $img_path) {
                   3420:         $ima->Read($img_path);
                   3421:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3422:             my $width = $ima->Get('width');
                   3423:             my $height = $ima->Get('height');
                   3424:             if ($width > $resizewidth) {
                   3425: 	        my $factor = $width/$resizewidth;
                   3426:                 my $newheight = $height/$factor;
                   3427:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3428:                 $resized = 1;
                   3429:             }
                   3430:         }
                   3431:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3432:             my $width = $ima->Get('width');
                   3433:             my $height = $ima->Get('height');
                   3434:             if ($height > $resizeheight) {
                   3435:                 my $factor = $height/$resizeheight;
                   3436:                 my $newwidth = $width/$factor;
                   3437:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3438:                 $resized = 1;
                   3439:             }
                   3440:         }
                   3441:         if ($resized) {
                   3442:             $ima->Write($img_path);
                   3443:         }
                   3444:     }
                   3445:     return;
1.977     amueller 3446: }
                   3447: 
1.608     albertel 3448: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3449: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3450: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3451: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3452: #                                    canceloverwrite, or ''. 
                   3453: #                   if 'coursedoc': upload to the current course
                   3454: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3455: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3456: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3457: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3458: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3459: #        $allfiles - reference to hash for embedded objects
                   3460: #        $codebase - reference to hash for codebase of java objects
                   3461: #        $desuname - username for permanent storage of uploaded file
                   3462: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3463: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3464: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3465: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3466: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3467: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3468: #                    from File::MMagic.
1.858     raeburn  3469: # 
1.686     albertel 3470: # output: url of file in userspace, or error: <message> 
                   3471: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3472: 
1.531     albertel 3473: sub userfileupload {
1.1090    raeburn  3474:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3475:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3476:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3477:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3478:     $fname=&clean_filename($fname);
1.1090    raeburn  3479:     # See if there is anything left
1.257     www      3480:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3481:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3482:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3483:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3484:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3485:         my $now = time;
1.1090    raeburn  3486:         my $filepath;
1.1095    raeburn  3487:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3488:              $filepath = 'tmp/helprequests/'.$now;
                   3489:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3490:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3491:                          '_'.$env{'user.domain'}.'/pending';
                   3492:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3493:             my ($docuname,$docudom);
                   3494:             if ($destudom) {
                   3495:                 $docudom = $destudom;
                   3496:             } else {
                   3497:                 $docudom = $env{'user.domain'};
                   3498:             }
                   3499:             if ($destuname) {
                   3500:                 $docuname = $destuname;
                   3501:             } else {
                   3502:                 $docuname = $env{'user.name'};
                   3503:             }
                   3504:             if (exists($env{'form.group'})) {
                   3505:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3506:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3507:             }
                   3508:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3509:             if ($context eq 'canceloverwrite') {
                   3510:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3511:                 if (-e  $tempfile) {
                   3512:                     my @info = stat($tempfile);
                   3513:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3514:                         unlink($tempfile);
                   3515:                     }
                   3516:                 }
                   3517:                 return;
1.523     raeburn  3518:             }
                   3519:         }
1.1090    raeburn  3520:         # Create the directory if not present
1.741     raeburn  3521:         my @parts=split(/\//,$filepath);
                   3522:         my $fullpath = $perlvar{'lonDaemons'};
                   3523:         for (my $i=0;$i<@parts;$i++) {
                   3524:             $fullpath .= '/'.$parts[$i];
                   3525:             if ((-e $fullpath)!=1) {
                   3526:                 mkdir($fullpath,0777);
                   3527:             }
                   3528:         }
                   3529:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3530:         print $fh $env{'form.'.$formname};
                   3531:         close($fh);
1.1090    raeburn  3532:         if ($context eq 'existingfile') {
                   3533:             my @info = stat($fullpath.'/'.$fname);
                   3534:             return ($fullpath.'/'.$fname,$info[9]);
                   3535:         } else {
                   3536:             return $fullpath.'/'.$fname;
                   3537:         }
1.523     raeburn  3538:     }
1.995     raeburn  3539:     if ($subdir eq 'scantron') {
                   3540:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3541:     } else {
1.995     raeburn  3542:         $fname="$subdir/$fname";
                   3543:     }
1.1090    raeburn  3544:     if ($context eq 'coursedoc') {
1.638     albertel 3545: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3546: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3547:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3548:             return &finishuserfileupload($docuname,$docudom,
                   3549: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3550: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3551:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3552:         } else {
1.1218    raeburn  3553:             if ($env{'form.folder'}) {
                   3554:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3555:             }
1.638     albertel 3556:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3557: 				       $fname,$formname,$parser,
1.1095    raeburn  3558: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3559:         }
1.719     banghart 3560:     } elsif (defined($destuname)) {
                   3561:         my $docuname=$destuname;
                   3562:         my $docudom=$destudom;
1.860     raeburn  3563: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3564: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3565:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3566:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3567:     } else {
1.638     albertel 3568:         my $docuname=$env{'user.name'};
                   3569:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3570:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3571:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3572:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3573:         }
1.860     raeburn  3574: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3575: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3576:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3577:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3578:     }
1.271     www      3579: }
                   3580: 
                   3581: sub finishuserfileupload {
1.860     raeburn  3582:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3583:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3584:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3585:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3586:   
1.860     raeburn  3587:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3588:     $file=$fname;
                   3589:     if ($fname=~m|/|) {
                   3590:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3591: 	$path.=$fnamepath.'/';
                   3592:     }
1.259     www      3593:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3594:     my $count;
                   3595:     for ($count=4;$count<=$#parts;$count++) {
                   3596:         $filepath.="/$parts[$count]";
                   3597:         if ((-e $filepath)!=1) {
                   3598: 	    mkdir($filepath,0777);
                   3599:         }
                   3600:     }
1.984     neumanie 3601: 
1.258     www      3602: # Save the file
                   3603:     {
1.701     albertel 3604: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3605: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3606: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3607: 	    return '/adm/notfound.html';
                   3608: 	}
1.1090    raeburn  3609:         if ($context eq 'overwrite') {
1.1117    foxr     3610:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3611:             my $target = $filepath.'/'.$file;
                   3612:             if (-e $source) {
                   3613:                 my @info = stat($source);
                   3614:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3615:                     unless (&File::Copy::move($source,$target)) {
                   3616:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3617:                         return "Moving from $source failed";
                   3618:                     }
                   3619:                 } else {
                   3620:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3621:                 }
                   3622:             } else {
                   3623:                 return "Temporary file: $source missing";
                   3624:             }
                   3625:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3626: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3627: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3628: 	    return '/adm/notfound.html';
                   3629: 	}
1.570     albertel 3630: 	close(FH);
1.1051    raeburn  3631:         if ($resizewidth && $resizeheight) {
                   3632:             my $mm = new File::MMagic;
                   3633:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3634:             if ($mime_type =~ m{^image/}) {
                   3635: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3636:             }  
1.977     amueller 3637: 	}
1.258     www      3638:     }
1.1152    raeburn  3639:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3640:         if (ref($mimetype)) {
                   3641:             if ($$mimetype eq '') {
                   3642:                 my $mm = new File::MMagic;
                   3643:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3644:                 $$mimetype = $type;
                   3645:             }
                   3646:         }
                   3647:     }
1.637     raeburn  3648:     if ($parser eq 'parse') {
1.1152    raeburn  3649:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3650:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3651:                                                        $allfiles,$codebase);
                   3652:             unless ($parse_result eq 'ok') {
                   3653:                 &logthis('Failed to parse '.$filepath.$file.
                   3654: 	   	         ' for embedded media: '.$parse_result); 
                   3655:             }
1.637     raeburn  3656:         }
                   3657:     }
1.860     raeburn  3658:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3659:         my $input = $filepath.'/'.$file;
                   3660:         my $output = $filepath.'/'.'tn-'.$file;
                   3661:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3662:         system("convert -sample $thumbsize $input $output");
                   3663:         if (-e $filepath.'/'.'tn-'.$file) {
                   3664:             $fetchthumb  = 1; 
                   3665:         }
                   3666:     }
1.858     raeburn  3667:  
1.259     www      3668: # Notify homeserver to grep it
                   3669: #
1.984     neumanie 3670:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3671:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3672:     if ($fetchresult eq 'ok') {
1.860     raeburn  3673:         if ($fetchthumb) {
                   3674:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3675:             if ($thumbresult ne 'ok') {
                   3676:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3677:                          $docuhome.': '.$thumbresult);
                   3678:             }
                   3679:         }
1.259     www      3680: #
1.258     www      3681: # Return the URL to it
1.494     albertel 3682:         return '/uploaded/'.$path.$file;
1.263     www      3683:     } else {
1.494     albertel 3684:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3685: 		 ': '.$fetchresult);
1.263     www      3686:         return '/adm/notfound.html';
1.858     raeburn  3687:     }
1.493     albertel 3688: }
                   3689: 
1.637     raeburn  3690: sub extract_embedded_items {
1.961     raeburn  3691:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3692:     my @state = ();
1.1164    raeburn  3693:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3694:     my %javafiles = (
                   3695:                       codebase => '',
                   3696:                       code => '',
                   3697:                       archive => ''
                   3698:                     );
                   3699:     my %mediafiles = (
                   3700:                       src => '',
                   3701:                       movie => '',
                   3702:                      );
1.648     raeburn  3703:     my $p;
                   3704:     if ($content) {
                   3705:         $p = HTML::LCParser->new($content);
                   3706:     } else {
1.961     raeburn  3707:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3708:     }
1.641     albertel 3709:     while (my $t=$p->get_token()) {
1.640     albertel 3710: 	if ($t->[0] eq 'S') {
                   3711: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3712: 	    push(@state, $tagname);
1.648     raeburn  3713:             if (lc($tagname) eq 'allow') {
                   3714:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3715:             }
1.640     albertel 3716: 	    if (lc($tagname) eq 'img') {
                   3717: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3718: 	    }
1.886     albertel 3719: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3720:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3721:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3722:                 }
1.886     albertel 3723: 	    }
1.645     raeburn  3724:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3725:                 my $src;
1.645     raeburn  3726:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3727:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3728:                 } else {
1.1164    raeburn  3729:                     if ($attr->{'src'} ne '') {
                   3730:                         $src = $attr->{'src'};
                   3731:                         &add_filetype($allfiles,$src,'src');
                   3732:                     }
                   3733:                 }
                   3734:                 my $text = $p->get_trimmed_text();
                   3735:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3736:                     my @swfargs = split(/,/,$1);
                   3737:                     foreach my $item (@swfargs) {
                   3738:                         $item =~ s/["']//g;
                   3739:                         $item =~ s/^\s+//;
                   3740:                         $item =~ s/\s+$//;
                   3741:                     }
                   3742:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3743:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3744:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3745:                         } else {
                   3746:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3747:                         }
                   3748:                     }
1.645     raeburn  3749:                 }
                   3750:             }
                   3751:             if (lc($tagname) eq 'link') {
                   3752:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3753:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3754:                 }
                   3755:             }
1.640     albertel 3756: 	    if (lc($tagname) eq 'object' ||
                   3757: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3758: 		foreach my $item (keys(%javafiles)) {
                   3759: 		    $javafiles{$item} = '';
                   3760: 		}
1.1164    raeburn  3761:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3762:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3763:                 }
1.640     albertel 3764: 	    }
                   3765: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3766: 		my $name = lc($attr->{'name'});
                   3767: 		foreach my $item (keys(%javafiles)) {
                   3768: 		    if ($name eq $item) {
                   3769: 			$javafiles{$item} = $attr->{'value'};
                   3770: 			last;
                   3771: 		    }
                   3772: 		}
1.1164    raeburn  3773:                 my $pathfrom;
1.640     albertel 3774: 		foreach my $item (keys(%mediafiles)) {
                   3775: 		    if ($name eq $item) {
1.1164    raeburn  3776:                         $pathfrom = $attr->{'value'};
                   3777:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3778: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3779: 			last;
                   3780: 		    }
                   3781: 		}
1.1164    raeburn  3782:                 if ($name eq 'flashvars') {
                   3783:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3784:                 }
                   3785:                 if ($pathfrom ne '') {
                   3786:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3787:                                          $pathfrom);
                   3788:                 }
1.640     albertel 3789: 	    }
                   3790: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3791: 		foreach my $item (keys(%javafiles)) {
                   3792: 		    if ($attr->{$item}) {
                   3793: 			$javafiles{$item} = $attr->{$item};
                   3794: 			last;
                   3795: 		    }
                   3796: 		}
                   3797: 		foreach my $item (keys(%mediafiles)) {
                   3798: 		    if ($attr->{$item}) {
                   3799: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3800: 			last;
                   3801: 		    }
                   3802: 		}
1.1164    raeburn  3803:                 if (lc($tagname) eq 'embed') {
                   3804:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3805:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3806:                                              $attr->{'src'});
                   3807:                     }
                   3808:                 }
1.640     albertel 3809: 	    }
1.1243    raeburn  3810:             if (lc($tagname) eq 'iframe') {
                   3811:                 my $src = $attr->{'src'} ;
                   3812:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3813:                     &add_filetype($allfiles,$src,'src');
                   3814:                 } elsif ($src =~ m{^/}) {
                   3815:                     if ($env{'request.course.id'}) {
                   3816:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3817:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3818:                         my $url = &hreflocation('',$fullpath);
                   3819:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3820:                             my $relpath = $1;
                   3821:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3822:                                 &add_filetype($allfiles,$1,'src');
                   3823:                             }
                   3824:                         }
                   3825:                     }
                   3826:                 }
                   3827:             }
1.1164    raeburn  3828:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3829:                 pop(@state);
1.1164    raeburn  3830:             }
1.640     albertel 3831: 	} elsif ($t->[0] eq 'E') {
                   3832: 	    my ($tagname) = ($t->[1]);
                   3833: 	    if ($javafiles{'codebase'} ne '') {
                   3834: 		$javafiles{'codebase'} .= '/';
                   3835: 	    }  
                   3836: 	    if (lc($tagname) eq 'applet' ||
                   3837: 		lc($tagname) eq 'object' ||
                   3838: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3839: 		) {
                   3840: 		foreach my $item (keys(%javafiles)) {
                   3841: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3842: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3843: 			&add_filetype($allfiles,$file,$item);
                   3844: 		    }
                   3845: 		}
                   3846: 	    } 
                   3847: 	    pop @state;
                   3848: 	}
                   3849:     }
1.1164    raeburn  3850:     foreach my $id (sort(keys(%flashvars))) {
                   3851:         if ($shockwave{$id} ne '') {
                   3852:             my @pairs = split(/\&/,$flashvars{$id});
                   3853:             foreach my $pair (@pairs) {
                   3854:                 my ($key,$value) = split(/\=/,$pair);
                   3855:                 if ($key eq 'thumb') {
                   3856:                     &add_filetype($allfiles,$value,$key);
                   3857:                 } elsif ($key eq 'content') {
                   3858:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3859:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3860:                     if ($ext ne '') {
                   3861:                         &add_filetype($allfiles,$path.$value,$ext);
                   3862:                     }
                   3863:                 }
                   3864:             }
                   3865:         }
                   3866:     }
1.637     raeburn  3867:     return 'ok';
                   3868: }
                   3869: 
1.639     albertel 3870: sub add_filetype {
                   3871:     my ($allfiles,$file,$type)=@_;
                   3872:     if (exists($allfiles->{$file})) {
                   3873: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3874: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3875: 	}
                   3876:     } else {
                   3877: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3878:     }
                   3879: }
                   3880: 
1.1164    raeburn  3881: sub embedded_dependency {
                   3882:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3883:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3884:         if (($identifier ne '') &&
                   3885:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3886:             ($pathfrom ne '')) {
                   3887:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3888:             foreach my $dep (@{$related->{$identifier}}) {
                   3889:                 &add_filetype($allfiles,$path.$dep,'object');
                   3890:             }
                   3891:         }
                   3892:     }
                   3893:     return;
                   3894: }
                   3895: 
1.493     albertel 3896: sub removeuploadedurl {
1.984     neumanie 3897:     my ($url)=@_;	
                   3898:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3899:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3900: }
                   3901: 
                   3902: sub removeuserfile {
                   3903:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3904:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3905:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3906:     if ($result eq 'ok') {	
1.798     raeburn  3907:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3908:             my $metafile = $fname.'.meta';
                   3909:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3910: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3911:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3912:             my $sqlresult = 
1.823     albertel 3913:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3914:                                         'portfolio_metadata',$group,
                   3915:                                         'delete');
1.798     raeburn  3916:         }
                   3917:     }
                   3918:     return $result;
1.257     www      3919: }
1.15      www      3920: 
1.530     albertel 3921: sub mkdiruserfile {
                   3922:     my ($docuname,$docudom,$dir)=@_;
                   3923:     my $home=&homeserver($docuname,$docudom);
                   3924:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3925: }
                   3926: 
1.531     albertel 3927: sub renameuserfile {
                   3928:     my ($docuname,$docudom,$old,$new)=@_;
                   3929:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3930:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3931:                         &escape("$old").':'.&escape("$new"),$home);
                   3932:     if ($result eq 'ok') {
                   3933:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3934:             my $oldmeta = $old.'.meta';
                   3935:             my $newmeta = $new.'.meta';
                   3936:             my $metaresult = 
                   3937:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3938: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3939:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3940:             my $sqlresult = 
1.823     albertel 3941:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3942:                                         'portfolio_metadata',$group,
                   3943:                                         'delete');
1.798     raeburn  3944:         }
                   3945:     }
                   3946:     return $result;
1.531     albertel 3947: }
                   3948: 
1.14      www      3949: # ------------------------------------------------------------------------- Log
                   3950: 
                   3951: sub log {
                   3952:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3953:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3954: }
                   3955: 
                   3956: # ------------------------------------------------------------------ Course Log
1.352     www      3957: #
                   3958: # This routine flushes several buffers of non-mission-critical nature
                   3959: #
1.157     www      3960: 
                   3961: sub flushcourselogs {
1.352     www      3962:     &logthis('Flushing log buffers');
                   3963: #
                   3964: # course logs
                   3965: # This is a log of all transactions in a course, which can be used
                   3966: # for data mining purposes
                   3967: #
                   3968: # It also collects the courseid database, which lists last transaction
                   3969: # times and course titles for all courseids
                   3970: #
                   3971:     my %courseidbuffer=();
1.921     raeburn  3972:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3973:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3974: 		          &escape($courselogs{$crsid}),
                   3975: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3976: 	    delete $courselogs{$crsid};
                   3977:         } else {
                   3978:             &logthis('Failed to flush log buffer for '.$crsid);
                   3979:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3980:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3981:                         " exceeded maximum size, deleting.</font>");
                   3982:                delete $courselogs{$crsid};
                   3983:             }
1.352     www      3984:         }
1.920     raeburn  3985:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3986:             'description' => $coursedescrbuf{$crsid},
                   3987:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3988:             'type'        => $coursetypebuf{$crsid},
                   3989:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3990:         };
1.191     harris41 3991:     }
1.352     www      3992: #
                   3993: # Write course id database (reverse lookup) to homeserver of courses 
                   3994: # Is used in pickcourse
                   3995: #
1.840     albertel 3996:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3997:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3998:                                     $courseidbuffer{$crs_home},
                   3999:                                     $crs_home,'timeonly');
1.352     www      4000:     }
                   4001: #
                   4002: # File accesses
                   4003: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4004: #
1.449     matthew  4005:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4006:         if ($entry =~ /___count$/) {
                   4007:             my ($dom,$name);
1.807     albertel 4008:             ($dom,$name,undef)=
1.811     albertel 4009: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4010:             if (! defined($dom) || $dom eq '' || 
                   4011:                 ! defined($name) || $name eq '') {
1.620     albertel 4012:                 my $cid = $env{'request.course.id'};
                   4013:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4014:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4015:             }
1.450     matthew  4016:             my $value = $accesshash{$entry};
                   4017:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4018:             my %temphash=($url => $value);
1.449     matthew  4019:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4020:             if ($result eq 'ok') {
                   4021:                 delete $accesshash{$entry};
                   4022:             }
                   4023:         } else {
1.811     albertel 4024:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4025:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4026:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4027:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4028:                 delete $accesshash{$entry};
                   4029:             }
1.185     www      4030:         }
1.191     harris41 4031:     }
1.352     www      4032: #
                   4033: # Roles
                   4034: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4035: #
1.800     albertel 4036:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4037:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4038: 	    split(/\:/,$entry);
                   4039:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4040:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4041:                 $rudom,$runame) eq 'ok') {
                   4042: 	    delete $userrolehash{$entry};
                   4043:         }
                   4044:     }
1.662     raeburn  4045: #
                   4046: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   4047: #
                   4048:     my %domrolebuffer = ();
1.1000    raeburn  4049:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4050:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4051:         if ($domrolebuffer{$rudom}) {
                   4052:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4053:                       '='.&escape($domainrolehash{$entry});
                   4054:         } else {
                   4055:             $domrolebuffer{$rudom}.=&escape($entry).
                   4056:                       '='.&escape($domainrolehash{$entry});
                   4057:         }
                   4058:         delete $domainrolehash{$entry};
                   4059:     }
                   4060:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 4061: 	my %servers = &get_servers($dom,'library');
                   4062: 	foreach my $tryserver (keys(%servers)) {
                   4063: 	    unless (&reply('domroleput:'.$dom.':'.
                   4064: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4065: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4066: 	    }
1.662     raeburn  4067:         }
                   4068:     }
1.186     www      4069:     $dumpcount++;
1.157     www      4070: }
                   4071: 
                   4072: sub courselog {
                   4073:     my $what=shift;
1.158     www      4074:     $what=time.':'.$what;
1.620     albertel 4075:     unless ($env{'request.course.id'}) { return ''; }
                   4076:     $coursedombuf{$env{'request.course.id'}}=
                   4077:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4078:     $coursenumbuf{$env{'request.course.id'}}=
                   4079:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4080:     $coursehombuf{$env{'request.course.id'}}=
                   4081:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4082:     $coursedescrbuf{$env{'request.course.id'}}=
                   4083:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4084:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4085:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4086:     $courseownerbuf{$env{'request.course.id'}}=
                   4087:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4088:     $coursetypebuf{$env{'request.course.id'}}=
                   4089:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4090:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4091: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4092:     } else {
1.620     albertel 4093: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4094:     }
1.620     albertel 4095:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4096: 	&flushcourselogs();
                   4097:     }
1.158     www      4098: }
                   4099: 
                   4100: sub courseacclog {
                   4101:     my $fnsymb=shift;
1.620     albertel 4102:     unless ($env{'request.course.id'}) { return ''; }
                   4103:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4104:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4105:         $what.=':POST';
1.583     matthew  4106:         # FIXME: Probably ought to escape things....
1.800     albertel 4107: 	foreach my $key (keys(%env)) {
                   4108:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4109:                 my $formitem = $1;
                   4110:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4111:                     $what.=':'.$formitem.'='.$env{$key};
                   4112:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4113:                     $what.=':'.$formitem.'='.$env{$key};
                   4114:                 }
1.158     www      4115:             }
1.191     harris41 4116:         }
1.583     matthew  4117:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4118:         # FIXME: We should not be depending on a form parameter that someone
                   4119:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4120:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4121:             $what.= ':POST';
                   4122:             # FIXME: Probably ought to escape things....
                   4123:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4124:                                  'crsdiscuss') {
1.620     albertel 4125:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4126:             }
                   4127:         }
1.158     www      4128:     }
                   4129:     &courselog($what);
1.149     www      4130: }
                   4131: 
1.185     www      4132: sub countacc {
                   4133:     my $url=&declutter(shift);
1.458     matthew  4134:     return if (! defined($url) || $url eq '');
1.620     albertel 4135:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4136: #
                   4137: # Mark that this url was used in this course
                   4138: #
1.620     albertel 4139:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4140: #
                   4141: # Increase the access count for this resource in this child process
                   4142: #
1.281     www      4143:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4144:     $accesshash{$key}++;
1.185     www      4145: }
1.349     www      4146: 
1.361     www      4147: sub linklog {
                   4148:     my ($from,$to)=@_;
                   4149:     $from=&declutter($from);
                   4150:     $to=&declutter($to);
                   4151:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4152:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4153: }
1.1160    www      4154: 
                   4155: sub statslog {
                   4156:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4157:     if ($users<2) { return; }
                   4158:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4159:             'course'       => $env{'request.course.id'},
                   4160:             'sections'     => '"all"',
                   4161:             'num_students' => $users,
                   4162:             'part'         => $part,
                   4163:             'symb'         => $symb,
                   4164:             'mean_tries'   => $av_attempts,
                   4165:             'deg_of_diff'  => $degdiff});
                   4166:     foreach my $key (keys(%dynstore)) {
                   4167:         $accesshash{$key}=$dynstore{$key};
                   4168:     }
                   4169: }
1.361     www      4170:   
1.349     www      4171: sub userrolelog {
                   4172:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4173:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4174:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4175:        $userrolehash
                   4176:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4177:                     =$tend.':'.$tstart;
1.662     raeburn  4178:     }
1.1169    droeschl 4179:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4180:        $userrolehash
                   4181:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4182:                     =$tend.':'.$tstart;
                   4183:     }
1.1169    droeschl 4184:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4185:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4186:        $domainrolehash
                   4187:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4188:                     = $tend.':'.$tstart;
                   4189:     }
1.351     www      4190: }
                   4191: 
1.957     raeburn  4192: sub courserolelog {
                   4193:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4194:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4195:         my $cdom = $1;
                   4196:         my $cnum = $2;
                   4197:         my $sec = $3;
                   4198:         my $namespace = 'rolelog';
                   4199:         my %storehash = (
                   4200:                            role    => $trole,
                   4201:                            start   => $tstart,
                   4202:                            end     => $tend,
                   4203:                            selfenroll => $selfenroll,
                   4204:                            context    => $context,
                   4205:                         );
                   4206:         if ($trole eq 'gr') {
                   4207:             $namespace = 'groupslog';
                   4208:             $storehash{'group'} = $sec;
                   4209:         } else {
                   4210:             $storehash{'section'} = $sec;
                   4211:         }
1.1188    raeburn  4212:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4213:                    $domain,$cnum,$cdom);
1.1184    raeburn  4214:         if (($trole ne 'st') || ($sec ne '')) {
                   4215:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4216:         }
                   4217:     }
                   4218:     return;
                   4219: }
                   4220: 
1.1184    raeburn  4221: sub domainrolelog {
                   4222:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4223:     if ($area =~ m{^/($match_domain)/$}) {
                   4224:         my $cdom = $1;
                   4225:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4226:         my $namespace = 'rolelog';
                   4227:         my %storehash = (
                   4228:                            role    => $trole,
                   4229:                            start   => $tstart,
                   4230:                            end     => $tend,
                   4231:                            context => $context,
                   4232:                         );
1.1188    raeburn  4233:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4234:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4235:     }
                   4236:     return;
                   4237: 
                   4238: }
                   4239: 
                   4240: sub coauthorrolelog {
                   4241:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4242:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4243:         my $audom = $1;
                   4244:         my $auname = $2;
                   4245:         my $namespace = 'rolelog';
                   4246:         my %storehash = (
                   4247:                            role    => $trole,
                   4248:                            start   => $tstart,
                   4249:                            end     => $tend,
                   4250:                            context => $context,
                   4251:                         );
1.1188    raeburn  4252:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4253:                    $domain,$auname,$audom);
1.1184    raeburn  4254:     }
                   4255:     return;
                   4256: }
                   4257: 
1.351     www      4258: sub get_course_adv_roles {
1.948     raeburn  4259:     my ($cid,$codes) = @_;
1.620     albertel 4260:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4261:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4262:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4263:     my %nothide=();
1.800     albertel 4264:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4265:         if ($user !~ /:/) {
                   4266: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4267:         } else {
                   4268:             $nothide{$user}=1;
                   4269:         }
1.470     www      4270:     }
1.1219    raeburn  4271:     my @possdoms = ($coursehash{'domain'});
                   4272:     if ($coursehash{'checkforpriv'}) {
                   4273:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4274:     }
1.351     www      4275:     my %returnhash=();
                   4276:     my %dumphash=
                   4277:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4278:     my $now=time;
1.997     raeburn  4279:     my %privileged;
1.1000    raeburn  4280:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4281: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4282:         if (($tstart) && ($tstart<0)) { next; }
                   4283:         if (($tend) && ($tend<$now)) { next; }
                   4284:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4285:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4286: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4287:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4288:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4289: 	if ($role eq 'cr') { next; }
1.948     raeburn  4290:         if ($codes) {
                   4291:             if ($section) { $role .= ':'.$section; }
                   4292:             if ($returnhash{$role}) {
                   4293:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4294:             } else {
                   4295:                 $returnhash{$role}=$username.':'.$domain;
                   4296:             }
1.351     www      4297:         } else {
1.988     raeburn  4298:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4299:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4300:             if ($returnhash{$key}) {
                   4301: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4302:             } else {
                   4303:                 $returnhash{$key}=$username.':'.$domain;
                   4304:             }
1.351     www      4305:         }
1.948     raeburn  4306:     }
1.400     www      4307:     return %returnhash;
                   4308: }
                   4309: 
                   4310: sub get_my_roles {
1.937     raeburn  4311:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4312:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4313:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4314:     my (%dumphash,%nothide);
1.1086    raeburn  4315:     if ($context eq 'userroles') {
1.1166    raeburn  4316:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4317:     } else {
1.1219    raeburn  4318:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4319:         if ($hidepriv) {
                   4320:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4321:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4322:                 if ($user !~ /:/) {
                   4323:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4324:                 } else {
                   4325:                     $nothide{$user} = 1;
                   4326:                 }
                   4327:             }
                   4328:         }
1.858     raeburn  4329:     }
1.400     www      4330:     my %returnhash=();
                   4331:     my $now=time;
1.999     raeburn  4332:     my %privileged;
1.800     albertel 4333:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4334:         my ($role,$tend,$tstart);
                   4335:         if ($context eq 'userroles') {
1.1149    raeburn  4336:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4337: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4338:         } else {
                   4339:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4340:         }
1.400     www      4341:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4342:         my $status = 'active';
1.939     raeburn  4343:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4344:             $status = 'previous';
                   4345:         } 
                   4346:         if (($tstart) && ($now<$tstart)) {
                   4347:             $status = 'future';
                   4348:         }
                   4349:         if (ref($types) eq 'ARRAY') {
                   4350:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4351:                 next;
                   4352:             } 
                   4353:         } else {
                   4354:             if ($status ne 'active') {
                   4355:                 next;
                   4356:             }
                   4357:         }
1.867     raeburn  4358:         my ($rolecode,$username,$domain,$section,$area);
                   4359:         if ($context eq 'userroles') {
1.1186    raeburn  4360:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4361:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4362:         } else {
                   4363:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4364:         }
1.832     raeburn  4365:         if (ref($roledoms) eq 'ARRAY') {
                   4366:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4367:                 next;
                   4368:             }
                   4369:         }
                   4370:         if (ref($roles) eq 'ARRAY') {
                   4371:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4372:                 if ($role =~ /^cr\//) {
                   4373:                     if (!grep(/^cr$/,@{$roles})) {
                   4374:                         next;
                   4375:                     }
1.1104    raeburn  4376:                 } elsif ($role =~ /^gr\//) {
                   4377:                     if (!grep(/^gr$/,@{$roles})) {
                   4378:                         next;
                   4379:                     }
1.922     raeburn  4380:                 } else {
                   4381:                     next;
                   4382:                 }
1.832     raeburn  4383:             }
1.867     raeburn  4384:         }
1.937     raeburn  4385:         if ($hidepriv) {
1.1219    raeburn  4386:             my @privroles = ('dc','su');
1.999     raeburn  4387:             if ($context eq 'userroles') {
1.1219    raeburn  4388:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4389:             } else {
1.1219    raeburn  4390:                 my $possdoms = [$domain];
                   4391:                 if (ref($roledoms) eq 'ARRAY') {
                   4392:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4393:                 }
1.1219    raeburn  4394:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4395:                     if (!$nothide{$username.':'.$domain}) {
                   4396:                         next;
                   4397:                     }
                   4398:                 }
1.937     raeburn  4399:             }
                   4400:         }
1.933     raeburn  4401:         if ($withsec) {
                   4402:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4403:                 $tstart.':'.$tend;
                   4404:         } else {
                   4405:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4406:         }
1.832     raeburn  4407:     }
1.373     www      4408:     return %returnhash;
1.399     www      4409: }
                   4410: 
                   4411: # ----------------------------------------------------- Frontpage Announcements
                   4412: #
                   4413: #
                   4414: 
                   4415: sub postannounce {
                   4416:     my ($server,$text)=@_;
1.844     albertel 4417:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4418:     unless ($text=~/\w/) { $text=''; }
                   4419:     return &reply('setannounce:'.&escape($text),$server);
                   4420: }
                   4421: 
                   4422: sub getannounce {
1.448     albertel 4423: 
                   4424:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4425: 	my $announcement='';
1.800     albertel 4426: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4427: 	close($fh);
1.399     www      4428: 	if ($announcement=~/\w/) { 
                   4429: 	    return 
                   4430:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4431:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4432: 	} else {
                   4433: 	    return '';
                   4434: 	}
                   4435:     } else {
                   4436: 	return '';
                   4437:     }
1.351     www      4438: }
1.353     www      4439: 
                   4440: # ---------------------------------------------------------- Course ID routines
                   4441: # Deal with domain's nohist_courseid.db files
                   4442: #
                   4443: 
                   4444: sub courseidput {
1.921     raeburn  4445:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4446:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4447:     my $outcome;
                   4448:     if ($caller eq 'timeonly') {
                   4449:         my $cids = '';
                   4450:         foreach my $item (keys(%$storehash)) {
                   4451:             $cids.=&escape($item).'&';
                   4452:         }
                   4453:         $cids=~s/\&$//;
                   4454:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4455:                           $coursehome);       
                   4456:     } else {
                   4457:         my $items = '';
                   4458:         foreach my $item (keys(%$storehash)) {
                   4459:             $items.= &escape($item).'='.
                   4460:                      &freeze_escape($$storehash{$item}).'&';
                   4461:         }
                   4462:         $items=~s/\&$//;
                   4463:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4464:                           $coursehome);
1.918     raeburn  4465:     }
                   4466:     if ($outcome eq 'unknown_cmd') {
                   4467:         my $what;
                   4468:         foreach my $cid (keys(%$storehash)) {
                   4469:             $what .= &escape($cid).'=';
1.921     raeburn  4470:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4471:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4472:             }
                   4473:             $what =~ s/\:$/&/;
                   4474:         }
                   4475:         $what =~ s/\&$//;  
                   4476:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4477:     } else {
                   4478:         return $outcome;
                   4479:     }
1.353     www      4480: }
                   4481: 
                   4482: sub courseiddump {
1.921     raeburn  4483:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4484:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4485:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4486:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4487:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4488:     my $as_hash = 1;
                   4489:     my %returnhash;
                   4490:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4491:     my %libserv = &all_library();
                   4492:     foreach my $tryserver (keys(%libserv)) {
                   4493:         if ( (  $hostidflag == 1 
                   4494: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4495: 	     || (!defined($hostidflag)) ) {
                   4496: 
1.918     raeburn  4497: 	    if (($domfilter eq '') ||
                   4498: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4499:                 my $rep;
                   4500:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4501:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4502:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4503:                                 &escape($descfilter), &escape($instcodefilter), 
                   4504:                                 &escape($ownerfilter), &escape($coursefilter),
                   4505:                                 &escape($typefilter), &escape($regexp_ok), 
                   4506:                                 $as_hash, &escape($selfenrollonly), 
                   4507:                                 &escape($catfilter), $showhidden, $caller, 
                   4508:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4509:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4510:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4511:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4512:                 } else {
                   4513:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4514:                              $sincefilter.':'.&escape($descfilter).':'.
                   4515:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4516:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4517:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4518:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4519:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4520:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4521:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4522:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4523:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4524:                 }
                   4525:                      
1.918     raeburn  4526:                 my @pairs=split(/\&/,$rep);
                   4527:                 foreach my $item (@pairs) {
                   4528:                     my ($key,$value)=split(/\=/,$item,2);
                   4529:                     $key = &unescape($key);
                   4530:                     next if ($key =~ /^error: 2 /);
                   4531:                     my $result = &thaw_unescape($value);
                   4532:                     if (ref($result) eq 'HASH') {
                   4533:                         $returnhash{$key}=$result;
                   4534:                     } else {
1.921     raeburn  4535:                         my @responses = split(/:/,$value);
                   4536:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4537:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4538:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4539:                         }
1.1008    raeburn  4540:                     }
1.353     www      4541:                 }
                   4542:             }
                   4543:         }
                   4544:     }
                   4545:     return %returnhash;
                   4546: }
                   4547: 
1.1055    raeburn  4548: sub courselastaccess {
                   4549:     my ($cdom,$cnum,$hostidref) = @_;
                   4550:     my %returnhash;
                   4551:     if ($cdom && $cnum) {
                   4552:         my $chome = &homeserver($cnum,$cdom);
                   4553:         if ($chome ne 'no_host') {
                   4554:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4555:             &extract_lastaccess(\%returnhash,$rep);
                   4556:         }
                   4557:     } else {
                   4558:         if (!$cdom) { $cdom=''; }
                   4559:         my %libserv = &all_library();
                   4560:         foreach my $tryserver (keys(%libserv)) {
                   4561:             if (ref($hostidref) eq 'ARRAY') {
                   4562:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4563:             } 
                   4564:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4565:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4566:                 &extract_lastaccess(\%returnhash,$rep);
                   4567:             }
                   4568:         }
                   4569:     }
                   4570:     return %returnhash;
                   4571: }
                   4572: 
                   4573: sub extract_lastaccess {
                   4574:     my ($returnhash,$rep) = @_;
                   4575:     if (ref($returnhash) eq 'HASH') {
                   4576:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4577:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4578:                  $rep eq '') {
                   4579:             my @pairs=split(/\&/,$rep);
                   4580:             foreach my $item (@pairs) {
                   4581:                 my ($key,$value)=split(/\=/,$item,2);
                   4582:                 $key = &unescape($key);
                   4583:                 next if ($key =~ /^error: 2 /);
                   4584:                 $returnhash->{$key} = &thaw_unescape($value);
                   4585:             }
                   4586:         }
                   4587:     }
                   4588:     return;
                   4589: }
                   4590: 
1.658     raeburn  4591: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4592: 
                   4593: sub dcmailput {
1.685     raeburn  4594:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4595:     my $status = &Apache::lonnet::critical(
1.740     www      4596:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4597:        &escape($message),$server);
1.662     raeburn  4598:     return $status;
                   4599: }
                   4600: 
1.658     raeburn  4601: sub dcmaildump {
                   4602:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4603:     my %returnhash=();
1.846     albertel 4604: 
                   4605:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4606:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4607:                                                          &escape($enddate).':';
                   4608: 	my @esc_senders=map { &escape($_)} @$senders;
                   4609: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4610: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4611:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4612:             if (($key) && ($value)) {
                   4613:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4614:             }
                   4615:         }
                   4616:     }
                   4617:     return %returnhash;
                   4618: }
1.662     raeburn  4619: # ---------------------------------------------------------- Domain roles
                   4620: 
                   4621: sub get_domain_roles {
                   4622:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4623:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4624:         $startdate = '.';
                   4625:     }
1.1018    raeburn  4626:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4627:         $enddate = '.';
                   4628:     }
1.922     raeburn  4629:     my $rolelist;
                   4630:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4631:         $rolelist = join('&',@{$roles});
1.922     raeburn  4632:     }
1.662     raeburn  4633:     my %personnel = ();
1.841     albertel 4634: 
                   4635:     my %servers = &get_servers($dom,'library');
                   4636:     foreach my $tryserver (keys(%servers)) {
                   4637: 	%{$personnel{$tryserver}}=();
                   4638: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4639: 					    &escape($startdate).':'.
                   4640: 					    &escape($enddate).':'.
                   4641: 					    &escape($rolelist), $tryserver))) {
                   4642: 	    my ($key,$value) = split(/\=/,$line,2);
                   4643: 	    if (($key) && ($value)) {
                   4644: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4645: 	    }
                   4646: 	}
1.662     raeburn  4647:     }
                   4648:     return %personnel;
                   4649: }
1.658     raeburn  4650: 
1.1057    www      4651: # ----------------------------------------------------------- Interval timing 
1.149     www      4652: 
1.1153    www      4653: {
                   4654: # Caches needed for speedup of navmaps
                   4655: # We don't want to cache this for very long at all (5 seconds at most)
                   4656: # 
                   4657: # The user for whom we cache
                   4658: my $cachedkey='';
                   4659: # The cached times for this user
                   4660: my %cachedtimes=();
                   4661: # When this was last done
1.1282    raeburn  4662: my $cachedtime='';
1.1153    www      4663: 
                   4664: sub load_all_first_access {
1.1308    raeburn  4665:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4666:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4667:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4668:         (!$ignorecache)) {
1.1154    raeburn  4669:         return;
                   4670:     }
                   4671:     $cachedtime=time;
                   4672:     $cachedkey=$uname.':'.$udom;
                   4673:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4674: }
                   4675: 
1.504     albertel 4676: sub get_first_access {
1.1308    raeburn  4677:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4678:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4679:     if ($argsymb) { $symb=$argsymb; }
                   4680:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4681:     if ($argmap) { $map = $argmap; }
1.926     albertel 4682:     if ($type eq 'course') {
                   4683: 	$res='course';
                   4684:     } elsif ($type eq 'map') {
1.588     albertel 4685: 	$res=&symbread($map);
                   4686:     } else {
                   4687: 	$res=$symb;
                   4688:     }
1.1308    raeburn  4689:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4690:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4691: }
                   4692: 
                   4693: sub set_first_access {
1.1162    raeburn  4694:     my ($type,$interval)=@_;
1.790     albertel 4695:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4696:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4697:     if ($type eq 'course') {
                   4698: 	$res='course';
                   4699:     } elsif ($type eq 'map') {
1.588     albertel 4700: 	$res=&symbread($map);
                   4701:     } else {
                   4702: 	$res=$symb;
                   4703:     }
1.1153    www      4704:     $cachedkey='';
1.1162    raeburn  4705:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4706:     if (!$firstaccess) {
1.1162    raeburn  4707:         my $start = time;
                   4708: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4709:                           $udom,$uname);
                   4710:         if ($putres eq 'ok') {
                   4711:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4712:                  $udom,$uname); 
                   4713:             &appenv(
                   4714:                      {
                   4715:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4716:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4717:                      }
                   4718:                   );
                   4719:         }
                   4720:         return $putres;
1.505     albertel 4721:     }
                   4722:     return 'already_set';
1.504     albertel 4723: }
1.1153    www      4724: }
1.1282    raeburn  4725: 
1.110     www      4726: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4727: 
                   4728: sub expirespread {
                   4729:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4730:     my $cid=$env{'request.course.id'}; 
1.110     www      4731:     if ($cid) {
                   4732:        my $now=time;
                   4733:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4734:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4735:                             $env{'course.'.$cid.'.num'}.
1.110     www      4736: 	        	    ':nohist_expirationdates:'.
                   4737:                             &escape($key).'='.$now,
1.620     albertel 4738:                             $env{'course.'.$cid.'.home'})
1.110     www      4739:     }
                   4740:     return 'ok';
1.14      www      4741: }
                   4742: 
1.109     www      4743: # ----------------------------------------------------- Devalidate Spreadsheets
                   4744: 
                   4745: sub devalidate {
1.325     www      4746:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4747:     my $cid=$env{'request.course.id'}; 
1.109     www      4748:     if ($cid) {
1.391     matthew  4749:         # delete the stored spreadsheets for
                   4750:         # - the student level sheet of this user in course's homespace
                   4751:         # - the assessment level sheet for this resource 
                   4752:         #   for this user in user's homespace
1.553     albertel 4753: 	# - current conditional state info
1.325     www      4754: 	my $key=$uname.':'.$udom.':';
1.109     www      4755:         my $status=
1.299     matthew  4756: 	    &del('nohist_calculatedsheets',
1.391     matthew  4757: 		 [$key.'studentcalc:'],
1.620     albertel 4758: 		 $env{'course.'.$cid.'.domain'},
                   4759: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4760: 		.' '.
                   4761: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4762: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4763:         unless ($status eq 'ok ok') {
                   4764:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4765:                     $uname.' at '.$udom.' for '.
1.109     www      4766: 		    $symb.': '.$status);
1.133     albertel 4767:         }
1.553     albertel 4768: 	&delenv('user.state.'.$cid);
1.109     www      4769:     }
                   4770: }
                   4771: 
1.265     albertel 4772: sub get_scalar {
                   4773:     my ($string,$end) = @_;
                   4774:     my $value;
                   4775:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4776: 	$value = $1;
                   4777:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4778: 	$value = $1;
                   4779:     }
                   4780:     return &unescape($value);
                   4781: }
                   4782: 
                   4783: sub array2str {
                   4784:   my (@array) = @_;
                   4785:   my $result=&arrayref2str(\@array);
                   4786:   $result=~s/^__ARRAY_REF__//;
                   4787:   $result=~s/__END_ARRAY_REF__$//;
                   4788:   return $result;
                   4789: }
                   4790: 
1.204     albertel 4791: sub arrayref2str {
                   4792:   my ($arrayref) = @_;
1.265     albertel 4793:   my $result='__ARRAY_REF__';
1.204     albertel 4794:   foreach my $elem (@$arrayref) {
1.265     albertel 4795:     if(ref($elem) eq 'ARRAY') {
                   4796:       $result.=&arrayref2str($elem).'&';
                   4797:     } elsif(ref($elem) eq 'HASH') {
                   4798:       $result.=&hashref2str($elem).'&';
                   4799:     } elsif(ref($elem)) {
                   4800:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4801:     } else {
                   4802:       $result.=&escape($elem).'&';
                   4803:     }
                   4804:   }
                   4805:   $result=~s/\&$//;
1.265     albertel 4806:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4807:   return $result;
                   4808: }
                   4809: 
1.168     albertel 4810: sub hash2str {
1.204     albertel 4811:   my (%hash) = @_;
                   4812:   my $result=&hashref2str(\%hash);
1.265     albertel 4813:   $result=~s/^__HASH_REF__//;
                   4814:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4815:   return $result;
                   4816: }
                   4817: 
                   4818: sub hashref2str {
                   4819:   my ($hashref)=@_;
1.265     albertel 4820:   my $result='__HASH_REF__';
1.800     albertel 4821:   foreach my $key (sort(keys(%$hashref))) {
                   4822:     if (ref($key) eq 'ARRAY') {
                   4823:       $result.=&arrayref2str($key).'=';
                   4824:     } elsif (ref($key) eq 'HASH') {
                   4825:       $result.=&hashref2str($key).'=';
                   4826:     } elsif (ref($key)) {
1.265     albertel 4827:       $result.='=';
1.800     albertel 4828:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4829:     } else {
1.1132    raeburn  4830: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4831:     }
                   4832: 
1.800     albertel 4833:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4834:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4835:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4836:       $result.=&hashref2str($hashref->{$key}).'&';
                   4837:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4838:        $result.='&';
1.800     albertel 4839:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4840:     } else {
1.800     albertel 4841:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4842:     }
                   4843:   }
1.168     albertel 4844:   $result=~s/\&$//;
1.265     albertel 4845:   $result .= '__END_HASH_REF__';
1.168     albertel 4846:   return $result;
                   4847: }
                   4848: 
                   4849: sub str2hash {
1.265     albertel 4850:     my ($string)=@_;
                   4851:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4852:     return %$hash;
                   4853: }
                   4854: 
                   4855: sub str2hashref {
1.168     albertel 4856:   my ($string) = @_;
1.265     albertel 4857: 
                   4858:   my %hash;
                   4859: 
                   4860:   if($string !~ /^__HASH_REF__/) {
                   4861:       if (! ($string eq '' || !defined($string))) {
                   4862: 	  $hash{'error'}='Not hash reference';
                   4863:       }
                   4864:       return (\%hash, $string);
                   4865:   }
                   4866: 
                   4867:   $string =~ s/^__HASH_REF__//;
                   4868: 
                   4869:   while($string !~ /^__END_HASH_REF__/) {
                   4870:       #key
                   4871:       my $key='';
                   4872:       if($string =~ /^__HASH_REF__/) {
                   4873:           ($key, $string)=&str2hashref($string);
                   4874:           if(defined($key->{'error'})) {
                   4875:               $hash{'error'}='Bad data';
                   4876:               return (\%hash, $string);
                   4877:           }
                   4878:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4879:           ($key, $string)=&str2arrayref($string);
                   4880:           if($key->[0] eq 'Array reference error') {
                   4881:               $hash{'error'}='Bad data';
                   4882:               return (\%hash, $string);
                   4883:           }
                   4884:       } else {
                   4885:           $string =~ s/^(.*?)=//;
1.267     albertel 4886: 	  $key=&unescape($1);
1.265     albertel 4887:       }
                   4888:       $string =~ s/^=//;
                   4889: 
                   4890:       #value
                   4891:       my $value='';
                   4892:       if($string =~ /^__HASH_REF__/) {
                   4893:           ($value, $string)=&str2hashref($string);
                   4894:           if(defined($value->{'error'})) {
                   4895:               $hash{'error'}='Bad data';
                   4896:               return (\%hash, $string);
                   4897:           }
                   4898:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4899:           ($value, $string)=&str2arrayref($string);
                   4900:           if($value->[0] eq 'Array reference error') {
                   4901:               $hash{'error'}='Bad data';
                   4902:               return (\%hash, $string);
                   4903:           }
                   4904:       } else {
                   4905: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4906:       }
                   4907:       $string =~ s/^&//;
                   4908: 
                   4909:       $hash{$key}=$value;
1.204     albertel 4910:   }
1.265     albertel 4911: 
                   4912:   $string =~ s/^__END_HASH_REF__//;
                   4913: 
                   4914:   return (\%hash, $string);
1.204     albertel 4915: }
                   4916: 
                   4917: sub str2array {
1.265     albertel 4918:     my ($string)=@_;
                   4919:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4920:     return @$array;
                   4921: }
                   4922: 
                   4923: sub str2arrayref {
1.204     albertel 4924:   my ($string) = @_;
1.265     albertel 4925:   my @array;
                   4926: 
                   4927:   if($string !~ /^__ARRAY_REF__/) {
                   4928:       if (! ($string eq '' || !defined($string))) {
                   4929: 	  $array[0]='Array reference error';
                   4930:       }
                   4931:       return (\@array, $string);
                   4932:   }
                   4933: 
                   4934:   $string =~ s/^__ARRAY_REF__//;
                   4935: 
                   4936:   while($string !~ /^__END_ARRAY_REF__/) {
                   4937:       my $value='';
                   4938:       if($string =~ /^__HASH_REF__/) {
                   4939:           ($value, $string)=&str2hashref($string);
                   4940:           if(defined($value->{'error'})) {
                   4941:               $array[0] ='Array reference error';
                   4942:               return (\@array, $string);
                   4943:           }
                   4944:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4945:           ($value, $string)=&str2arrayref($string);
                   4946:           if($value->[0] eq 'Array reference error') {
                   4947:               $array[0] ='Array reference error';
                   4948:               return (\@array, $string);
                   4949:           }
                   4950:       } else {
                   4951: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4952:       }
                   4953:       $string =~ s/^&//;
                   4954: 
                   4955:       push(@array, $value);
1.191     harris41 4956:   }
1.265     albertel 4957: 
                   4958:   $string =~ s/^__END_ARRAY_REF__//;
                   4959: 
                   4960:   return (\@array, $string);
1.168     albertel 4961: }
                   4962: 
1.167     albertel 4963: # -------------------------------------------------------------------Temp Store
                   4964: 
1.168     albertel 4965: sub tmpreset {
                   4966:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4967:   if (!$symb) {
                   4968:     $symb=&symbread();
1.620     albertel 4969:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4970:   }
                   4971:   $symb=escape($symb);
                   4972: 
1.620     albertel 4973:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4974:   $namespace=~s/\//\_/g;
                   4975:   $namespace=~s/\W//g;
                   4976: 
1.620     albertel 4977:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4978:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4979:   if ($domain eq 'public' && $stuname eq 'public') {
                   4980:       $stuname=$ENV{'REMOTE_ADDR'};
                   4981:   }
1.1117    foxr     4982:   my $path=LONCAPA::tempdir();
1.168     albertel 4983:   my %hash;
                   4984:   if (tie(%hash,'GDBM_File',
                   4985: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4986: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4987:     foreach my $key (keys(%hash)) {
1.180     albertel 4988:       if ($key=~ /:$symb/) {
1.168     albertel 4989: 	delete($hash{$key});
                   4990:       }
                   4991:     }
                   4992:   }
                   4993: }
                   4994: 
1.167     albertel 4995: sub tmpstore {
1.168     albertel 4996:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4997: 
                   4998:   if (!$symb) {
                   4999:     $symb=&symbread();
1.620     albertel 5000:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5001:   }
                   5002:   $symb=escape($symb);
                   5003: 
                   5004:   if (!$namespace) {
                   5005:     # I don't think we would ever want to store this for a course.
                   5006:     # it seems this will only be used if we don't have a course.
1.620     albertel 5007:     #$namespace=$env{'request.course.id'};
1.168     albertel 5008:     #if (!$namespace) {
1.620     albertel 5009:       $namespace=$env{'request.state'};
1.168     albertel 5010:     #}
                   5011:   }
                   5012:   $namespace=~s/\//\_/g;
                   5013:   $namespace=~s/\W//g;
1.620     albertel 5014:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5015:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5016:   if ($domain eq 'public' && $stuname eq 'public') {
                   5017:       $stuname=$ENV{'REMOTE_ADDR'};
                   5018:   }
1.168     albertel 5019:   my $now=time;
                   5020:   my %hash;
1.1117    foxr     5021:   my $path=LONCAPA::tempdir();
1.168     albertel 5022:   if (tie(%hash,'GDBM_File',
                   5023: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5024: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5025:     $hash{"version:$symb"}++;
                   5026:     my $version=$hash{"version:$symb"};
                   5027:     my $allkeys=''; 
                   5028:     foreach my $key (keys(%$storehash)) {
                   5029:       $allkeys.=$key.':';
1.591     albertel 5030:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5031:     }
                   5032:     $hash{"$version:$symb:timestamp"}=$now;
                   5033:     $allkeys.='timestamp';
                   5034:     $hash{"$version:keys:$symb"}=$allkeys;
                   5035:     if (untie(%hash)) {
                   5036:       return 'ok';
                   5037:     } else {
                   5038:       return "error:$!";
                   5039:     }
                   5040:   } else {
                   5041:     return "error:$!";
                   5042:   }
                   5043: }
1.167     albertel 5044: 
1.168     albertel 5045: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5046: 
1.168     albertel 5047: sub tmprestore {
                   5048:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5049: 
1.168     albertel 5050:   if (!$symb) {
                   5051:     $symb=&symbread();
1.620     albertel 5052:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5053:   }
                   5054:   $symb=escape($symb);
                   5055: 
1.620     albertel 5056:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5057: 
1.620     albertel 5058:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5059:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5060:   if ($domain eq 'public' && $stuname eq 'public') {
                   5061:       $stuname=$ENV{'REMOTE_ADDR'};
                   5062:   }
1.168     albertel 5063:   my %returnhash;
                   5064:   $namespace=~s/\//\_/g;
                   5065:   $namespace=~s/\W//g;
                   5066:   my %hash;
1.1117    foxr     5067:   my $path=LONCAPA::tempdir();
1.168     albertel 5068:   if (tie(%hash,'GDBM_File',
                   5069: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5070: 	  &GDBM_READER(),0640)) {
1.168     albertel 5071:     my $version=$hash{"version:$symb"};
                   5072:     $returnhash{'version'}=$version;
                   5073:     my $scope;
                   5074:     for ($scope=1;$scope<=$version;$scope++) {
                   5075:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5076:       my @keys=split(/:/,$vkeys);
                   5077:       my $key;
                   5078:       $returnhash{"$scope:keys"}=$vkeys;
                   5079:       foreach $key (@keys) {
1.591     albertel 5080: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5081: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5082:       }
                   5083:     }
1.168     albertel 5084:     if (!(untie(%hash))) {
                   5085:       return "error:$!";
                   5086:     }
                   5087:   } else {
                   5088:     return "error:$!";
                   5089:   }
                   5090:   return %returnhash;
1.167     albertel 5091: }
                   5092: 
1.9       www      5093: # ----------------------------------------------------------------------- Store
                   5094: 
                   5095: sub store {
1.1269    raeburn  5096:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5097:     my $home='';
                   5098: 
1.168     albertel 5099:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5100: 
1.213     www      5101:     $symb=&symbclean($symb);
1.122     albertel 5102:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5103: 
1.620     albertel 5104:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5105:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5106: 
                   5107:     &devalidate($symb,$stuname,$domain);
1.109     www      5108: 
                   5109:     $symb=escape($symb);
1.187     www      5110:     if (!$namespace) { 
1.620     albertel 5111:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5112:           return ''; 
                   5113:        } 
                   5114:     }
1.620     albertel 5115:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5116: 
                   5117:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5118:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5119: 
1.12      www      5120:     my $namevalue='';
1.800     albertel 5121:     foreach my $key (keys(%$storehash)) {
                   5122:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5123:     }
1.12      www      5124:     $namevalue=~s/\&$//;
1.187     www      5125:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5126:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5127: }
                   5128: 
1.47      www      5129: # -------------------------------------------------------------- Critical Store
                   5130: 
                   5131: sub cstore {
1.1269    raeburn  5132:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5133:     my $home='';
                   5134: 
1.168     albertel 5135:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5136: 
1.213     www      5137:     $symb=&symbclean($symb);
1.122     albertel 5138:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5139: 
1.620     albertel 5140:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5141:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5142: 
                   5143:     &devalidate($symb,$stuname,$domain);
1.109     www      5144: 
                   5145:     $symb=escape($symb);
1.187     www      5146:     if (!$namespace) { 
1.620     albertel 5147:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5148:           return ''; 
                   5149:        } 
                   5150:     }
1.620     albertel 5151:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5152: 
                   5153:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5154:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5155: 
1.47      www      5156:     my $namevalue='';
1.800     albertel 5157:     foreach my $key (keys(%$storehash)) {
                   5158:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5159:     }
1.47      www      5160:     $namevalue=~s/\&$//;
1.187     www      5161:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5162:     return critical
1.1269    raeburn  5163:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5164: }
                   5165: 
1.9       www      5166: # --------------------------------------------------------------------- Restore
                   5167: 
                   5168: sub restore {
1.124     www      5169:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5170:     my $home='';
                   5171: 
1.168     albertel 5172:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5173: 
1.122     albertel 5174:     if (!$symb) {
1.1224    raeburn  5175:         return if ($namespace eq 'courserequests');
                   5176:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5177:     } else {
1.1224    raeburn  5178:         unless ($namespace eq 'courserequests') {
                   5179:             $symb=&escape(&symbclean($symb));
                   5180:         }
1.122     albertel 5181:     }
1.188     www      5182:     if (!$namespace) { 
1.620     albertel 5183:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5184:           return ''; 
                   5185:        } 
                   5186:     }
1.620     albertel 5187:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5188:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5189:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5190:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5191: 
1.12      www      5192:     my %returnhash=();
1.800     albertel 5193:     foreach my $line (split(/\&/,$answer)) {
                   5194: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5195:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5196:     }
1.75      www      5197:     my $version;
                   5198:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5199:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5200:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5201:        }
1.75      www      5202:     }
1.13      www      5203:     return %returnhash;
1.34      www      5204: }
                   5205: 
                   5206: # ---------------------------------------------------------- Course Description
1.1118    foxr     5207: #
                   5208: #  
1.34      www      5209: 
                   5210: sub coursedescription {
1.731     albertel 5211:     my ($courseid,$args)=@_;
1.34      www      5212:     $courseid=~s/^\///;
1.49      www      5213:     $courseid=~s/\_/\//g;
1.34      www      5214:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5215:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5216:     my $normalid=$cdomain.'_'.$cnum;
                   5217:     # need to always cache even if we get errors otherwise we keep 
                   5218:     # trying and trying and trying to get the course description.
                   5219:     my %envhash=();
                   5220:     my %returnhash=();
1.731     albertel 5221:     
                   5222:     my $expiretime=600;
                   5223:     if ($env{'request.course.id'} eq $normalid) {
                   5224: 	$expiretime=120;
                   5225:     }
                   5226: 
                   5227:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5228:     if (!$args->{'freshen_cache'}
                   5229: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5230: 	foreach my $key (keys(%env)) {
                   5231: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5232: 	    my ($setting) = $1;
                   5233: 	    $returnhash{$setting} = $env{$key};
                   5234: 	}
                   5235: 	return %returnhash;
                   5236:     }
                   5237: 
1.1118    foxr     5238:     # get the data again
                   5239: 
1.731     albertel 5240:     if (!$args->{'one_time'}) {
                   5241: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5242:     }
1.811     albertel 5243: 
1.34      www      5244:     if ($chome ne 'no_host') {
1.302     albertel 5245:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5246:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5247: 	   my $username = $env{'user.name'}; # Defult username
                   5248: 	   if(defined $args->{'user'}) {
                   5249: 	       $username = $args->{'user'};
                   5250: 	   }
1.129     albertel 5251:            $returnhash{'home'}= $chome;
                   5252: 	   $returnhash{'domain'} = $cdomain;
                   5253: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5254:            if (!defined($returnhash{'type'})) {
                   5255:                $returnhash{'type'} = 'Course';
                   5256:            }
1.130     albertel 5257:            while (my ($name,$value) = each %returnhash) {
1.53      www      5258:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5259:            }
1.270     www      5260:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5261:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5262: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5263:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5264:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5265:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5266:        }
                   5267:     }
1.731     albertel 5268:     if (!$args->{'one_time'}) {
1.949     raeburn  5269: 	&appenv(\%envhash);
1.731     albertel 5270:     }
1.302     albertel 5271:     return %returnhash;
1.461     www      5272: }
                   5273: 
1.1080    raeburn  5274: sub update_released_required {
                   5275:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5276:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5277:         $cid = $env{'request.course.id'};
                   5278:         $cdom = $env{'course.'.$cid.'.domain'};
                   5279:         $cnum = $env{'course.'.$cid.'.num'};
                   5280:         $chome = $env{'course.'.$cid.'.home'};
                   5281:     }
                   5282:     if ($needsrelease) {
                   5283:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5284:         my $needsupdate;
                   5285:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5286:             $needsupdate = 1;
                   5287:         } else {
                   5288:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5289:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5290:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5291:                 $needsupdate = 1;
                   5292:             }
                   5293:         }
                   5294:         if ($needsupdate) {
                   5295:             my %needshash = (
                   5296:                              'internal.releaserequired' => $needsrelease,
                   5297:                             );
                   5298:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5299:             if ($putresult eq 'ok') {
                   5300:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5301:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5302:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5303:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5304:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5305:                 }
                   5306:             }
                   5307:         }
                   5308:     }
                   5309:     return;
                   5310: }
                   5311: 
1.461     www      5312: # -------------------------------------------------See if a user is privileged
                   5313: 
                   5314: sub privileged {
1.1219    raeburn  5315:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5316:     my $now = time;
1.1219    raeburn  5317:     my $roles;
                   5318:     if (ref($possroles) eq 'ARRAY') {
                   5319:         $roles = $possroles; 
                   5320:     } else {
                   5321:         $roles = ['dc','su'];
                   5322:     }
                   5323:     if (ref($possdomains) eq 'ARRAY') {
                   5324:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5325:         foreach my $dom (@{$possdomains}) {
                   5326:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5327:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5328:                 foreach my $role (@{$roles}) {
                   5329:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5330:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5331:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5332:                             return 1 unless (($end && $end < $now) ||
                   5333:                                              ($start && $start > $now));
                   5334:                         }
                   5335:                     }
                   5336:                 }
                   5337:             }
                   5338:         }
                   5339:     } else {
                   5340:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5341:         my $now = time;
1.1170    droeschl 5342: 
1.1275    musolffc 5343:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5344:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5345:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5346:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5347:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5348:             }
1.1219    raeburn  5349:         }
                   5350:     }
                   5351:     return 0;
                   5352: }
1.1170    droeschl 5353: 
1.1219    raeburn  5354: sub privileged_by_domain {
                   5355:     my ($domains,$roles) = @_;
                   5356:     my %privileged = ();
                   5357:     my $cachetime = 60*60*24;
                   5358:     my $now = time;
                   5359:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5360:         return %privileged;
                   5361:     }
                   5362:     foreach my $dom (@{$domains}) {
                   5363:         next if (ref($privileged{$dom}) eq 'HASH');
                   5364:         my $needroles;
                   5365:         foreach my $role (@{$roles}) {
                   5366:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5367:             if (defined($cached)) {
                   5368:                 if (ref($result) eq 'HASH') {
                   5369:                     $privileged{$dom}{$role} = $result;
                   5370:                 }
                   5371:             } else {
                   5372:                 $needroles = 1;
                   5373:             }
                   5374:         }
                   5375:         if ($needroles) {
                   5376:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5377:             $privileged{$dom} = {};
                   5378:             foreach my $server (keys(%dompersonnel)) {
                   5379:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5380:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5381:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5382:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5383:                         next if ($end && $end < $now);
                   5384:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5385:                             $dompersonnel{$server}{$item};
                   5386:                     }
                   5387:                 }
                   5388:             }
                   5389:             if (ref($privileged{$dom}) eq 'HASH') {
                   5390:                 foreach my $role (@{$roles}) {
                   5391:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5392:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5393:                     } else {
                   5394:                         my %hash = ();
                   5395:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5396:                     }
                   5397:                 }
                   5398:             }
                   5399:         }
                   5400:     }
                   5401:     return %privileged;
1.9       www      5402: }
1.1       albertel 5403: 
1.103     harris41 5404: # -------------------------------------------------------- Get user privileges
1.11      www      5405: 
                   5406: sub rolesinit {
1.1169    droeschl 5407:     my ($domain, $username) = @_;
                   5408:     my %userroles = ('user.login.time' => time);
                   5409:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5410: 
                   5411:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5412:     # also, blocking can be triggered by an activating timer
                   5413:     # it's saved in the user's %env.
                   5414:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5415:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5416:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5417:         %timerintchk, %timerintenv);
                   5418: 
1.1162    raeburn  5419:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5420:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5421:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5422:     }
1.1169    droeschl 5423: 
1.1162    raeburn  5424:     foreach my $key (keys(%timerinterval)) {
                   5425:         my ($cid,$rest) = split(/\0/,$key);
                   5426:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5427:     }
1.1169    droeschl 5428: 
1.11      www      5429:     my %allroles=();
1.1162    raeburn  5430:     my %allgroups=();
1.11      www      5431: 
1.1274    raeburn  5432:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5433:         my $role = $rolesdump{$area};
                   5434:         $area =~ s/\_\w\w$//;
                   5435: 
                   5436:         my ($trole, $tend, $tstart, $group_privs);
                   5437: 
                   5438:         if ($role =~ /^cr/) {
                   5439:         # Custom role, defined by a user 
                   5440:         # e.g., user.role.cr/msu/smith/mynewrole
                   5441:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5442:                 $trole = $1;
                   5443:                 ($tend, $tstart) = split('_', $2);
                   5444:             } else {
                   5445:                 $trole = $role;
                   5446:             }
                   5447:         } elsif ($role =~ m|^gr/|) {
                   5448:         # Role of member in a group, defined within a course/community
                   5449:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5450:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5451:             next if $tstart eq '-1';
                   5452:             ($trole, $group_privs) = split(/\//, $trole);
                   5453:             $group_privs = &unescape($group_privs);
                   5454:         } else {
                   5455:         # Just a normal role, defined in roles.tab
                   5456:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5457:         }
                   5458: 
                   5459:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5460:                  $username);
                   5461:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5462: 
                   5463:         # role expired or not available yet?
                   5464:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5465:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5466: 
                   5467:         next if $area eq '' or $trole eq '';
                   5468: 
                   5469:         my $spec = "$trole.$area";
                   5470:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5471: 
                   5472:         if ($trole =~ /^cr\//) {
                   5473:         # Custom role, defined by a user
                   5474:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5475:         } elsif ($trole eq 'gr') {
                   5476:         # Role of a member in a group, defined within a course/community
                   5477:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5478:             next;
                   5479:         } else {
                   5480:         # Normal role, defined in roles.tab
                   5481:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5482:         }
                   5483: 
                   5484:         my $cid = $tdomain.'_'.$trest;
                   5485:         unless ($firstaccchk{$cid}) {
                   5486:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5487:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5488:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5489:                         $coursetimerstarts{$cid}{$item}; 
                   5490:                 }
                   5491:             }
                   5492:             $firstaccchk{$cid} = 1;
                   5493:         }
                   5494:         unless ($timerintchk{$cid}) {
                   5495:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5496:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5497:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5498:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5499:                 }
1.12      www      5500:             }
1.1169    droeschl 5501:             $timerintchk{$cid} = 1;
1.191     harris41 5502:         }
1.11      www      5503:     }
1.1169    droeschl 5504: 
                   5505:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5506:         \%allroles, \%allgroups);
                   5507:     $env{'user.adv'} = $userroles{'user.adv'};
                   5508: 
1.1162    raeburn  5509:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5510: }
                   5511: 
1.567     raeburn  5512: sub set_arearole {
1.1215    raeburn  5513:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5514:     unless ($nolog) {
1.567     raeburn  5515: # log the associated role with the area
1.1215    raeburn  5516:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5517:     }
1.743     albertel 5518:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5519: }
                   5520: 
                   5521: sub custom_roleprivs {
                   5522:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5523:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5524:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5525:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5526:         my ($rdummy,$roledef)=
                   5527:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5528:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5529:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5530:             if (defined($syspriv)) {
1.1043    raeburn  5531:                 if ($trest =~ /^$match_community$/) {
                   5532:                     $syspriv =~ s/bre\&S//; 
                   5533:                 }
1.567     raeburn  5534:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5535:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5536:             }
                   5537:             if ($tdomain ne '') {
                   5538:                 if (defined($dompriv)) {
                   5539:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5540:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5541:                 }
                   5542:                 if (($trest ne '') && (defined($coursepriv))) {
                   5543:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5544:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5545:                 }
                   5546:             }
                   5547:         }
                   5548:     }
                   5549: }
                   5550: 
1.678     raeburn  5551: sub group_roleprivs {
                   5552:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5553:     my $access = 1;
                   5554:     my $now = time;
                   5555:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5556:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5557:     if ($access) {
1.811     albertel 5558:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5559:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5560:     }
                   5561: }
1.567     raeburn  5562: 
                   5563: sub standard_roleprivs {
                   5564:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5565:     if (defined($pr{$trole.':s'})) {
                   5566:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5567:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5568:     }
                   5569:     if ($tdomain ne '') {
                   5570:         if (defined($pr{$trole.':d'})) {
                   5571:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5572:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5573:         }
                   5574:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5575:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5576:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5577:         }
                   5578:     }
                   5579: }
                   5580: 
                   5581: sub set_userprivs {
1.1064    raeburn  5582:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5583:     my $author=0;
                   5584:     my $adv=0;
1.678     raeburn  5585:     my %grouproles = ();
                   5586:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5587:         my @groupkeys; 
1.1000    raeburn  5588:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5589:             push(@groupkeys,$role);
                   5590:         }
                   5591:         if (ref($groups_roles) eq 'HASH') {
                   5592:             foreach my $key (keys(%{$groups_roles})) {
                   5593:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5594:                     push(@groupkeys,$key);
                   5595:                 }
                   5596:             }
                   5597:         }
                   5598:         if (@groupkeys > 0) {
                   5599:             foreach my $role (@groupkeys) {
                   5600:                 my ($trole,$area,$sec,$extendedarea);
                   5601:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5602:                     $trole = $1;
                   5603:                     $area = $2;
                   5604:                     $sec = $3;
                   5605:                     $extendedarea = $area.$sec;
                   5606:                     if (exists($$allgroups{$area})) {
                   5607:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5608:                             my $spec = $trole.'.'.$extendedarea;
                   5609:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5610:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5611:                         }
1.678     raeburn  5612:                     }
                   5613:                 }
                   5614:             }
                   5615:         }
                   5616:     }
1.800     albertel 5617:     foreach my $group (keys(%grouproles)) {
                   5618:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5619:     }
1.800     albertel 5620:     foreach my $role (keys(%{$allroles})) {
                   5621:         my %thesepriv;
1.941     raeburn  5622:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5623:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5624:             if ($item ne '') {
                   5625:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5626:                 if ($restrictions eq '') {
                   5627:                     $thesepriv{$privilege}='F';
                   5628:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5629:                     $thesepriv{$privilege}.=$restrictions;
                   5630:                 }
                   5631:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5632:             }
                   5633:         }
                   5634:         my $thesestr='';
1.1104    raeburn  5635:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5636: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5637: 	}
                   5638:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5639:     }
                   5640:     return ($author,$adv);
                   5641: }
                   5642: 
1.994     raeburn  5643: sub role_status {
1.1104    raeburn  5644:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5645:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5646:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5647:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5648:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5649:             $$where = '/'.$two;
1.994     raeburn  5650:             $$trolecode=$$role.'.'.$$where;
                   5651:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5652:             $$tstatus='is';
1.1104    raeburn  5653:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5654:                 $$tstatus='future';
1.1034    raeburn  5655:                 if ($$tstart<$now) {
                   5656:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5657:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5658:                             my (%allroles,%allgroups,$group_privs,
                   5659:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5660:                             my %userroles = (
                   5661:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5662:                             );
1.1064    raeburn  5663:                             @rolecodes = ('cm'); 
1.1002    raeburn  5664:                             my $spec=$$role.'.'.$$where;
                   5665:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5666:                             if ($$role =~ /^cr\//) {
                   5667:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5668:                                 push(@rolecodes,'cr');
1.1002    raeburn  5669:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5670:                                 push(@rolecodes,$$role);
1.1002    raeburn  5671:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5672:                                                     $env{'user.name'});
1.1064    raeburn  5673:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5674:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5675:                                 $group_privs = &unescape($group_privs);
                   5676:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5677:                                 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  5678:                                 &get_groups_roles($tdomain,$trest,
                   5679:                                                   \%course_roles,\@rolecodes,
                   5680:                                                   \%groups_roles);
1.1002    raeburn  5681:                             } else {
1.1064    raeburn  5682:                                 push(@rolecodes,$$role);
1.1002    raeburn  5683:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5684:                             }
1.1064    raeburn  5685:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5686:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5687:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5688:                         }
                   5689:                     }
1.1034    raeburn  5690:                     $$tstatus = 'is';
1.1002    raeburn  5691:                 }
1.994     raeburn  5692:             }
                   5693:             if ($$tend) {
1.1104    raeburn  5694:                 if ($$tend<$update) {
1.994     raeburn  5695:                     $$tstatus='expired';
                   5696:                 } elsif ($$tend<$now) {
                   5697:                     $$tstatus='will_not';
                   5698:                 }
                   5699:             }
                   5700:         }
                   5701:     }
                   5702: }
                   5703: 
1.1104    raeburn  5704: sub get_groups_roles {
                   5705:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5706:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5707:                   (ref($rolecodes) eq 'ARRAY') && 
                   5708:                   (ref($groups_roles) eq 'HASH')); 
                   5709:     if (keys(%{$cdom_courseroles}) > 0) {
                   5710:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5711:         if ($cdom ne '' && $cnum ne '') {
                   5712:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5713:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5714:                     my $crsrole = $1;
                   5715:                     my $crssec = $2;
                   5716:                     if ($crsrole =~ /^cr/) {
                   5717:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5718:                             push(@{$rolecodes},'cr');
                   5719:                         }
                   5720:                     } else {
                   5721:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5722:                             push(@{$rolecodes},$crsrole);
                   5723:                         }
                   5724:                     }
                   5725:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5726:                     if ($crssec ne '') {
                   5727:                         $rolekey .= "/$crssec";
                   5728:                     }
                   5729:                     $rolekey .= './';
                   5730:                     $groups_roles->{$rolekey} = $rolecodes;
                   5731:                 }
                   5732:             }
                   5733:         }
                   5734:     }
                   5735:     return;
                   5736: }
                   5737: 
                   5738: sub delete_env_groupprivs {
                   5739:     my ($where,$courseroles,$possroles) = @_;
                   5740:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5741:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5742:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5743:         %{$courseroles->{$udom}} =
                   5744:             &get_my_roles('','','userroles',['active'],
                   5745:                           $possroles,[$udom],1);
                   5746:     }
                   5747:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5748:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5749:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5750:             my $area = '/'.$cdom.'/'.$cnum;
                   5751:             my $privkey = "user.priv.$crsrole.$area";
                   5752:             if ($crssec ne '') {
                   5753:                 $privkey .= '/'.$crssec;
                   5754:             }
                   5755:             $privkey .= ".$area/$group";
                   5756:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5757:         }
                   5758:     }
                   5759:     return;
                   5760: }
                   5761: 
1.994     raeburn  5762: sub check_adhoc_privs {
1.1104    raeburn  5763:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5764:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5765:     my $setprivs;
1.994     raeburn  5766:     if ($env{$cckey}) {
                   5767:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5768:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5769:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5770:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5771:             $setprivs = 1;
1.994     raeburn  5772:         }
                   5773:     } else {
1.1088    raeburn  5774:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5775:         $setprivs = 1;
1.994     raeburn  5776:     }
1.1185    raeburn  5777:     return $setprivs;
1.994     raeburn  5778: }
                   5779: 
                   5780: sub set_adhoc_privileges {
                   5781: # role can be cc or ca
1.1088    raeburn  5782:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5783:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5784:     my $spec = $role.'.'.$area;
                   5785:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5786:                                   $env{'user.name'},1);
1.994     raeburn  5787:     my %ccrole = ();
                   5788:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5789:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5790:     &appenv(\%userroles,[$role,'cm']);
                   5791:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5792:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5793:         &appenv( {'request.role'        => $spec,
                   5794:                   'request.role.domain' => $dcdom,
                   5795:                   'request.course.sec'  => ''
                   5796:                  }
                   5797:                );
                   5798:         my $tadv=0;
                   5799:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5800:         &appenv({'request.role.adv'    => $tadv});
                   5801:     }
1.994     raeburn  5802: }
                   5803: 
1.12      www      5804: # --------------------------------------------------------------- get interface
                   5805: 
                   5806: sub get {
1.131     albertel 5807:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5808:    my $items='';
1.800     albertel 5809:    foreach my $item (@$storearr) {
                   5810:        $items.=&escape($item).'&';
1.191     harris41 5811:    }
1.12      www      5812:    $items=~s/\&$//;
1.620     albertel 5813:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5814:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5815:    my $uhome=&homeserver($uname,$udomain);
                   5816: 
1.133     albertel 5817:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5818:    my @pairs=split(/\&/,$rep);
1.273     albertel 5819:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5820:      return @pairs;
                   5821:    }
1.15      www      5822:    my %returnhash=();
1.42      www      5823:    my $i=0;
1.800     albertel 5824:    foreach my $item (@$storearr) {
                   5825:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5826:       $i++;
1.191     harris41 5827:    }
1.15      www      5828:    return %returnhash;
1.27      www      5829: }
                   5830: 
                   5831: # --------------------------------------------------------------- del interface
                   5832: 
                   5833: sub del {
1.133     albertel 5834:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5835:    my $items='';
1.800     albertel 5836:    foreach my $item (@$storearr) {
                   5837:        $items.=&escape($item).'&';
1.191     harris41 5838:    }
1.984     neumanie 5839: 
1.27      www      5840:    $items=~s/\&$//;
1.620     albertel 5841:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5842:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5843:    my $uhome=&homeserver($uname,$udomain);
                   5844:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5845: }
                   5846: 
                   5847: # -------------------------------------------------------------- dump interface
                   5848: 
1.1180    droeschl 5849: sub unserialize {
                   5850:     my ($rep, $escapedkeys) = @_;
                   5851: 
                   5852:     return {} if $rep =~ /^error/;
                   5853: 
                   5854:     my %returnhash=();
1.1252    raeburn  5855: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5856: 	    my ($key, $value) = split(/=/, $item, 2);
                   5857: 	    $key = unescape($key) unless $escapedkeys;
                   5858: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5859: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5860: 	}
                   5861:     #return %returnhash;
                   5862:     return \%returnhash;
                   5863: }        
                   5864: 
                   5865: # see Lond::dump_with_regexp
                   5866: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5867: sub dump {
1.1180    droeschl 5868:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5869:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5870:     if (!$uname) { $uname=$env{'user.name'}; }
                   5871:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5872: 
1.1266    raeburn  5873:     if ($regexp) {
                   5874:         $regexp=&escape($regexp);
                   5875:     } else {
                   5876:         $regexp='.';
                   5877:     }
1.1180    droeschl 5878:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5879:         # user is hosted on this machine
1.1266    raeburn  5880:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5881:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5882:         return %{unserialize($reply, $escapedkeys)};
                   5883:     }
1.1166    raeburn  5884:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5885:     my @pairs=split(/\&/,$rep);
                   5886:     my %returnhash=();
1.1098    foxr     5887:     if (!($rep =~ /^error/ )) {
                   5888: 	foreach my $item (@pairs) {
                   5889: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5890:         $key = unescape($key) unless $escapedkeys;
                   5891:         #$key = &unescape($key);
1.1098    foxr     5892: 	    next if ($key =~ /^error: 2 /);
                   5893: 	    $returnhash{$key}=&thaw_unescape($value);
                   5894: 	}
1.755     albertel 5895:     }
                   5896:     return %returnhash;
1.407     www      5897: }
                   5898: 
1.1098    foxr     5899: 
1.717     albertel 5900: # --------------------------------------------------------- dumpstore interface
                   5901: 
                   5902: sub dumpstore {
                   5903:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5904:    # same as dump but keys must be escaped. They may contain colon separated
                   5905:    # lists of values that may themself contain colons (e.g. symbs).
                   5906:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5907: }
                   5908: 
1.407     www      5909: # -------------------------------------------------------------- keys interface
                   5910: 
                   5911: sub getkeys {
                   5912:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5913:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5914:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5915:    my $uhome=&homeserver($uname,$udomain);
                   5916:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5917:    my @keyarray=();
1.800     albertel 5918:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5919:       next if ($key =~ /^error: 2 /);
1.800     albertel 5920:       push(@keyarray,&unescape($key));
1.407     www      5921:    }
                   5922:    return @keyarray;
1.318     matthew  5923: }
                   5924: 
1.319     matthew  5925: # --------------------------------------------------------------- currentdump
                   5926: sub currentdump {
1.328     matthew  5927:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5928:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5929:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5930:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5931:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5932:    my $rep;
                   5933: 
                   5934:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5935:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5936:                    $courseid)));
                   5937:    } else {
                   5938:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5939:    }
                   5940: 
1.318     matthew  5941:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5942:    #
1.318     matthew  5943:    my %returnhash=();
1.319     matthew  5944:    #
                   5945:    if ($rep eq "unknown_cmd") { 
                   5946:        # an old lond will not know currentdump
                   5947:        # Do a dump and make it look like a currentdump
1.822     albertel 5948:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5949:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5950:        my %hash = @tmp;
                   5951:        @tmp=();
1.424     matthew  5952:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5953:    } else {
                   5954:        my @pairs=split(/\&/,$rep);
1.800     albertel 5955:        foreach my $pair (@pairs) {
                   5956:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5957:            my ($symb,$param) = split(/:/,$key);
                   5958:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5959:                                                         &thaw_unescape($value);
1.319     matthew  5960:        }
1.191     harris41 5961:    }
1.12      www      5962:    return %returnhash;
1.424     matthew  5963: }
                   5964: 
                   5965: sub convert_dump_to_currentdump{
                   5966:     my %hash = %{shift()};
                   5967:     my %returnhash;
                   5968:     # Code ripped from lond, essentially.  The only difference
                   5969:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5970:     # we might run in to problems with parameter names =~ /^v\./
                   5971:     while (my ($key,$value) = each(%hash)) {
                   5972:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5973: 	$symb  = &unescape($symb);
                   5974: 	$param = &unescape($param);
1.424     matthew  5975:         next if ($v eq 'version' || $symb eq 'keys');
                   5976:         next if (exists($returnhash{$symb}) &&
                   5977:                  exists($returnhash{$symb}->{$param}) &&
                   5978:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5979:         $returnhash{$symb}->{$param}=$value;
                   5980:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5981:     }
                   5982:     #
                   5983:     # Remove all of the keys in the hashes which keep track of
                   5984:     # the version of the parameter.
                   5985:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5986:         # use a foreach because we are going to delete from the hash.
                   5987:         foreach my $key (keys(%$param_hash)) {
                   5988:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5989:         }
                   5990:     }
                   5991:     return \%returnhash;
1.12      www      5992: }
                   5993: 
1.627     albertel 5994: # ------------------------------------------------------ critical inc interface
                   5995: 
                   5996: sub cinc {
                   5997:     return &inc(@_,'critical');
                   5998: }
                   5999: 
1.449     matthew  6000: # --------------------------------------------------------------- inc interface
                   6001: 
                   6002: sub inc {
1.627     albertel 6003:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6004:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6005:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6006:     my $uhome=&homeserver($uname,$udomain);
                   6007:     my $items='';
                   6008:     if (! ref($store)) {
                   6009:         # got a single value, so use that instead
                   6010:         $items = &escape($store).'=&';
                   6011:     } elsif (ref($store) eq 'SCALAR') {
                   6012:         $items = &escape($$store).'=&';        
                   6013:     } elsif (ref($store) eq 'ARRAY') {
                   6014:         $items = join('=&',map {&escape($_);} @{$store});
                   6015:     } elsif (ref($store) eq 'HASH') {
                   6016:         while (my($key,$value) = each(%{$store})) {
                   6017:             $items.= &escape($key).'='.&escape($value).'&';
                   6018:         }
                   6019:     }
                   6020:     $items=~s/\&$//;
1.627     albertel 6021:     if ($critical) {
                   6022: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6023:     } else {
                   6024: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6025:     }
1.449     matthew  6026: }
                   6027: 
1.12      www      6028: # --------------------------------------------------------------- put interface
                   6029: 
                   6030: sub put {
1.134     albertel 6031:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6032:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6033:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6034:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6035:    my $items='';
1.800     albertel 6036:    foreach my $item (keys(%$storehash)) {
                   6037:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6038:    }
1.12      www      6039:    $items=~s/\&$//;
1.134     albertel 6040:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6041: }
                   6042: 
1.631     albertel 6043: # ------------------------------------------------------------ newput interface
                   6044: 
                   6045: sub newput {
                   6046:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6047:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6048:    if (!$uname) { $uname=$env{'user.name'}; }
                   6049:    my $uhome=&homeserver($uname,$udomain);
                   6050:    my $items='';
                   6051:    foreach my $key (keys(%$storehash)) {
                   6052:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6053:    }
                   6054:    $items=~s/\&$//;
                   6055:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6056: }
                   6057: 
                   6058: # ---------------------------------------------------------  putstore interface
                   6059: 
1.524     raeburn  6060: sub putstore {
1.1269    raeburn  6061:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6062:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6063:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6064:    my $uhome=&homeserver($uname,$udomain);
                   6065:    my $items='';
1.715     albertel 6066:    foreach my $key (keys(%$storehash)) {
                   6067:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6068:    }
1.715     albertel 6069:    $items=~s/\&$//;
1.716     albertel 6070:    my $esc_symb=&escape($symb);
                   6071:    my $esc_v=&escape($version);
1.715     albertel 6072:    my $reply =
1.716     albertel 6073:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6074: 	      $uhome);
1.1269    raeburn  6075:    if (($tolog) && ($reply eq 'ok')) {
                   6076:        my $namevalue='';
                   6077:        foreach my $key (keys(%{$storehash})) {
                   6078:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6079:        }
                   6080:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6081:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6082:                      '&version='.$esc_v.
                   6083:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6084:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6085:    }
1.715     albertel 6086:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6087:        # gfall back to way things use to be done
1.715     albertel 6088:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6089: 			    $uname);
1.524     raeburn  6090:    }
1.715     albertel 6091:    return $reply;
                   6092: }
                   6093: 
                   6094: sub old_putstore {
1.716     albertel 6095:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6096:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6097:     if (!$uname) { $uname=$env{'user.name'}; }
                   6098:     my $uhome=&homeserver($uname,$udomain);
                   6099:     my %newstorehash;
1.800     albertel 6100:     foreach my $item (keys(%$storehash)) {
                   6101: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6102: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6103:     }
                   6104:     my $items='';
                   6105:     my %allitems = ();
1.800     albertel 6106:     foreach my $item (keys(%newstorehash)) {
                   6107: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6108: 	    my $key = $1.':keys:'.$2;
                   6109: 	    $allitems{$key} .= $3.':';
                   6110: 	}
1.800     albertel 6111: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6112:     }
1.800     albertel 6113:     foreach my $item (keys(%allitems)) {
                   6114: 	$allitems{$item} =~ s/\:$//;
                   6115: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6116:     }
                   6117:     $items=~s/\&$//;
                   6118:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6119: }
                   6120: 
1.47      www      6121: # ------------------------------------------------------ critical put interface
                   6122: 
                   6123: sub cput {
1.134     albertel 6124:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6125:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6126:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6127:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6128:    my $items='';
1.800     albertel 6129:    foreach my $item (keys(%$storehash)) {
                   6130:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6131:    }
1.47      www      6132:    $items=~s/\&$//;
1.134     albertel 6133:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6134: }
                   6135: 
                   6136: # -------------------------------------------------------------- eget interface
                   6137: 
                   6138: sub eget {
1.133     albertel 6139:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6140:    my $items='';
1.800     albertel 6141:    foreach my $item (@$storearr) {
                   6142:        $items.=&escape($item).'&';
1.191     harris41 6143:    }
1.12      www      6144:    $items=~s/\&$//;
1.620     albertel 6145:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6146:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6147:    my $uhome=&homeserver($uname,$udomain);
                   6148:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6149:    my @pairs=split(/\&/,$rep);
                   6150:    my %returnhash=();
1.42      www      6151:    my $i=0;
1.800     albertel 6152:    foreach my $item (@$storearr) {
                   6153:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6154:       $i++;
1.191     harris41 6155:    }
1.12      www      6156:    return %returnhash;
                   6157: }
                   6158: 
1.667     albertel 6159: # ------------------------------------------------------------ tmpput interface
                   6160: sub tmpput {
1.802     raeburn  6161:     my ($storehash,$server,$context)=@_;
1.667     albertel 6162:     my $items='';
1.800     albertel 6163:     foreach my $item (keys(%$storehash)) {
                   6164: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6165:     }
                   6166:     $items=~s/\&$//;
1.802     raeburn  6167:     if (defined($context)) {
                   6168:         $items .= ':'.&escape($context);
                   6169:     }
1.667     albertel 6170:     return &reply("tmpput:$items",$server);
                   6171: }
                   6172: 
                   6173: # ------------------------------------------------------------ tmpget interface
                   6174: sub tmpget {
1.688     albertel 6175:     my ($token,$server)=@_;
                   6176:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6177:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6178:     my %returnhash;
                   6179:     foreach my $item (split(/\&/,$rep)) {
                   6180: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6181:         next if ($key =~ /^error: 2 /);
1.667     albertel 6182: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6183:     }
                   6184:     return %returnhash;
                   6185: }
                   6186: 
1.1113    raeburn  6187: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6188: sub tmpdel {
                   6189:     my ($token,$server)=@_;
                   6190:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6191:     return &reply("tmpdel:$token",$server);
                   6192: }
                   6193: 
1.1198    raeburn  6194: # ------------------------------------------------------------ get_timebased_id 
                   6195: 
                   6196: sub get_timebased_id {
                   6197:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6198:         $maxtries) = @_;
                   6199:     my ($newid,$error,$dellock);
                   6200:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6201:         return ('','ok','invalid call to get suffix');
                   6202:     }
                   6203: 
                   6204: # set defaults for any optional args for which values were not supplied
                   6205:     if ($who eq '') {
                   6206:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6207:     }
                   6208:     if (!$locktries) {
                   6209:         $locktries = 3;
                   6210:     }
                   6211:     if (!$maxtries) {
                   6212:         $maxtries = 10;
                   6213:     }
                   6214:     
                   6215:     if (($cdom eq '') || ($cnum eq '')) {
                   6216:         if ($env{'request.course.id'}) {
                   6217:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6218:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6219:         }
                   6220:         if (($cdom eq '') || ($cnum eq '')) {
                   6221:             return ('','ok','call to get suffix not in course context');
                   6222:         }
                   6223:     }
                   6224: 
                   6225: # construct locking item
                   6226:     my $lockhash = {
                   6227:                       $prefix."\0".'locked_'.$keyid => $who,
                   6228:                    };
                   6229:     my $tries = 0;
                   6230: 
                   6231: # attempt to get lock on nohist_$namespace file
                   6232:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6233:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6234:         $tries ++;
                   6235:         sleep 1;
                   6236:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6237:     }
                   6238: 
                   6239: # attempt to get unique identifier, based on current timestamp
                   6240:     if ($gotlock eq 'ok') {
                   6241:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6242:         my $id = time;
                   6243:         $newid = $id;
1.1268    raeburn  6244:         if ($idtype eq 'addcode') {
                   6245:             $newid .= &sixnum_code();
                   6246:         }
1.1198    raeburn  6247:         my $idtries = 0;
                   6248:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6249:             if ($idtype eq 'concat') {
                   6250:                 $newid = $id.$idtries;
1.1268    raeburn  6251:             } elsif ($idtype eq 'addcode') {
                   6252:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6253:             } else {
                   6254:                 $newid ++;
                   6255:             }
                   6256:             $idtries ++;
                   6257:         }
                   6258:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6259:             my %new_item =  (
                   6260:                               $prefix."\0".$newid => $who,
                   6261:                             );
                   6262:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6263:                                                  $cdom,$cnum);
                   6264:             if ($putresult ne 'ok') {
                   6265:                 undef($newid);
                   6266:                 $error = 'error saving new item: '.$putresult;
                   6267:             }
                   6268:         } else {
1.1268    raeburn  6269:              undef($newid);
1.1198    raeburn  6270:              $error = ('error: no unique suffix available for the new item ');
                   6271:         }
                   6272: #  remove lock
                   6273:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6274:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6275:     } else {
                   6276:         $error = "error: could not obtain lockfile\n";
                   6277:         $dellock = 'ok';
1.1276    raeburn  6278:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6279:             $dellock = 'nolock';
                   6280:         }
1.1198    raeburn  6281:     }
                   6282:     return ($newid,$dellock,$error);
                   6283: }
                   6284: 
1.1268    raeburn  6285: sub sixnum_code {
                   6286:     my $code;
                   6287:     for (0..6) {
                   6288:         $code .= int( rand(9) );
                   6289:     }
                   6290:     return $code;
                   6291: }
                   6292: 
1.765     albertel 6293: # -------------------------------------------------- portfolio access checking
                   6294: 
                   6295: sub portfolio_access {
1.1270    raeburn  6296:     my ($requrl,$clientip) = @_;
1.765     albertel 6297:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6298:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6299:     if ($result) {
                   6300:         my %setters;
                   6301:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6302:             my ($startblock,$endblock) =
                   6303:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6304:             if ($startblock && $endblock) {
                   6305:                 return 'B';
                   6306:             }
                   6307:         } else {
                   6308:             my ($startblock,$endblock) =
                   6309:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6310:             if ($startblock && $endblock) {
                   6311:                 return 'B';
                   6312:             }
                   6313:         }
                   6314:     }
1.765     albertel 6315:     if ($result eq 'ok') {
1.766     albertel 6316:        return 'F';
1.765     albertel 6317:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6318:        return 'A';
1.765     albertel 6319:     }
1.766     albertel 6320:     return '';
1.765     albertel 6321: }
                   6322: 
                   6323: sub get_portfolio_access {
1.1270    raeburn  6324:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6325: 
                   6326:     if (!ref($access_hash)) {
                   6327: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6328: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6329: 						   $file_name);
                   6330: 	$access_hash = $access_controls{$file_name};
                   6331:     }
                   6332: 
1.1270    raeburn  6333:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6334:     my $now = time;
                   6335:     if (ref($access_hash) eq 'HASH') {
                   6336:         foreach my $key (keys(%{$access_hash})) {
                   6337:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6338:             if ($start > $now) {
                   6339:                 next;
                   6340:             }
                   6341:             if ($end && $end<$now) {
                   6342:                 next;
                   6343:             }
                   6344:             if ($scope eq 'public') {
                   6345:                 $public = $key;
                   6346:                 last;
                   6347:             } elsif ($scope eq 'guest') {
                   6348:                 $guest = $key;
                   6349:             } elsif ($scope eq 'domains') {
                   6350:                 push(@domains,$key);
                   6351:             } elsif ($scope eq 'users') {
                   6352:                 push(@users,$key);
                   6353:             } elsif ($scope eq 'course') {
                   6354:                 push(@courses,$key);
                   6355:             } elsif ($scope eq 'group') {
                   6356:                 push(@groups,$key);
1.1270    raeburn  6357:             } elsif ($scope eq 'ip') {
                   6358:                 push(@ips,$key);
1.765     albertel 6359:             }
                   6360:         }
                   6361:         if ($public) {
                   6362:             return 'ok';
1.1270    raeburn  6363:         } elsif (@ips > 0) {
                   6364:             my $allowed;
                   6365:             foreach my $ipkey (@ips) {
                   6366:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6367:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6368:                         $allowed = 1;
                   6369:                         last; 
                   6370:                     }
                   6371:                 }
                   6372:             }
                   6373:             if ($allowed) {
                   6374:                 return 'ok';
                   6375:             }
1.765     albertel 6376:         }
                   6377:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6378:             if ($guest) {
                   6379:                 return $guest;
                   6380:             }
                   6381:         } else {
                   6382:             if (@domains > 0) {
                   6383:                 foreach my $domkey (@domains) {
                   6384:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6385:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6386:                             return 'ok';
                   6387:                         }
                   6388:                     }
                   6389:                 }
                   6390:             }
                   6391:             if (@users > 0) {
                   6392:                 foreach my $userkey (@users) {
1.865     raeburn  6393:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6394:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6395:                             if (ref($item) eq 'HASH') {
                   6396:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6397:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6398:                                     return 'ok';
                   6399:                                 }
                   6400:                             }
                   6401:                         }
                   6402:                     } 
1.765     albertel 6403:                 }
                   6404:             }
                   6405:             my %roleshash;
                   6406:             my @courses_and_groups = @courses;
                   6407:             push(@courses_and_groups,@groups); 
                   6408:             if (@courses_and_groups > 0) {
                   6409:                 my (%allgroups,%allroles); 
                   6410:                 my ($start,$end,$role,$sec,$group);
                   6411:                 foreach my $envkey (%env) {
1.1060    raeburn  6412:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6413:                         my $cid = $2.'_'.$3; 
                   6414:                         if ($1 eq 'gr') {
                   6415:                             $group = $4;
                   6416:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6417:                         } else {
                   6418:                             if ($4 eq '') {
                   6419:                                 $sec = 'none';
                   6420:                             } else {
                   6421:                                 $sec = $4;
                   6422:                             }
                   6423:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6424:                         }
1.811     albertel 6425:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6426:                         my $cid = $2.'_'.$3;
                   6427:                         if ($4 eq '') {
                   6428:                             $sec = 'none';
                   6429:                         } else {
                   6430:                             $sec = $4;
                   6431:                         }
                   6432:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6433:                     }
                   6434:                 }
                   6435:                 if (keys(%allroles) == 0) {
                   6436:                     return;
                   6437:                 }
                   6438:                 foreach my $key (@courses_and_groups) {
                   6439:                     my %content = %{$$access_hash{$key}};
                   6440:                     my $cnum = $content{'number'};
                   6441:                     my $cdom = $content{'domain'};
                   6442:                     my $cid = $cdom.'_'.$cnum;
                   6443:                     if (!exists($allroles{$cid})) {
                   6444:                         next;
                   6445:                     }    
                   6446:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6447:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6448:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6449:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6450:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6451:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6452:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6453:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6454:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6455:                                         if (grep/^all$/,@sections) {
                   6456:                                             return 'ok';
                   6457:                                         } else {
                   6458:                                             if (grep/^$sec$/,@sections) {
                   6459:                                                 return 'ok';
                   6460:                                             }
                   6461:                                         }
                   6462:                                     }
                   6463:                                 }
                   6464:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6465:                                     if (grep/^none$/,@groups) {
                   6466:                                         return 'ok';
                   6467:                                     }
                   6468:                                 } else {
                   6469:                                     if (grep/^all$/,@groups) {
                   6470:                                         return 'ok';
                   6471:                                     } 
                   6472:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6473:                                         if (grep/^$group$/,@groups) {
                   6474:                                             return 'ok';
                   6475:                                         }
                   6476:                                     }
                   6477:                                 } 
                   6478:                             }
                   6479:                         }
                   6480:                     }
                   6481:                 }
                   6482:             }
                   6483:             if ($guest) {
                   6484:                 return $guest;
                   6485:             }
                   6486:         }
                   6487:     }
                   6488:     return;
                   6489: }
                   6490: 
                   6491: sub course_group_datechecker {
                   6492:     my ($dates,$now,$status) = @_;
                   6493:     my ($start,$end) = split(/\./,$dates);
                   6494:     if (!$start && !$end) {
                   6495:         return 'ok';
                   6496:     }
                   6497:     if (grep/^active$/,@{$status}) {
                   6498:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6499:             return 'ok';
                   6500:         }
                   6501:     }
                   6502:     if (grep/^previous$/,@{$status}) {
                   6503:         if ($end > $now ) {
                   6504:             return 'ok';
                   6505:         }
                   6506:     }
                   6507:     if (grep/^future$/,@{$status}) {
                   6508:         if ($start > $now) {
                   6509:             return 'ok';
                   6510:         }
                   6511:     }
                   6512:     return; 
                   6513: }
                   6514: 
                   6515: sub parse_portfolio_url {
                   6516:     my ($url) = @_;
                   6517: 
                   6518:     my ($type,$udom,$unum,$group,$file_name);
                   6519:     
1.823     albertel 6520:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6521: 	$type = 1;
                   6522:         $udom = $1;
                   6523:         $unum = $2;
                   6524:         $file_name = $3;
1.823     albertel 6525:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6526: 	$type = 2;
                   6527:         $udom = $1;
                   6528:         $unum = $2;
                   6529:         $group = $3;
                   6530:         $file_name = $3.'/'.$4;
                   6531:     }
                   6532:     if (wantarray) {
                   6533: 	return ($type,$udom,$unum,$file_name,$group);
                   6534:     }
                   6535:     return $type;
                   6536: }
                   6537: 
                   6538: sub is_portfolio_url {
                   6539:     my ($url) = @_;
                   6540:     return scalar(&parse_portfolio_url($url));
                   6541: }
                   6542: 
1.798     raeburn  6543: sub is_portfolio_file {
                   6544:     my ($file) = @_;
1.820     raeburn  6545:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6546:         return 1;
                   6547:     }
                   6548:     return;
                   6549: }
                   6550: 
1.976     raeburn  6551: sub usertools_access {
1.1084    raeburn  6552:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6553:     my ($access,%tools);
                   6554:     if ($context eq '') {
                   6555:         $context = 'tools';
                   6556:     }
                   6557:     if ($context eq 'requestcourses') {
                   6558:         %tools = (
                   6559:                       official   => 1,
                   6560:                       unofficial => 1,
1.1006    raeburn  6561:                       community  => 1,
1.1246    raeburn  6562:                       textbook   => 1,
1.1305    raeburn  6563:                       placement  => 1,
1.985     raeburn  6564:                  );
1.1183    raeburn  6565:     } elsif ($context eq 'requestauthor') {
                   6566:         %tools = (
                   6567:                       requestauthor => 1,
                   6568:                  );
1.985     raeburn  6569:     } else {
                   6570:         %tools = (
                   6571:                       aboutme   => 1,
                   6572:                       blog      => 1,
1.1177    raeburn  6573:                       webdav    => 1,
1.985     raeburn  6574:                       portfolio => 1,
                   6575:                  );
                   6576:     }
1.976     raeburn  6577:     return if (!defined($tools{$tool}));
                   6578: 
1.1242    raeburn  6579:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6580:         $udom = $env{'user.domain'};
                   6581:         $uname = $env{'user.name'};
                   6582:     }
                   6583: 
1.978     raeburn  6584:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6585:         if ($action ne 'reload') {
1.985     raeburn  6586:             if ($context eq 'requestcourses') {
                   6587:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6588:             } elsif ($context eq 'requestauthor') {
                   6589:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6590:             } else {
                   6591:                 return $env{'environment.availabletools.'.$tool};
                   6592:             }
                   6593:         }
1.976     raeburn  6594:     }
                   6595: 
1.1183    raeburn  6596:     my ($toolstatus,$inststatus,$envkey);
                   6597:     if ($context eq 'requestauthor') {
                   6598:         $envkey = $context; 
                   6599:     } else {
                   6600:         $envkey = $context.'.'.$tool;
                   6601:     }
1.976     raeburn  6602: 
1.985     raeburn  6603:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6604:          ($action ne 'reload')) {
1.1183    raeburn  6605:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6606:         $inststatus = $env{'environment.inststatus'};
                   6607:     } else {
1.1084    raeburn  6608:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6609:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6610:             $inststatus = $userenvref->{'inststatus'};
                   6611:         } else {
1.1183    raeburn  6612:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6613:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6614:             $inststatus = $userenv{'inststatus'};
                   6615:         }
1.976     raeburn  6616:     }
                   6617: 
                   6618:     if ($toolstatus ne '') {
                   6619:         if ($toolstatus) {
                   6620:             $access = 1;
                   6621:         } else {
                   6622:             $access = 0;
                   6623:         }
                   6624:         return $access;
                   6625:     }
                   6626: 
1.1084    raeburn  6627:     my ($is_adv,%domdef);
                   6628:     if (ref($is_advref) eq 'HASH') {
                   6629:         $is_adv = $is_advref->{'is_adv'};
                   6630:     } else {
                   6631:         $is_adv = &is_advanced_user($udom,$uname);
                   6632:     }
                   6633:     if (ref($domdefref) eq 'HASH') {
                   6634:         %domdef = %{$domdefref};
                   6635:     } else {
                   6636:         %domdef = &get_domain_defaults($udom);
                   6637:     }
1.976     raeburn  6638:     if (ref($domdef{$tool}) eq 'HASH') {
                   6639:         if ($is_adv) {
                   6640:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6641:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6642:                     $access = 1;
                   6643:                 } else {
                   6644:                     $access = 0;
                   6645:                 }
                   6646:                 return $access;
                   6647:             }
                   6648:         }
                   6649:         if ($inststatus ne '') {
                   6650:             my ($hasaccess,$hasnoaccess);
                   6651:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6652:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6653:                     if ($domdef{$tool}{$affiliation}) {
                   6654:                         $hasaccess = 1;
                   6655:                     } else {
                   6656:                         $hasnoaccess = 1;
                   6657:                     }
                   6658:                 }
                   6659:             }
                   6660:             if ($hasaccess || $hasnoaccess) {
                   6661:                 if ($hasaccess) {
                   6662:                     $access = 1;
                   6663:                 } elsif ($hasnoaccess) {
                   6664:                     $access = 0; 
                   6665:                 }
                   6666:                 return $access;
                   6667:             }
                   6668:         } else {
                   6669:             if ($domdef{$tool}{'default'} ne '') {
                   6670:                 if ($domdef{$tool}{'default'}) {
                   6671:                     $access = 1;
                   6672:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6673:                     $access = 0;
                   6674:                 }
                   6675:                 return $access;
                   6676:             }
                   6677:         }
                   6678:     } else {
1.1177    raeburn  6679:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6680:             $access = 1;
                   6681:         } else {
                   6682:             $access = 0;
                   6683:         }
1.976     raeburn  6684:         return $access;
                   6685:     }
                   6686: }
                   6687: 
1.1050    raeburn  6688: sub is_course_owner {
                   6689:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6690:     if (($udom eq '') || ($uname eq '')) {
                   6691:         $udom = $env{'user.domain'};
                   6692:         $uname = $env{'user.name'};
                   6693:     }
                   6694:     unless (($udom eq '') || ($uname eq '')) {
                   6695:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6696:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6697:                 return 1;
                   6698:             } else {
                   6699:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6700:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6701:                     return 1;
                   6702:                 }
                   6703:             }
                   6704:         }
                   6705:     }
                   6706:     return;
                   6707: }
                   6708: 
1.976     raeburn  6709: sub is_advanced_user {
                   6710:     my ($udom,$uname) = @_;
1.1085    raeburn  6711:     if ($udom ne '' && $uname ne '') {
                   6712:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6713:             if (wantarray) {
                   6714:                 return ($env{'user.adv'},$env{'user.author'});
                   6715:             } else {
                   6716:                 return $env{'user.adv'};
                   6717:             }
1.1085    raeburn  6718:         }
                   6719:     }
1.976     raeburn  6720:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6721:     my %allroles;
1.1128    raeburn  6722:     my ($is_adv,$is_author);
1.976     raeburn  6723:     foreach my $role (keys(%roleshash)) {
                   6724:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6725:         my $area = '/'.$tdomain.'/'.$trest;
                   6726:         if ($sec ne '') {
                   6727:             $area .= '/'.$sec;
                   6728:         }
                   6729:         if (($area ne '') && ($trole ne '')) {
                   6730:             my $spec=$trole.'.'.$area;
                   6731:             if ($trole =~ /^cr\//) {
                   6732:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6733:             } elsif ($trole ne 'gr') {
                   6734:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6735:             }
1.1128    raeburn  6736:             if ($trole eq 'au') {
                   6737:                 $is_author = 1;
                   6738:             }
1.976     raeburn  6739:         }
                   6740:     }
                   6741:     foreach my $role (keys(%allroles)) {
                   6742:         last if ($is_adv);
                   6743:         foreach my $item (split(/:/,$allroles{$role})) {
                   6744:             if ($item ne '') {
                   6745:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6746:                 if ($privilege eq 'adv') {
                   6747:                     $is_adv = 1;
                   6748:                     last;
                   6749:                 }
                   6750:             }
                   6751:         }
                   6752:     }
1.1128    raeburn  6753:     if (wantarray) {
                   6754:         return ($is_adv,$is_author);
                   6755:     }
1.976     raeburn  6756:     return $is_adv;
                   6757: }
1.798     raeburn  6758: 
1.1035    raeburn  6759: sub check_can_request {
1.1036    raeburn  6760:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6761:     my $canreq = 0;
                   6762:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6763:     my @options = ('approval','validate','autolimit');
                   6764:     my $optregex = join('|',@options);
                   6765:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6766:         foreach my $type (@{$types}) {
                   6767:             if (&usertools_access($env{'user.name'},
                   6768:                                   $env{'user.domain'},
                   6769:                                   $type,undef,'requestcourses')) {
                   6770:                 $canreq ++;
1.1036    raeburn  6771:                 if (ref($request_domains) eq 'HASH') {
                   6772:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6773:                 }
1.1035    raeburn  6774:                 if ($dom eq $env{'user.domain'}) {
                   6775:                     $can_request->{$type} = 1;
                   6776:                 }
                   6777:             }
                   6778:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6779:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6780:                 if (@curr > 0) {
1.1036    raeburn  6781:                     foreach my $item (@curr) {
                   6782:                         if (ref($request_domains) eq 'HASH') {
                   6783:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6784:                             if ($otherdom ne '') {
                   6785:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6786:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6787:                                         push(@{$request_domains->{$type}},$otherdom);
                   6788:                                     }
                   6789:                                 } else {
                   6790:                                     push(@{$request_domains->{$type}},$otherdom);
                   6791:                                 }
                   6792:                             }
                   6793:                         }
                   6794:                     }
                   6795:                     unless($dom eq $env{'user.domain'}) {
                   6796:                         $canreq ++;
1.1035    raeburn  6797:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6798:                             $can_request->{$type} = 1;
                   6799:                         }
                   6800:                     }
                   6801:                 }
                   6802:             }
                   6803:         }
                   6804:     }
                   6805:     return $canreq;
                   6806: }
                   6807: 
1.341     www      6808: # ---------------------------------------------- Custom access rule evaluation
                   6809: 
                   6810: sub customaccess {
                   6811:     my ($priv,$uri)=@_;
1.807     albertel 6812:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6813:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6814:     $udom = &LONCAPA::clean_domain($udom);
                   6815:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6816:     my $access=0;
1.800     albertel 6817:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6818: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6819: 	if ($type eq 'user') {
                   6820: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6821: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6822: 		if ($tdom) {
                   6823: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6824: 		}
1.896     albertel 6825: 		if ($tuname) {
                   6826: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6827: 		}
                   6828: 		$access=($effect eq 'allow');
                   6829: 		last;
                   6830: 	    }
                   6831: 	} else {
                   6832: 	    if ($role) {
                   6833: 		if ($role ne $urole) { next; }
                   6834: 	    }
                   6835: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6836: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6837: 		if ($tdom) {
                   6838: 		    if ($tdom ne $udom) { next; }
                   6839: 		}
                   6840: 		if ($tcrs) {
                   6841: 		    if ($tcrs ne $ucrs) { next; }
                   6842: 		}
                   6843: 		if ($tsec) {
                   6844: 		    if ($tsec ne $usec) { next; }
                   6845: 		}
                   6846: 		$access=($effect eq 'allow');
                   6847: 		last;
                   6848: 	    }
                   6849: 	    if ($realm eq '' && $role eq '') {
                   6850: 		$access=($effect eq 'allow');
                   6851: 	    }
1.402     bowersj2 6852: 	}
1.341     www      6853:     }
                   6854:     return $access;
                   6855: }
                   6856: 
1.103     harris41 6857: # ------------------------------------------------- Check for a user privilege
1.12      www      6858: 
                   6859: sub allowed {
1.1281    raeburn  6860:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6861:     my $ver_orguri=$uri;
1.439     www      6862:     $uri=&deversion($uri);
1.152     www      6863:     my $orguri=$uri;
1.52      www      6864:     $uri=&declutter($uri);
1.809     raeburn  6865: 
1.810     raeburn  6866:     if ($priv eq 'evb') {
                   6867: # Evade communication block restrictions for specified role in a course
                   6868:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6869:             return $1;
                   6870:         } else {
                   6871:             return;
                   6872:         }
                   6873:     }
                   6874: 
1.620     albertel 6875:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6876: # Free bre access to adm and meta resources
1.775     albertel 6877:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6878: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6879: 	&& ($priv eq 'bre')) {
1.14      www      6880: 	return 'F';
1.159     www      6881:     }
                   6882: 
1.545     banghart 6883: # Free bre access to user's own portfolio contents
1.714     raeburn  6884:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6885:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6886: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6887:         my %setters;
                   6888:         my ($startblock,$endblock) = 
                   6889:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6890:         if ($startblock && $endblock) {
                   6891:             return 'B';
                   6892:         } else {
                   6893:             return 'F';
                   6894:         }
1.545     banghart 6895:     }
                   6896: 
1.762     raeburn  6897: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6898:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6899:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6900:         if (exists($env{'request.course.id'})) {
                   6901:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6902:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6903:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6904:                 my $courseprivid=$env{'request.course.id'};
                   6905:                 $courseprivid=~s/\_/\//;
                   6906:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6907:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6908:                     return $1; 
1.762     raeburn  6909:                 } else {
                   6910:                     if ($env{'request.course.sec'}) {
                   6911:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6912:                     }
                   6913:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6914:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6915:                         return $2;
                   6916:                     }
1.714     raeburn  6917:                 }
                   6918:             }
                   6919:         }
                   6920:     }
                   6921: 
1.159     www      6922: # Free bre to public access
                   6923: 
                   6924:     if ($priv eq 'bre') {
1.238     www      6925:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6926: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6927:            return 'F'; 
                   6928:         }
1.238     www      6929:         if ($copyright eq 'priv') {
                   6930:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6931: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6932: 		return '';
                   6933:             }
                   6934:         }
                   6935:         if ($copyright eq 'domain') {
                   6936:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6937: 	    unless (($env{'user.domain'} eq $1) ||
                   6938:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6939: 		return '';
                   6940:             }
1.262     matthew  6941:         }
1.620     albertel 6942:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6943:             # Library role, so allow browsing of resources in this domain.
                   6944:             return 'F';
1.238     www      6945:         }
1.341     www      6946:         if ($copyright eq 'custom') {
                   6947: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6948:         }
1.14      www      6949:     }
1.264     matthew  6950:     # Domain coordinator is trying to create a course
1.620     albertel 6951:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6952:         # uri is the requested domain in this case.
                   6953:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6954:         # a role of dc for the domain in question.
1.620     albertel 6955:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6956:     }
1.29      www      6957: 
1.52      www      6958:     my $thisallowed='';
                   6959:     my $statecond=0;
                   6960:     my $courseprivid='';
                   6961: 
1.1039    raeburn  6962:     my $ownaccess;
1.1043    raeburn  6963:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6964:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6965:         if ($uri eq '') {
                   6966:             $ownaccess = 1;
                   6967:         } else {
                   6968:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6969:                 my $udom = $env{'user.domain'};
                   6970:                 my $uname = $env{'user.name'};
                   6971:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6972:                     $ownaccess = 1;
1.1040    raeburn  6973:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6974:                     unless ($uri =~ m{\.\./}) {
                   6975:                         $ownaccess = 1;
                   6976:                     }
                   6977:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6978:                     my $now = time;
                   6979:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6980:                         my $adom = $1;
                   6981:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6982:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6983:                                 my ($start,$end) = split('.',$env{$key});
                   6984:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6985:                                     $ownaccess = 1;
                   6986:                                     last;
                   6987:                                 }
                   6988:                             }
                   6989:                         }
                   6990:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6991:                         my $adom = $1;
                   6992:                         my $aname = $2;
1.1042    raeburn  6993:                         foreach my $role ('ca','aa') { 
                   6994:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6995:                                 my ($start,$end) =
                   6996:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6997:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6998:                                     $ownaccess = 1;
                   6999:                                     last;
                   7000:                                 }
1.1039    raeburn  7001:                             }
                   7002:                         }
                   7003:                     }
                   7004:                 }
                   7005:             }
                   7006:         }
                   7007:     }
                   7008: 
1.52      www      7009: # Course
                   7010: 
1.620     albertel 7011:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7012:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7013:             $thisallowed.=$1;
                   7014:         }
1.52      www      7015:     }
1.29      www      7016: 
1.52      www      7017: # Domain
                   7018: 
1.620     albertel 7019:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7020:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7021:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7022:             $thisallowed.=$1;
                   7023:         }
1.12      www      7024:     }
1.52      www      7025: 
1.1141    raeburn  7026: # User who is not author or co-author might still be able to edit
                   7027: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7028:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7029:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7030:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7031:             $thisallowed.=$1;
                   7032:         }
                   7033:     }
                   7034: 
1.52      www      7035: # Course: uri itself is a course
1.66      www      7036:     my $courseuri=$uri;
                   7037:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7038:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7039: 
1.620     albertel 7040:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7041:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7042:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7043:             $thisallowed.=$1;
                   7044:         }
1.12      www      7045:     }
1.29      www      7046: 
1.665     albertel 7047: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7048: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7049:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7050: 	$thisallowed='';
1.671     raeburn  7051:         my ($match)=&is_on_map($uri);
                   7052:         if ($match) {
                   7053:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7054:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7055:                 my $value = $1;
                   7056:                 if ($noblockcheck) {
                   7057:                     $thisallowed.=$value;
1.1162    raeburn  7058:                 } else {
1.1281    raeburn  7059:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7060:                     if (@blockers > 0) {
                   7061:                         $thisallowed = 'B';
                   7062:                     } else {
                   7063:                         $thisallowed.=$value;
                   7064:                     }
1.1162    raeburn  7065:                 }
1.671     raeburn  7066:             }
                   7067:         } else {
1.705     albertel 7068:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7069:             if ($refuri) {
                   7070:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7071:                     $thisallowed='F';
1.671     raeburn  7072:                 } else {
                   7073:                     $refuri=&declutter($refuri);
                   7074:                     my ($match) = &is_on_map($refuri);
                   7075:                     if ($match) {
1.1281    raeburn  7076:                         if ($noblockcheck) {
                   7077:                             $thisallowed='F';
1.1162    raeburn  7078:                         } else {
1.1281    raeburn  7079:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7080:                             if (@blockers > 0) {
                   7081:                                 $thisallowed = 'B';
                   7082:                             } else {
                   7083:                                 $thisallowed='F';
                   7084:                             }
1.1162    raeburn  7085:                         }
1.671     raeburn  7086:                     }
1.669     raeburn  7087:                 }
1.671     raeburn  7088:             }
                   7089:         }
1.314     www      7090:     }
1.492     albertel 7091: 
1.766     albertel 7092:     if ($priv eq 'bre'
                   7093: 	&& $thisallowed ne 'F' 
                   7094: 	&& $thisallowed ne '2'
                   7095: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7096: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7097:     }
1.1250    raeburn  7098: 
1.52      www      7099: # Full access at system, domain or course-wide level? Exit.
1.29      www      7100:     if ($thisallowed=~/F/) {
                   7101: 	return 'F';
                   7102:     }
                   7103: 
1.52      www      7104: # If this is generating or modifying users, exit with special codes
1.29      www      7105: 
1.643     www      7106:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7107: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7108: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7109: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7110: 	    unless ($auname) { return $thisallowed; }
                   7111: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7112: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7113: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7114: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7115: 	}
1.52      www      7116: 	return $thisallowed;
                   7117:     }
                   7118: #
1.103     harris41 7119: # Gathered so far: system, domain and course wide privileges
1.52      www      7120: #
                   7121: # Course: See if uri or referer is an individual resource that is part of 
                   7122: # the course
                   7123: 
1.620     albertel 7124:     if ($env{'request.course.id'}) {
1.232     www      7125: 
1.620     albertel 7126:        $courseprivid=$env{'request.course.id'};
                   7127:        if ($env{'request.course.sec'}) {
                   7128:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7129:        }
                   7130:        $courseprivid=~s/\_/\//;
                   7131:        my $checkreferer=1;
1.232     www      7132:        my ($match,$cond)=&is_on_map($uri);
                   7133:        if ($match) {
                   7134:            $statecond=$cond;
1.620     albertel 7135:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7136:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7137:                my $value = $1;
                   7138:                if ($priv eq 'bre') {
1.1281    raeburn  7139:                    if ($noblockcheck) {
                   7140:                        $thisallowed.=$value;
1.1162    raeburn  7141:                    } else {
1.1281    raeburn  7142:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7143:                        if (@blockers > 0) {
                   7144:                            $thisallowed = 'B';
                   7145:                        } else {
                   7146:                            $thisallowed.=$value;
                   7147:                        }
1.1162    raeburn  7148:                    }
                   7149:                } else {
                   7150:                    $thisallowed.=$value;
                   7151:                }
1.52      www      7152:                $checkreferer=0;
                   7153:            }
1.29      www      7154:        }
1.83      www      7155:        
1.148     www      7156:        if ($checkreferer) {
1.620     albertel 7157: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7158:             unless ($refuri) {
1.800     albertel 7159:                 foreach my $key (keys(%env)) {
                   7160: 		    if ($key=~/^httpref\..*\*/) {
                   7161: 			my $pattern=$key;
1.156     www      7162:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7163:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7164:                         $pattern=~s/\//\\\//g;
1.152     www      7165:                         if ($orguri=~/$pattern/) {
1.800     albertel 7166: 			    $refuri=$env{$key};
1.148     www      7167:                         }
                   7168:                     }
1.191     harris41 7169:                 }
1.148     www      7170:             }
1.232     www      7171: 
1.148     www      7172:          if ($refuri) { 
1.152     www      7173: 	  $refuri=&declutter($refuri);
1.232     www      7174:           my ($match,$cond)=&is_on_map($refuri);
                   7175:             if ($match) {
                   7176:               my $refstatecond=$cond;
1.620     albertel 7177:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7178:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7179:                   my $value = $1;
                   7180:                   if ($priv eq 'bre') {
1.1281    raeburn  7181:                       if ($noblockcheck) {
                   7182:                           $thisallowed.=$value;
1.1162    raeburn  7183:                       } else {
1.1281    raeburn  7184:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7185:                           if (@blockers > 0) {
                   7186:                               $thisallowed = 'B';
                   7187:                           } else {
                   7188:                               $thisallowed.=$value;
                   7189:                           }
1.1162    raeburn  7190:                       }
                   7191:                   } else {
                   7192:                       $thisallowed.=$value;
                   7193:                   }
1.53      www      7194:                   $uri=$refuri;
                   7195:                   $statecond=$refstatecond;
1.52      www      7196:               }
                   7197:           }
1.148     www      7198:         }
1.29      www      7199:        }
1.52      www      7200:    }
1.29      www      7201: 
1.52      www      7202: #
1.103     harris41 7203: # Gathered now: all privileges that could apply, and condition number
1.52      www      7204: # 
                   7205: #
                   7206: # Full or no access?
                   7207: #
1.29      www      7208: 
1.52      www      7209:     if ($thisallowed=~/F/) {
                   7210: 	return 'F';
                   7211:     }
1.29      www      7212: 
1.52      www      7213:     unless ($thisallowed) {
                   7214:         return '';
                   7215:     }
1.29      www      7216: 
1.52      www      7217: # Restrictions exist, deal with them
                   7218: #
                   7219: #   C:according to course preferences
                   7220: #   R:according to resource settings
                   7221: #   L:unless locked
                   7222: #   X:according to user session state
                   7223: #
                   7224: 
                   7225: # Possibly locked functionality, check all courses
1.54      www      7226: # Locks might take effect only after 10 minutes cache expiration for other
                   7227: # courses, and 2 minutes for current course
1.52      www      7228: 
                   7229:     my $envkey;
                   7230:     if ($thisallowed=~/L/) {
1.1000    raeburn  7231:         foreach $envkey (keys(%env)) {
1.54      www      7232:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7233:                my $courseid=$2;
                   7234:                my $roleid=$1.'.'.$2;
1.92      www      7235:                $courseid=~s/^\///;
1.54      www      7236:                my $expiretime=600;
1.620     albertel 7237:                if ($env{'request.role'} eq $roleid) {
1.54      www      7238: 		  $expiretime=120;
                   7239:                }
                   7240: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7241:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7242:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7243: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7244:                }
1.620     albertel 7245:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7246:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7247: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7248:                        &log($env{'user.domain'},$env{'user.name'},
                   7249:                             $env{'user.home'},
1.57      www      7250:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7251:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7252:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7253: 		       return '';
                   7254:                    }
                   7255:                }
1.620     albertel 7256:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7257:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7258: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7259:                        &log($env{'user.domain'},$env{'user.name'},
                   7260:                             $env{'user.home'},
1.57      www      7261:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7262:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7263:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7264: 		       return '';
                   7265:                    }
                   7266:                }
                   7267: 	   }
1.29      www      7268:        }
1.52      www      7269:     }
                   7270:    
                   7271: #
                   7272: # Rest of the restrictions depend on selected course
                   7273: #
                   7274: 
1.620     albertel 7275:     unless ($env{'request.course.id'}) {
1.766     albertel 7276: 	if ($thisallowed eq 'A') {
                   7277: 	    return 'A';
1.814     raeburn  7278:         } elsif ($thisallowed eq 'B') {
                   7279:             return 'B';
1.766     albertel 7280: 	} else {
                   7281: 	    return '1';
                   7282: 	}
1.52      www      7283:     }
1.29      www      7284: 
1.52      www      7285: #
                   7286: # Now user is definitely in a course
                   7287: #
1.53      www      7288: 
                   7289: 
                   7290: # Course preferences
                   7291: 
                   7292:    if ($thisallowed=~/C/) {
1.620     albertel 7293:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7294:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7295:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7296: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7297: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7298: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7299: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7300: 			$env{'request.course.id'});
                   7301: 	   }
1.237     www      7302:            return '';
                   7303:        }
                   7304: 
1.620     albertel 7305:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7306: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7307: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7308: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7309: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7310: 			$env{'request.course.id'});
                   7311: 	   }
1.54      www      7312:            return '';
                   7313:        }
1.53      www      7314:    }
                   7315: 
                   7316: # Resource preferences
                   7317: 
                   7318:    if ($thisallowed=~/R/) {
1.620     albertel 7319:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7320:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7321: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7322: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7323: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7324: 	   }
                   7325: 	   return '';
1.54      www      7326:        }
1.53      www      7327:    }
1.30      www      7328: 
1.246     www      7329: # Restricted by state or randomout?
1.30      www      7330: 
1.52      www      7331:    if ($thisallowed=~/X/) {
1.620     albertel 7332:       if ($env{'acc.randomout'}) {
1.579     albertel 7333: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7334:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7335:             return ''; 
                   7336:          }
1.247     www      7337:       }
                   7338:       if (&condval($statecond)) {
1.52      www      7339: 	 return '2';
                   7340:       } else {
                   7341:          return '';
                   7342:       }
                   7343:    }
1.30      www      7344: 
1.766     albertel 7345:     if ($thisallowed eq 'A') {
                   7346: 	return 'A';
1.814     raeburn  7347:     } elsif ($thisallowed eq 'B') {
                   7348:         return 'B';
1.766     albertel 7349:     }
1.52      www      7350:    return 'F';
1.232     www      7351: }
1.1162    raeburn  7352: 
1.1192    raeburn  7353: # ------------------------------------------- Check construction space access
                   7354: 
                   7355: sub constructaccess {
                   7356:     my ($url,$setpriv)=@_;
                   7357: 
                   7358: # We do not allow editing of previous versions of files
                   7359:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7360: 
                   7361: # Get username and domain from URL
                   7362:     my ($ownername,$ownerdomain,$ownerhome);
                   7363: 
                   7364:     ($ownerdomain,$ownername) =
1.1297    damieng  7365:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
1.1192    raeburn  7366: 
                   7367: # The URL does not really point to any authorspace, forget it
                   7368:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7369: 
                   7370: # Now we need to see if the user has access to the authorspace of
                   7371: # $ownername at $ownerdomain
                   7372: 
                   7373:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7374: # Real author for this?
                   7375:        $ownerhome = $env{'user.home'};
                   7376:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7377:           return ($ownername,$ownerdomain,$ownerhome);
                   7378:        }
                   7379:     } else {
                   7380: # Co-author for this?
                   7381:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7382:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7383:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7384:             return ($ownername,$ownerdomain,$ownerhome);
                   7385:         }
                   7386:     }
                   7387: 
                   7388: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7389: # we might as well leave
                   7390:    unless ($setpriv) { return ''; }
                   7391: 
                   7392: # Backdoor access?
                   7393:     my $allowed=&allowed('eco',$ownerdomain);
                   7394: # Nope
                   7395:     unless ($allowed) { return ''; }
                   7396: # Looks like we may have access, but could be locked by the owner of the construction space
                   7397:     if ($allowed eq 'U') {
                   7398:         my %blocked=&get('environment',['domcoord.author'],
                   7399:                          $ownerdomain,$ownername);
                   7400: # Is blocked by owner
                   7401:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7402:     }
                   7403:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7404: # Grant temporary access
                   7405:         my $then=$env{'user.login.time'};
1.1209    raeburn  7406:         my $update=$env{'user.update.time'};
1.1192    raeburn  7407:         if (!$update) { $update = $then; }
                   7408:         my $refresh=$env{'user.refresh.time'};
                   7409:         if (!$refresh) { $refresh = $update; }
                   7410:         my $now = time;
                   7411:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7412:                            $now,'ca','constructaccess');
                   7413:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7414:         return($ownername,$ownerdomain,$ownerhome);
                   7415:     }
                   7416: # No business here
                   7417:     return '';
                   7418: }
                   7419: 
1.1282    raeburn  7420: # ----------------------------------------------------------- Content Blocking
                   7421: 
                   7422: {
                   7423: # Caches for faster Course Contents display where content blocking
                   7424: # is in operation (i.e., interval param set) for timed quiz.
                   7425: #
                   7426: # User for whom data are being temporarily cached.
                   7427: my $cacheduser='';
                   7428: # Cached blockers for this user (a hash of blocking items). 
                   7429: my %cachedblockers=();
                   7430: # When the data were last cached.
                   7431: my $cachedlast='';
                   7432: 
                   7433: sub load_all_blockers {
                   7434:     my ($uname,$udom,$blocks)=@_;
                   7435:     if (($uname ne '') && ($udom ne '')) { 
                   7436:         if (($cacheduser eq $uname.':'.$udom) &&
                   7437:             (abs($cachedlast-time)<5)) {
                   7438:             return;
                   7439:         }
                   7440:     }
                   7441:     $cachedlast=time;
                   7442:     $cacheduser=$uname.':'.$udom;
                   7443:     %cachedblockers = &get_commblock_resources($blocks);
                   7444: }
                   7445: 
1.1162    raeburn  7446: sub get_comm_blocks {
                   7447:     my ($cdom,$cnum) = @_;
                   7448:     if ($cdom eq '' || $cnum eq '') {
                   7449:         return unless ($env{'request.course.id'});
                   7450:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7451:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7452:     }
                   7453:     my %commblocks;
                   7454:     my $hashid=$cdom.'_'.$cnum;
                   7455:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7456:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7457:         %commblocks = %{$blocksref};
                   7458:     } else {
                   7459:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7460:         my $cachetime = 600;
                   7461:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7462:     }
                   7463:     return %commblocks;
                   7464: }
                   7465: 
1.1282    raeburn  7466: sub get_commblock_resources {
                   7467:     my ($blocks) = @_;
                   7468:     my %blockers = ();
                   7469:     return %blockers unless ($env{'request.course.id'});
                   7470:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7471:     my %commblocks;
                   7472:     if (ref($blocks) eq 'HASH') {
                   7473:         %commblocks = %{$blocks};
                   7474:     } else {
                   7475:         %commblocks = &get_comm_blocks();
                   7476:     }
1.1282    raeburn  7477:     return %blockers unless (keys(%commblocks) > 0); 
                   7478:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7479:     return %blockers unless (ref($navmap));
1.1162    raeburn  7480:     my $now = time;
                   7481:     foreach my $block (keys(%commblocks)) {
                   7482:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7483:             my ($start,$end) = ($1,$2);
                   7484:             if ($start <= $now && $end >= $now) {
                   7485:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7486:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7487:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7488:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7489:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7490:                             }
                   7491:                         }
                   7492:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7493:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7494:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7495:                             }
                   7496:                         }
                   7497:                     }
                   7498:                 }
                   7499:             }
                   7500:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7501:             my $item = $1;
1.1163    raeburn  7502:             my @to_test;
1.1162    raeburn  7503:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7504:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7505:                     my @interval;
                   7506:                     my $type = 'map';
                   7507:                     if ($item eq 'course') {
                   7508:                         $type = 'course';
                   7509:                         @interval=&EXT("resource.0.interval");
                   7510:                     } else {
                   7511:                         if ($item =~ /___\d+___/) {
                   7512:                             $type = 'resource';
                   7513:                             @interval=&EXT("resource.0.interval",$item);
                   7514:                             if (ref($navmap)) {                        
                   7515:                                 my $res = $navmap->getBySymb($item); 
                   7516:                                 push(@to_test,$res);
                   7517:                             }
1.1162    raeburn  7518:                         } else {
1.1282    raeburn  7519:                             my $mapsymb = &symbread($item,1);
                   7520:                             if ($mapsymb) {
                   7521:                                 if (ref($navmap)) {
                   7522:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7523:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7524:                                     foreach my $res (@to_test) {
                   7525:                                         my $symb = $res->symb();
                   7526:                                         next if ($symb eq $mapsymb);
                   7527:                                         if ($symb ne '') {
                   7528:                                             @interval=&EXT("resource.0.interval",$symb);
                   7529:                                             if ($interval[1] eq 'map') {
                   7530:                                                 last;
1.1162    raeburn  7531:                                             }
                   7532:                                         }
                   7533:                                     }
                   7534:                                 }
                   7535:                             }
                   7536:                         }
1.1282    raeburn  7537:                     }
1.1310    raeburn  7538:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7539:                         my $timelimit = $1; 
1.1282    raeburn  7540:                         my $first_access;
                   7541:                         if ($type eq 'resource') {
                   7542:                             $first_access=&get_first_access($interval[1],$item);
                   7543:                         } elsif ($type eq 'map') {
                   7544:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7545:                         } else {
                   7546:                             $first_access=&get_first_access($interval[1]);
                   7547:                         }
                   7548:                         if ($first_access) {
1.1292    raeburn  7549:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7550:                             if ($timesup > $now) {
                   7551:                                 my $activeblock;
                   7552:                                 foreach my $res (@to_test) {
1.1283    raeburn  7553:                                     if ($res->answerable()) {
1.1282    raeburn  7554:                                         $activeblock = 1;
                   7555:                                         last;
                   7556:                                     }
                   7557:                                 }
                   7558:                                 if ($activeblock) {
                   7559:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7560:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7561:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7562:                                          }
                   7563:                                     }
                   7564:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7565:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7566:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7567:                                         }
1.1162    raeburn  7568:                                     }
                   7569:                                 }
                   7570:                             }
                   7571:                         }
                   7572:                     }
                   7573:                 }
                   7574:             }
                   7575:         }
                   7576:     }
1.1282    raeburn  7577:     return %blockers;
1.1162    raeburn  7578: }
                   7579: 
1.1282    raeburn  7580: sub has_comm_blocking {
                   7581:     my ($priv,$symb,$uri,$blocks) = @_;
                   7582:     my @blockers;
                   7583:     return unless ($env{'request.course.id'});
                   7584:     return unless ($priv eq 'bre');
                   7585:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7586:     return if ($env{'request.state'} eq 'construct');
                   7587:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7588:     return unless (keys(%cachedblockers) > 0);
                   7589:     my (%possibles,@symbs);
                   7590:     if (!$symb) {
                   7591:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7592:     }
1.1282    raeburn  7593:     if ($symb) {
                   7594:         @symbs = ($symb);
                   7595:     } elsif (keys(%possibles)) { 
                   7596:         @symbs = keys(%possibles);
                   7597:     }
                   7598:     my $noblock;
                   7599:     foreach my $symb (@symbs) {
                   7600:         last if ($noblock);
                   7601:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7602:         foreach my $block (keys(%cachedblockers)) {
                   7603:             if ($block =~ /^firstaccess____(.+)$/) {
                   7604:                 my $item = $1;
                   7605:                 if (($item eq $map) || ($item eq $symb)) {
                   7606:                     $noblock = 1;
                   7607:                     last;
                   7608:                 }
                   7609:             }
                   7610:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7611:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7612:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7613:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7614:                             push(@blockers,$block);
                   7615:                         }
                   7616:                     }
                   7617:                 }
1.1162    raeburn  7618:             }
1.1282    raeburn  7619:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7620:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7621:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7622:                         push(@blockers,$block);
                   7623:                     }
                   7624:                 }
1.1162    raeburn  7625:             }
                   7626:         }
                   7627:     }
1.1282    raeburn  7628:     return if ($noblock);
                   7629:     return @blockers;
                   7630: }
1.1162    raeburn  7631: }
                   7632: 
1.1282    raeburn  7633: # -------------------------------- Deversion and split uri into path an filename   
                   7634: 
1.1133    foxr     7635: #
1.1282    raeburn  7636: #   Removes the version from a URI and
1.1133    foxr     7637: #   splits it in to its filename and path to the filename.
                   7638: #   Seems like File::Basename could have done this more clearly.
                   7639: #   Parameters:
                   7640: #      $uri   - input URI
                   7641: #   Returns:
                   7642: #     Two element list consisting of 
                   7643: #     $pathname  - the URI up to and excluding the trailing /
                   7644: #     $filename  - The part of the URI following the last /
                   7645: #  NOTE:
                   7646: #    Another realization of this is simply:
                   7647: #    use File::Basename;
                   7648: #    ...
                   7649: #    $uri = shift;
                   7650: #    $filename = basename($uri);
                   7651: #    $path     = dirname($uri);
                   7652: #    return ($filename, $path);
                   7653: #
                   7654: #     The implementation below is probably faster however.
                   7655: #
1.710     albertel 7656: sub split_uri_for_cond {
                   7657:     my $uri=&deversion(&declutter(shift));
                   7658:     my @uriparts=split(/\//,$uri);
                   7659:     my $filename=pop(@uriparts);
                   7660:     my $pathname=join('/',@uriparts);
                   7661:     return ($pathname,$filename);
                   7662: }
1.232     www      7663: # --------------------------------------------------- Is a resource on the map?
                   7664: 
                   7665: sub is_on_map {
1.710     albertel 7666:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7667:     #Trying to find the conditional for the file
1.620     albertel 7668:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7669: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7670:     if ($match) {
1.289     bowersj2 7671: 	return (1,$1);
                   7672:     } else {
1.434     www      7673: 	return (0,0);
1.289     bowersj2 7674:     }
1.12      www      7675: }
                   7676: 
1.427     www      7677: # --------------------------------------------------------- Get symb from alias
                   7678: 
                   7679: sub get_symb_from_alias {
                   7680:     my $symb=shift;
                   7681:     my ($map,$resid,$url)=&decode_symb($symb);
                   7682: # Already is a symb
                   7683:     if ($url) { return $symb; }
                   7684: # Must be an alias
                   7685:     my $aliassymb='';
                   7686:     my %bighash;
1.620     albertel 7687:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7688:                             &GDBM_READER(),0640)) {
                   7689:         my $rid=$bighash{'mapalias_'.$symb};
                   7690: 	if ($rid) {
                   7691: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7692: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7693: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7694: 	}
                   7695:         untie %bighash;
                   7696:     }
                   7697:     return $aliassymb;
                   7698: }
                   7699: 
1.12      www      7700: # ----------------------------------------------------------------- Define Role
                   7701: 
                   7702: sub definerole {
                   7703:   if (allowed('mcr','/')) {
                   7704:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7705:     foreach my $role (split(':',$sysrole)) {
                   7706: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7707:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7708:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7709: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7710:                return "refused:s:$crole&$cqual"; 
                   7711:             }
                   7712:         }
1.191     harris41 7713:     }
1.800     albertel 7714:     foreach my $role (split(':',$domrole)) {
                   7715: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7716:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7717:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7718: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7719:                return "refused:d:$crole&$cqual"; 
                   7720:             }
                   7721:         }
1.191     harris41 7722:     }
1.800     albertel 7723:     foreach my $role (split(':',$courole)) {
                   7724: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7725:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7726:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7727: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7728:                return "refused:c:$crole&$cqual"; 
                   7729:             }
                   7730:         }
1.191     harris41 7731:     }
1.620     albertel 7732:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7733:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7734: 	        "rolesdef_$rolename=".
                   7735:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7736:     return reply($command,$env{'user.home'});
1.12      www      7737:   } else {
                   7738:     return 'refused';
                   7739:   }
1.105     harris41 7740: }
                   7741: 
                   7742: # ---------------- Make a metadata query against the network of library servers
                   7743: 
                   7744: sub metadata_query {
1.1237    raeburn  7745:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7746:     my %rhash;
1.845     albertel 7747:     my %libserv = &all_library();
1.244     matthew  7748:     my @server_list = (defined($server_array) ? @$server_array
                   7749:                                               : keys(%libserv) );
                   7750:     for my $server (@server_list) {
1.1237    raeburn  7751:         my $domains = ''; 
                   7752:         if (ref($domains_hash) eq 'HASH') {
                   7753:             $domains = $domains_hash->{$server}; 
                   7754:         }
1.118     harris41 7755: 	unless ($custom or $customshow) {
1.1237    raeburn  7756: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7757: 	    $rhash{$server}=$reply;
                   7758: 	}
                   7759: 	else {
                   7760: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7761: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7762: 			     $server);
                   7763: 	    $rhash{$server}=$reply;
                   7764: 	}
1.112     harris41 7765:     }
1.118     harris41 7766:     return \%rhash;
1.240     www      7767: }
                   7768: 
                   7769: # ----------------------------------------- Send log queries and wait for reply
                   7770: 
                   7771: sub log_query {
                   7772:     my ($uname,$udom,$query,%filters)=@_;
                   7773:     my $uhome=&homeserver($uname,$udom);
                   7774:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7775:     my $uhost=&hostname($uhome);
1.800     albertel 7776:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7777:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7778:                        $uhome);
1.479     albertel 7779:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7780:     return get_query_reply($queryid);
                   7781: }
                   7782: 
1.818     raeburn  7783: # -------------------------- Update MySQL table for portfolio file
                   7784: 
                   7785: sub update_portfolio_table {
1.821     raeburn  7786:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7787:     if ($group ne '') {
                   7788:         $file_name =~s /^\Q$group\E//;
                   7789:     }
1.818     raeburn  7790:     my $homeserver = &homeserver($uname,$udom);
                   7791:     my $queryid=
1.821     raeburn  7792:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7793:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7794:     my $reply = &get_query_reply($queryid);
                   7795:     return $reply;
                   7796: }
                   7797: 
1.899     raeburn  7798: # -------------------------- Update MySQL allusers table
                   7799: 
                   7800: sub update_allusers_table {
                   7801:     my ($uname,$udom,$names) = @_;
                   7802:     my $homeserver = &homeserver($uname,$udom);
                   7803:     my $queryid=
                   7804:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7805:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7806:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7807:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7808:                'generation='.&escape($names->{'generation'}).'%%'.
                   7809:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7810:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7811:     return;
1.899     raeburn  7812: }
                   7813: 
1.508     raeburn  7814: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7815: 
                   7816: sub fetch_enrollment_query {
1.511     raeburn  7817:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7818:     my $homeserver;
1.547     raeburn  7819:     my $maxtries = 1;
1.508     raeburn  7820:     if ($context eq 'automated') {
                   7821:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7822:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7823:     } else {
                   7824:         $homeserver = &homeserver($cnum,$dom);
                   7825:     }
1.838     albertel 7826:     my $host=&hostname($homeserver);
1.506     raeburn  7827:     my $cmd = '';
1.1000    raeburn  7828:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7829:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7830:     }
                   7831:     $cmd =~ s/%%$//;
                   7832:     $cmd = &escape($cmd);
                   7833:     my $query = 'fetchenrollment';
1.620     albertel 7834:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7835:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7836:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7837:         return 'error: '.$queryid;
                   7838:     }
1.506     raeburn  7839:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7840:     my $tries = 1;
                   7841:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7842:         $reply = &get_query_reply($queryid);
                   7843:         $tries ++;
                   7844:     }
1.526     raeburn  7845:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7846:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7847:     } else {
1.901     albertel 7848:         my @responses = split(/:/,$reply);
1.515     raeburn  7849:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7850:             foreach my $line (@responses) {
                   7851:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7852:                 $$replyref{$key} = $value;
                   7853:             }
                   7854:         } else {
1.1117    foxr     7855:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7856:             foreach my $line (@responses) {
                   7857:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7858:                 $$replyref{$key} = $value;
                   7859:                 if ($value > 0) {
1.800     albertel 7860:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7861:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7862:                         my $destname = $pathname.'/'.$filename;
                   7863:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7864:                         if ($xml_classlist =~ /^error/) {
                   7865:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7866:                         } else {
1.506     raeburn  7867:                             if ( open(FILE,">$destname") ) {
                   7868:                                 print FILE &unescape($xml_classlist);
                   7869:                                 close(FILE);
1.526     raeburn  7870:                             } else {
                   7871:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7872:                             }
                   7873:                         }
                   7874:                     }
                   7875:                 }
                   7876:             }
                   7877:         }
                   7878:         return 'ok';
                   7879:     }
                   7880:     return 'error';
                   7881: }
                   7882: 
1.242     www      7883: sub get_query_reply {
                   7884:     my $queryid=shift;
1.1117    foxr     7885:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7886:     my $reply='';
                   7887:     for (1..100) {
1.1289    damieng  7888: 	sleep(0.2);
1.240     www      7889:         if (-e $replyfile.'.end') {
1.448     albertel 7890: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7891: 		$reply = join('',<$fh>);
                   7892: 		close($fh);
1.240     www      7893: 	   } else { return 'error: reply_file_error'; }
1.242     www      7894:            return &unescape($reply);
                   7895: 	}
1.240     www      7896:     }
1.242     www      7897:     return 'timeout:'.$queryid;
1.240     www      7898: }
                   7899: 
                   7900: sub courselog_query {
1.241     www      7901: #
                   7902: # possible filters:
                   7903: # url: url or symb
                   7904: # username
                   7905: # domain
                   7906: # action: view, submit, grade
                   7907: # start: timestamp
                   7908: # end: timestamp
                   7909: #
1.240     www      7910:     my (%filters)=@_;
1.620     albertel 7911:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7912:     if ($filters{'url'}) {
                   7913: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7914:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7915:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7916:     }
1.620     albertel 7917:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7918:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7919:     return &log_query($cname,$cdom,'courselog',%filters);
                   7920: }
                   7921: 
                   7922: sub userlog_query {
1.858     raeburn  7923: #
                   7924: # possible filters:
                   7925: # action: log check role
                   7926: # start: timestamp
                   7927: # end: timestamp
                   7928: #
1.240     www      7929:     my ($uname,$udom,%filters)=@_;
                   7930:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7931: }
                   7932: 
1.506     raeburn  7933: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7934: 
                   7935: sub auto_run {
1.508     raeburn  7936:     my ($cnum,$cdom) = @_;
1.876     raeburn  7937:     my $response = 0;
                   7938:     my $settings;
                   7939:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7940:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7941:         $settings = $domconfig{'autoenroll'};
                   7942:         if ($settings->{'run'} eq '1') {
                   7943:             $response = 1;
                   7944:         }
                   7945:     } else {
1.934     raeburn  7946:         my $homeserver;
                   7947:         if (&is_course($cdom,$cnum)) {
                   7948:             $homeserver = &homeserver($cnum,$cdom);
                   7949:         } else {
                   7950:             $homeserver = &domain($cdom,'primary');
                   7951:         }
                   7952:         if ($homeserver ne 'no_host') {
                   7953:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7954:         }
1.876     raeburn  7955:     }
1.506     raeburn  7956:     return $response;
                   7957: }
1.776     albertel 7958: 
1.506     raeburn  7959: sub auto_get_sections {
1.508     raeburn  7960:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7961:     my $homeserver;
                   7962:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7963:         $homeserver = &homeserver($cnum,$cdom);
                   7964:     }
                   7965:     if (!defined($homeserver)) { 
                   7966:         if ($cdom =~ /^$match_domain$/) {
                   7967:             $homeserver = &domain($cdom,'primary');
                   7968:         }
                   7969:     }
                   7970:     my @secs;
                   7971:     if (defined($homeserver)) {
                   7972:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7973:         unless ($response eq 'refused') {
                   7974:             @secs = split(/:/,$response);
                   7975:         }
1.506     raeburn  7976:     }
                   7977:     return @secs;
                   7978: }
1.776     albertel 7979: 
1.506     raeburn  7980: sub auto_new_course {
1.1099    raeburn  7981:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7982:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7983:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7984:     return $response;
                   7985: }
1.776     albertel 7986: 
1.506     raeburn  7987: sub auto_validate_courseID {
1.508     raeburn  7988:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7989:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7990:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7991:     return $response;
                   7992: }
1.776     albertel 7993: 
1.1007    raeburn  7994: sub auto_validate_instcode {
1.1020    raeburn  7995:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7996:     my ($homeserver,$response);
                   7997:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7998:         $homeserver = &homeserver($cnum,$cdom);
                   7999:     }
                   8000:     if (!defined($homeserver)) {
                   8001:         if ($cdom =~ /^$match_domain$/) {
                   8002:             $homeserver = &domain($cdom,'primary');
                   8003:         }
                   8004:     }
1.1065    raeburn  8005:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8006:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8007:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8008:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8009: }
                   8010: 
1.506     raeburn  8011: sub auto_create_password {
1.873     raeburn  8012:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8013:     my ($homeserver,$response);
1.506     raeburn  8014:     my $create_passwd = 0;
                   8015:     my $authchk = '';
1.873     raeburn  8016:     if ($udom =~ /^$match_domain$/) {
                   8017:         $homeserver = &domain($udom,'primary');
                   8018:     }
                   8019:     if ($homeserver eq '') {
                   8020:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8021:             $homeserver = &homeserver($cnum,$cdom);
                   8022:         }
                   8023:     }
                   8024:     if ($homeserver eq '') {
                   8025:         $authchk = 'nodomain';
1.506     raeburn  8026:     } else {
1.873     raeburn  8027:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8028:         if ($response eq 'refused') {
                   8029:             $authchk = 'refused';
                   8030:         } else {
1.901     albertel 8031:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8032:         }
1.506     raeburn  8033:     }
                   8034:     return ($authparam,$create_passwd,$authchk);
                   8035: }
                   8036: 
1.706     raeburn  8037: sub auto_photo_permission {
                   8038:     my ($cnum,$cdom,$students) = @_;
                   8039:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8040:     my ($outcome,$perm_reqd,$conditions) = 
                   8041: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8042:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8043: 	return (undef,undef);
                   8044:     }
1.706     raeburn  8045:     return ($outcome,$perm_reqd,$conditions);
                   8046: }
                   8047: 
                   8048: sub auto_checkphotos {
                   8049:     my ($uname,$udom,$pid) = @_;
                   8050:     my $homeserver = &homeserver($uname,$udom);
                   8051:     my ($result,$resulttype);
                   8052:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8053: 				   &escape($uname).':'.&escape($pid),
                   8054: 				   $homeserver));
1.709     albertel 8055:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8056: 	return (undef,undef);
                   8057:     }
1.706     raeburn  8058:     if ($outcome) {
                   8059:         ($result,$resulttype) = split(/:/,$outcome);
                   8060:     } 
                   8061:     return ($result,$resulttype);
                   8062: }
                   8063: 
                   8064: sub auto_photochoice {
                   8065:     my ($cnum,$cdom) = @_;
                   8066:     my $homeserver = &homeserver($cnum,$cdom);
                   8067:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8068: 						       &escape($cdom),
                   8069: 						       $homeserver)));
1.709     albertel 8070:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8071: 	return (undef,undef);
                   8072:     }
1.706     raeburn  8073:     return ($update,$comment);
                   8074: }
                   8075: 
                   8076: sub auto_photoupdate {
                   8077:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8078:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8079:     my $host=&hostname($homeserver);
1.706     raeburn  8080:     my $cmd = '';
                   8081:     my $maxtries = 1;
1.800     albertel 8082:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8083:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8084:     }
                   8085:     $cmd =~ s/%%$//;
                   8086:     $cmd = &escape($cmd);
                   8087:     my $query = 'institutionalphotos';
                   8088:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8089:     unless ($queryid=~/^\Q$host\E\_/) {
                   8090:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8091:         return 'error: '.$queryid;
                   8092:     }
                   8093:     my $reply = &get_query_reply($queryid);
                   8094:     my $tries = 1;
                   8095:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8096:         $reply = &get_query_reply($queryid);
                   8097:         $tries ++;
                   8098:     }
                   8099:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8100:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8101:     } else {
                   8102:         my @responses = split(/:/,$reply);
                   8103:         my $outcome = shift(@responses); 
                   8104:         foreach my $item (@responses) {
                   8105:             my ($key,$value) = split(/=/,$item);
                   8106:             $$photo{$key} = $value;
                   8107:         }
                   8108:         return $outcome;
                   8109:     }
                   8110:     return 'error';
                   8111: }
                   8112: 
1.521     raeburn  8113: sub auto_instcode_format {
1.793     albertel 8114:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8115: 	$cat_order) = @_;
1.521     raeburn  8116:     my $courses = '';
1.772     raeburn  8117:     my @homeservers;
1.521     raeburn  8118:     if ($caller eq 'global') {
1.841     albertel 8119: 	my %servers = &get_servers($codedom,'library');
                   8120: 	foreach my $tryserver (keys(%servers)) {
                   8121: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8122: 		push(@homeservers,$tryserver);
                   8123: 	    }
1.584     raeburn  8124:         }
1.1022    raeburn  8125:     } elsif ($caller eq 'requests') {
                   8126:         if ($codedom =~ /^$match_domain$/) {
                   8127:             my $chome = &domain($codedom,'primary');
                   8128:             unless ($chome eq 'no_host') {
                   8129:                 push(@homeservers,$chome);
                   8130:             }
                   8131:         }
1.521     raeburn  8132:     } else {
1.772     raeburn  8133:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8134:     }
1.793     albertel 8135:     foreach my $code (keys(%{$instcodes})) {
                   8136:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8137:     }
                   8138:     chop($courses);
1.772     raeburn  8139:     my $ok_response = 0;
                   8140:     my $response;
                   8141:     while (@homeservers > 0 && $ok_response == 0) {
                   8142:         my $server = shift(@homeservers); 
                   8143:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8144:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8145:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8146: 		split(/:/,$response);
1.772     raeburn  8147:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8148:             push(@{$codetitles},&str2array($codetitles_str));
                   8149:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8150:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8151:             $ok_response = 1;
                   8152:         }
                   8153:     }
                   8154:     if ($ok_response) {
1.521     raeburn  8155:         return 'ok';
1.772     raeburn  8156:     } else {
                   8157:         return $response;
1.521     raeburn  8158:     }
                   8159: }
                   8160: 
1.792     raeburn  8161: sub auto_instcode_defaults {
                   8162:     my ($domain,$returnhash,$code_order) = @_;
                   8163:     my @homeservers;
1.841     albertel 8164: 
                   8165:     my %servers = &get_servers($domain,'library');
                   8166:     foreach my $tryserver (keys(%servers)) {
                   8167: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8168: 	    push(@homeservers,$tryserver);
                   8169: 	}
1.792     raeburn  8170:     }
1.841     albertel 8171: 
1.792     raeburn  8172:     my $response;
1.841     albertel 8173:     foreach my $server (@homeservers) {
1.792     raeburn  8174:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8175:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8176: 	
                   8177: 	foreach my $pair (split(/\&/,$response)) {
                   8178: 	    my ($name,$value)=split(/\=/,$pair);
                   8179: 	    if ($name eq 'code_order') {
                   8180: 		@{$code_order} = split(/\&/,&unescape($value));
                   8181: 	    } else {
                   8182: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8183: 	    }
                   8184: 	}
                   8185: 	return 'ok';
1.792     raeburn  8186:     }
1.841     albertel 8187: 
                   8188:     return $response;
1.1003    raeburn  8189: }
                   8190: 
                   8191: sub auto_possible_instcodes {
1.1007    raeburn  8192:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8193:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8194:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8195:         return;
                   8196:     }
1.1003    raeburn  8197:     my (@homeservers,$uhome);
                   8198:     if (defined(&domain($domain,'primary'))) {
                   8199:         $uhome=&domain($domain,'primary');
                   8200:         push(@homeservers,&domain($domain,'primary'));
                   8201:     } else {
                   8202:         my %servers = &get_servers($domain,'library');
                   8203:         foreach my $tryserver (keys(%servers)) {
                   8204:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8205:                 push(@homeservers,$tryserver);
                   8206:             }
                   8207:         }
                   8208:     }
                   8209:     my $response;
                   8210:     foreach my $server (@homeservers) {
                   8211:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8212:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8213:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8214:             split(':',$response);
                   8215:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8216:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8217:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8218:             my ($name,$value)=split('=',$item);
                   8219:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8220:         }
                   8221:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8222:             my ($name,$value)=split('=',$item);
                   8223:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8224:         }
                   8225:         return 'ok';
                   8226:     }
                   8227:     return $response;
                   8228: }
1.792     raeburn  8229: 
1.1010    raeburn  8230: sub auto_courserequest_checks {
                   8231:     my ($dom) = @_;
1.1020    raeburn  8232:     my ($homeserver,%validations);
                   8233:     if ($dom =~ /^$match_domain$/) {
                   8234:         $homeserver = &domain($dom,'primary');
                   8235:     }
                   8236:     unless ($homeserver eq 'no_host') {
                   8237:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8238:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8239:             my @items = split(/&/,$response);
                   8240:             foreach my $item (@items) {
                   8241:                 my ($key,$value) = split('=',$item);
                   8242:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8243:             }
                   8244:         }
                   8245:     }
1.1010    raeburn  8246:     return %validations; 
                   8247: }
                   8248: 
1.1020    raeburn  8249: sub auto_courserequest_validation {
1.1255    raeburn  8250:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8251:     my ($homeserver,$response);
                   8252:     if ($dom =~ /^$match_domain$/) {
                   8253:         $homeserver = &domain($dom,'primary');
                   8254:     }
1.1255    raeburn  8255:     unless ($homeserver eq 'no_host') {
                   8256:         my $customdata;
                   8257:         if (ref($custominfo) eq 'HASH') {
                   8258:             $customdata = &freeze_escape($custominfo);
                   8259:         }
1.1020    raeburn  8260:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8261:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8262:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8263:                                     $customdata,$homeserver));
1.1020    raeburn  8264:     }
                   8265:     return $response;
                   8266: }
                   8267: 
1.777     albertel 8268: sub auto_validate_class_sec {
1.918     raeburn  8269:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8270:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8271:     my $ownerlist;
                   8272:     if (ref($owners) eq 'ARRAY') {
                   8273:         $ownerlist = join(',',@{$owners});
                   8274:     } else {
                   8275:         $ownerlist = $owners;
                   8276:     }
1.773     raeburn  8277:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8278:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8279:     return $response;
                   8280: }
                   8281: 
1.1248    raeburn  8282: sub auto_crsreq_update {
                   8283:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8284:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8285:     my ($homeserver,%crsreqresponse);
                   8286:     if ($cdom =~ /^$match_domain$/) {
                   8287:         $homeserver = &domain($cdom,'primary');
                   8288:     }
                   8289:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8290:         my $info;
                   8291:         if (ref($inbound) eq 'HASH') {
                   8292:             $info = &freeze_escape($inbound);
                   8293:         }
                   8294:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8295:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8296:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8297:                             &escape($title).':'.&escape($code).':'.
                   8298:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8299:                             $homeserver);
1.1248    raeburn  8300:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8301:             my @items = split(/&/,$response);
                   8302:             foreach my $item (@items) {
                   8303:                 my ($key,$value) = split('=',$item);
                   8304:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8305:             }
                   8306:         }
                   8307:     }
                   8308:     return \%crsreqresponse;
                   8309: }
                   8310: 
1.1305    raeburn  8311: sub auto_export_grades {
1.1309    raeburn  8312:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8313:     my ($homeserver,%exportresponse);
                   8314:     if ($cdom =~ /^$match_domain$/) {
                   8315:         $homeserver = &domain($cdom,'primary');
                   8316:     }
                   8317:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8318:         my $info;
                   8319:         if (ref($inforef) eq 'HASH') {
                   8320:             $info = &freeze_escape($inforef);
                   8321:         }
                   8322:         if (ref($gradesref) eq 'HASH') {
                   8323:             my $grades = &freeze_escape($gradesref);
                   8324:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8325:                                 $info.':'.$grades,$homeserver);
                   8326:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8327:                 my @items = split(/&/,$response);
                   8328:                 foreach my $item (@items) {
                   8329:                     my ($key,$value) = split('=',$item);
                   8330:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8331:                 }
                   8332:             }
                   8333:         }
                   8334:     }
                   8335:     return \%exportresponse;
1.1305    raeburn  8336: }
                   8337: 
1.1287    raeburn  8338: sub check_instcode_cloning {
                   8339:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8340:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8341:         return;
                   8342:     }
                   8343:     my $canclone;
                   8344:     if (@{$code_order} > 0) {
                   8345:         my $instcoderegexp ='^';
                   8346:         my @clonecodes = split(/\&/,$cloner);
                   8347:         foreach my $item (@{$code_order}) {
                   8348:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8349:                 foreach my $pair (@clonecodes) {
                   8350:                     my ($key,$val) = split(/\=/,$pair,2);
                   8351:                     $val = &unescape($val);
                   8352:                     if ($key eq $item) {
                   8353:                         $instcoderegexp .= '('.$val.')';
                   8354:                         last;
                   8355:                     }
                   8356:                 }
                   8357:             } else {
                   8358:                 $instcoderegexp .= $codedefaults->{$item};
                   8359:             }
                   8360:         }
                   8361:         $instcoderegexp .= '$';
                   8362:         my (@from,@to);
                   8363:         eval {
                   8364:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8365:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8366:         };
                   8367:         if ((@from > 0) && (@to > 0)) {
                   8368:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8369:             if (!@diffs) {
                   8370:                 $canclone = 1;
                   8371:             }
                   8372:         }
                   8373:     }
                   8374:     return $canclone;
                   8375: }
                   8376: 
                   8377: sub default_instcode_cloning {
                   8378:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8379:     my (%codedefaults,@code_order,$canclone);
                   8380:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8381:         %codedefaults = %{$codedefaultsref};
                   8382:         @code_order = @{$codeorderref};
                   8383:     } elsif ($clonedom) {
                   8384:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8385:     }
                   8386:     if (($domdefclone) && (@code_order)) {
                   8387:         my @clonecodes = split(/\+/,$domdefclone);
                   8388:         my $instcoderegexp ='^';
                   8389:         foreach my $item (@code_order) {
                   8390:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8391:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8392:             } else {
                   8393:                 $instcoderegexp .= $codedefaults{$item};
                   8394:             }
                   8395:         }
                   8396:         $instcoderegexp .= '$';
                   8397:         my (@from,@to);
                   8398:         eval {
                   8399:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8400:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8401:         };
                   8402:         if ((@from > 0) && (@to > 0)) {
                   8403:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8404:             if (!@diffs) {
                   8405:                 $canclone = 1;
                   8406:             }
                   8407:         }
                   8408:     }
                   8409:     return $canclone;
                   8410: }
                   8411: 
1.679     raeburn  8412: # ------------------------------------------------------- Course Group routines
                   8413: 
                   8414: sub get_coursegroups {
1.809     raeburn  8415:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8416:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8417: }
                   8418: 
1.679     raeburn  8419: sub modify_coursegroup {
                   8420:     my ($cdom,$cnum,$groupsettings) = @_;
                   8421:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8422: }
                   8423: 
1.809     raeburn  8424: sub toggle_coursegroup_status {
                   8425:     my ($cdom,$cnum,$group,$action) = @_;
                   8426:     my ($from_namespace,$to_namespace);
                   8427:     if ($action eq 'delete') {
                   8428:         $from_namespace = 'coursegroups';
                   8429:         $to_namespace = 'deleted_groups';
                   8430:     } else {
                   8431:         $from_namespace = 'deleted_groups';
                   8432:         $to_namespace = 'coursegroups';
                   8433:     }
                   8434:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8435:     if (my $tmp = &error(%curr_group)) {
                   8436:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8437:         return ('read error',$tmp);
                   8438:     } else {
                   8439:         my %savedsettings = %curr_group; 
1.809     raeburn  8440:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8441:         my $deloutcome;
                   8442:         if ($result eq 'ok') {
1.809     raeburn  8443:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8444:         } else {
                   8445:             return ('write error',$result);
                   8446:         }
                   8447:         if ($deloutcome eq 'ok') {
                   8448:             return 'ok';
                   8449:         } else {
                   8450:             return ('delete error',$deloutcome);
                   8451:         }
                   8452:     }
                   8453: }
                   8454: 
1.679     raeburn  8455: sub modify_group_roles {
1.957     raeburn  8456:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8457:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8458:     my $role = 'gr/'.&escape($userprivs);
                   8459:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8460:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8461:     if ($result eq 'ok') {
                   8462:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8463:     }
1.679     raeburn  8464:     return $result;
                   8465: }
                   8466: 
                   8467: sub modify_coursegroup_membership {
                   8468:     my ($cdom,$cnum,$membership) = @_;
                   8469:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8470:     return $result;
                   8471: }
                   8472: 
1.682     raeburn  8473: sub get_active_groups {
                   8474:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8475:     my $now = time;
                   8476:     my %groups = ();
                   8477:     foreach my $key (keys(%env)) {
1.811     albertel 8478:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8479:             my ($start,$end) = split(/\./,$env{$key});
                   8480:             if (($end!=0) && ($end<$now)) { next; }
                   8481:             if (($start!=0) && ($start>$now)) { next; }
                   8482:             if ($1 eq $cdom && $2 eq $cnum) {
                   8483:                 $groups{$3} = $env{$key} ;
                   8484:             }
                   8485:         }
                   8486:     }
                   8487:     return %groups;
                   8488: }
                   8489: 
1.683     raeburn  8490: sub get_group_membership {
                   8491:     my ($cdom,$cnum,$group) = @_;
                   8492:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8493: }
                   8494: 
                   8495: sub get_users_groups {
                   8496:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8497:     my @usersgroups;
1.683     raeburn  8498:     my $cachetime=1800;
                   8499: 
                   8500:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8501:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8502:     if (defined($cached)) {
1.734     albertel 8503:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8504:     } else {  
                   8505:         $grouplist = '';
1.816     raeburn  8506:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8507:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8508:         my $access_end = $env{'course.'.$courseid.
                   8509:                               '.default_enrollment_end_date'};
                   8510:         my $now = time;
                   8511:         foreach my $key (keys(%roleshash)) {
                   8512:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8513:                 my $group = $1;
                   8514:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8515:                     my $start = $2;
                   8516:                     my $end = $1;
                   8517:                     if ($start == -1) { next; } # deleted from group
                   8518:                     if (($start!=0) && ($start>$now)) { next; }
                   8519:                     if (($end!=0) && ($end<$now)) {
                   8520:                         if ($access_end && $access_end < $now) {
                   8521:                             if ($access_end - $end < 86400) {
                   8522:                                 push(@usersgroups,$group);
1.733     raeburn  8523:                             }
                   8524:                         }
1.817     raeburn  8525:                         next;
1.733     raeburn  8526:                     }
1.817     raeburn  8527:                     push(@usersgroups,$group);
1.683     raeburn  8528:                 }
                   8529:             }
                   8530:         }
1.817     raeburn  8531:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8532:         $grouplist = join(':',@usersgroups);
                   8533:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8534:     }
1.733     raeburn  8535:     return @usersgroups;
1.683     raeburn  8536: }
                   8537: 
                   8538: sub devalidate_getgroups_cache {
                   8539:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8540:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8541: 
1.683     raeburn  8542:     my $hashid="$udom:$uname:$courseid";
                   8543:     &devalidate_cache_new('getgroups',$hashid);
                   8544: }
                   8545: 
1.12      www      8546: # ------------------------------------------------------------------ Plain Text
                   8547: 
                   8548: sub plaintext {
1.988     raeburn  8549:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8550:     if ($short =~ m{^cr/}) {
1.758     albertel 8551: 	return (split('/',$short))[-1];
                   8552:     }
1.742     raeburn  8553:     if (!defined($cid)) {
                   8554:         $cid = $env{'request.course.id'};
                   8555:     }
                   8556:     my %rolenames = (
1.1008    raeburn  8557:                       Course    => 'std',
                   8558:                       Community => 'alt1',
1.1305    raeburn  8559:                       Placement => 'std',
1.742     raeburn  8560:                     );
1.1037    raeburn  8561:     if ($cid ne '') {
                   8562:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8563:             unless ($forcedefault) {
                   8564:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8565:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8566:                 return &Apache::lonlocal::mt($roletext);
                   8567:             }
                   8568:         }
                   8569:     }
                   8570:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8571:         (defined($rolenames{$type})) && 
                   8572:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8573:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8574:     } elsif ($cid ne '') {
                   8575:         my $crstype = $env{'course.'.$cid.'.type'};
                   8576:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8577:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8578:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8579:         }
1.742     raeburn  8580:     }
1.1037    raeburn  8581:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8582: }
                   8583: 
                   8584: # ----------------------------------------------------------------- Assign Role
                   8585: 
                   8586: sub assignrole {
1.957     raeburn  8587:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8588:         $context)=@_;
1.21      www      8589:     my $mrole;
                   8590:     if ($role =~ /^cr\//) {
1.393     www      8591:         my $cwosec=$url;
1.811     albertel 8592:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8593: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8594:            my $refused = 1;
                   8595:            if ($context eq 'requestcourses') {
                   8596:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8597:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8598:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8599:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8600:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8601:                            if ($crsenv{'internal.courseowner'} eq
                   8602:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8603:                                $refused = '';
                   8604:                            }
                   8605:                        }
                   8606:                    }
                   8607:                }
                   8608:            }
                   8609:            if ($refused) {
                   8610:                &logthis('Refused custom assignrole: '.
                   8611:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8612:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8613:                return 'refused';
                   8614:            }
1.104     www      8615:         }
1.21      www      8616:         $mrole='cr';
1.678     raeburn  8617:     } elsif ($role =~ /^gr\//) {
                   8618:         my $cwogrp=$url;
1.811     albertel 8619:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8620:         unless (&allowed('mdg',$cwogrp)) {
                   8621:             &logthis('Refused group assignrole: '.
                   8622:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8623:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8624:             return 'refused';
                   8625:         }
                   8626:         $mrole='gr';
1.21      www      8627:     } else {
1.82      www      8628:         my $cwosec=$url;
1.811     albertel 8629:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8630:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8631:             my $refused;
                   8632:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8633:                 if (!(&allowed('c'.$role,$url))) {
                   8634:                     $refused = 1;
                   8635:                 }
                   8636:             } else {
                   8637:                 $refused = 1;
                   8638:             }
1.947     raeburn  8639:             if ($refused) {
1.1045    raeburn  8640:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8641:                 if (!$selfenroll && $context eq 'course') {
                   8642:                     my %crsenv;
                   8643:                     if ($role eq 'cc' || $role eq 'co') {
                   8644:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8645:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8646:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8647:                                 if ($crsenv{'internal.courseowner'} eq 
                   8648:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8649:                                     $refused = '';
                   8650:                                 }
                   8651:                             }
                   8652:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8653:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8654:                                 if ($crsenv{'internal.courseowner'} eq 
                   8655:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8656:                                     $refused = '';
                   8657:                                 }
                   8658:                             }
                   8659:                         }
                   8660:                     }
                   8661:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8662:                     $refused = '';
1.1017    raeburn  8663:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8664:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8665:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8666:                         my $wrongcc;
                   8667:                         if ($cnum =~ /^$match_community$/) {
                   8668:                             $wrongcc = 1 if ($role eq 'cc');
                   8669:                         } else {
                   8670:                             $wrongcc = 1 if ($role eq 'co');
                   8671:                         }
                   8672:                         unless ($wrongcc) {
                   8673:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8674:                             if ($crsenv{'internal.courseowner'} eq 
                   8675:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8676:                                 $refused = '';
                   8677:                             }
1.1017    raeburn  8678:                         }
                   8679:                     }
1.1183    raeburn  8680:                 } elsif ($context eq 'requestauthor') {
                   8681:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8682:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8683:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8684:                             $refused = '';
                   8685:                         } else {
                   8686:                             my %domdefaults = &get_domain_defaults($udom);
                   8687:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8688:                                 my $checkbystatus;
                   8689:                                 if ($env{'user.adv'}) { 
                   8690:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8691:                                     if ($disposition eq 'automatic') {
                   8692:                                         $refused = '';
                   8693:                                     } elsif ($disposition eq '') {
                   8694:                                         $checkbystatus = 1;
                   8695:                                     } 
                   8696:                                 } else {
                   8697:                                     $checkbystatus = 1;
                   8698:                                 }
                   8699:                                 if ($checkbystatus) {
                   8700:                                     if ($env{'environment.inststatus'}) {
                   8701:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8702:                                         foreach my $type (@inststatuses) {
                   8703:                                             if (($type ne '') &&
                   8704:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8705:                                                 $refused = '';
                   8706:                                             }
                   8707:                                         }
                   8708:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8709:                                         $refused = '';
                   8710:                                     }
                   8711:                                 }
                   8712:                             }
                   8713:                         }
                   8714:                     }
1.1017    raeburn  8715:                 }
                   8716:                 if ($refused) {
1.947     raeburn  8717:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8718:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8719: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8720:                     return 'refused';
                   8721:                 }
1.932     raeburn  8722:             }
1.1131    raeburn  8723:         } elsif ($role eq 'au') {
                   8724:             if ($url ne '/'.$udom.'/') {
                   8725:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8726:                          ' to assign author role for '.$uname.':'.$udom.
                   8727:                          ' in domain: '.$url.' refused (wrong domain).');
                   8728:                 return 'refused';
                   8729:             }
1.104     www      8730:         }
1.21      www      8731:         $mrole=$role;
                   8732:     }
1.620     albertel 8733:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8734:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8735:     if ($end) { $command.='_'.$end; }
1.21      www      8736:     if ($start) {
                   8737: 	if ($end) { 
1.81      www      8738:            $command.='_'.$start; 
1.21      www      8739:         } else {
1.81      www      8740:            $command.='_0_'.$start;
1.21      www      8741:         }
                   8742:     }
1.739     raeburn  8743:     my $origstart = $start;
                   8744:     my $origend = $end;
1.957     raeburn  8745:     my $delflag;
1.357     www      8746: # actually delete
                   8747:     if ($deleteflag) {
1.373     www      8748: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8749: # modify command to delete the role
1.620     albertel 8750:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8751:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8752: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8753: # set start and finish to negative values for userrolelog
                   8754:            $start=-1;
                   8755:            $end=-1;
1.957     raeburn  8756:            $delflag = 1;
1.357     www      8757:         }
                   8758:     }
                   8759: # send command
1.349     www      8760:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8761: # log new user role if status is ok
1.349     www      8762:     if ($answer eq 'ok') {
1.663     raeburn  8763: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8764:         if (($role eq 'cc') || ($role eq 'in') ||
                   8765:             ($role eq 'ep') || ($role eq 'ad') ||
                   8766:             ($role eq 'ta') || ($role eq 'st') ||
                   8767:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8768:             ($role eq 'co')) {
1.1200    raeburn  8769: # for course roles, perform group memberships changes triggered by role change.
                   8770:             unless ($role =~ /^gr/) {
                   8771:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8772:                                                  $origstart,$selfenroll,$context);
                   8773:             }
1.1184    raeburn  8774:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8775:                            $selfenroll,$context);
                   8776:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8777:                  ($role eq 'au') || ($role eq 'dc')) {
                   8778:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8779:                            $context);
                   8780:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8781:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8782:                              $context); 
                   8783:         }
1.1053    raeburn  8784:         if ($role eq 'cc') {
                   8785:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8786:         }
1.349     www      8787:     }
                   8788:     return $answer;
1.169     harris41 8789: }
                   8790: 
1.1053    raeburn  8791: sub autoupdate_coowners {
                   8792:     my ($url,$end,$start,$uname,$udom) = @_;
                   8793:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8794:     if (($cdom ne '') && ($cnum ne '')) {
                   8795:         my $now = time;
                   8796:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8797:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8798:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8799:             my $instcode = $coursehash{'internal.coursecode'};
                   8800:             if ($instcode ne '') {
1.1056    raeburn  8801:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8802:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8803:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8804:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8805:                         if ($result eq 'valid') {
                   8806:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8807:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8808:                                     push(@newcoowners,$coowner);
                   8809:                                 }
                   8810:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8811:                                     push(@newcoowners,$uname.':'.$udom);
                   8812:                                 }
                   8813:                                 @newcoowners = sort(@newcoowners);
                   8814:                             } else {
                   8815:                                 push(@newcoowners,$uname.':'.$udom);
                   8816:                             }
                   8817:                         } else {
                   8818:                             if ($coursehash{'internal.co-owners'}) {
                   8819:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8820:                                     unless ($coowner eq $uname.':'.$udom) {
                   8821:                                         push(@newcoowners,$coowner);
                   8822:                                     }
                   8823:                                 }
                   8824:                                 unless (@newcoowners > 0) {
                   8825:                                     $delcoowners = 1;
                   8826:                                     $coowners = '';
                   8827:                                 }
                   8828:                             }
                   8829:                         }
                   8830:                         if (@newcoowners || $delcoowners) {
                   8831:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8832:                                             $delcoowners,@newcoowners);
                   8833:                         }
                   8834:                     }
                   8835:                 }
                   8836:             }
                   8837:         }
                   8838:     }
                   8839: }
                   8840: 
                   8841: sub store_coowners {
                   8842:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8843:     my $cid = $cdom.'_'.$cnum;
                   8844:     my ($coowners,$delresult,$putresult);
                   8845:     if (@newcoowners) {
                   8846:         $coowners = join(',',@newcoowners);
                   8847:         my %coownershash = (
                   8848:                             'internal.co-owners' => $coowners,
                   8849:                            );
                   8850:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8851:         if ($putresult eq 'ok') {
                   8852:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8853:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8854:             }
                   8855:         }
                   8856:     }
                   8857:     if ($delcoowners) {
                   8858:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8859:         if ($delresult eq 'ok') {
                   8860:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8861:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8862:             }
                   8863:         }
                   8864:     }
                   8865:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8866:         my %crsinfo =
                   8867:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8868:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8869:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8870:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8871:         }
                   8872:     }
                   8873: }
                   8874: 
1.169     harris41 8875: # -------------------------------------------------- Modify user authentication
1.197     www      8876: # Overrides without validation
                   8877: 
1.169     harris41 8878: sub modifyuserauth {
                   8879:     my ($udom,$uname,$umode,$upass)=@_;
                   8880:     my $uhome=&homeserver($uname,$udom);
1.197     www      8881:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8882:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8883:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8884:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8885:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8886: 		     &escape($upass),$uhome);
1.620     albertel 8887:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8888:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8889:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8890:     &log($udom,,$uname,$uhome,
1.620     albertel 8891:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8892:                                      $env{'user.name'}.', '.$umode.
1.197     www      8893:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8894:     unless ($reply eq 'ok') {
1.197     www      8895:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8896: 	return 'error: '.$reply;
                   8897:     }   
1.170     harris41 8898:     return 'ok';
1.80      www      8899: }
                   8900: 
1.81      www      8901: # --------------------------------------------------------------- Modify a user
1.80      www      8902: 
1.81      www      8903: sub modifyuser {
1.206     matthew  8904:     my ($udom,    $uname, $uid,
                   8905:         $umode,   $upass, $first,
                   8906:         $middle,  $last,  $gene,
1.1058    raeburn  8907:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8908:     $udom= &LONCAPA::clean_domain($udom);
                   8909:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8910:     my $showcandelete = 'none';
                   8911:     if (ref($candelete) eq 'ARRAY') {
                   8912:         if (@{$candelete} > 0) {
                   8913:             $showcandelete = join(', ',@{$candelete});
                   8914:         }
                   8915:     }
1.81      www      8916:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8917:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8918: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8919:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8920:                                      ' desiredhome not specified'). 
1.620     albertel 8921:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8922:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8923:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8924:     my $newuser;
                   8925:     if ($uhome eq 'no_host') {
                   8926:         $newuser = 1;
                   8927:     }
1.80      www      8928: # ----------------------------------------------------------------- Create User
1.406     albertel 8929:     if (($uhome eq 'no_host') && 
                   8930: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8931:         my $unhome='';
1.844     albertel 8932:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8933:             $unhome = $desiredhome;
1.620     albertel 8934: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8935: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8936:         } else { # load balancing routine for determining $unhome
1.81      www      8937:             my $loadm=10000000;
1.841     albertel 8938: 	    my %servers = &get_servers($udom,'library');
                   8939: 	    foreach my $tryserver (keys(%servers)) {
                   8940: 		my $answer=reply('load',$tryserver);
                   8941: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8942: 		    $loadm=$answer;
                   8943: 		    $unhome=$tryserver;
                   8944: 		}
1.80      www      8945: 	    }
                   8946:         }
                   8947:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8948: 	    return 'error: unable to find a home server for '.$uname.
                   8949:                    ' in domain '.$udom;
1.80      www      8950:         }
                   8951:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8952:                          &escape($upass),$unhome);
                   8953: 	unless ($reply eq 'ok') {
                   8954:             return 'error: '.$reply;
                   8955:         }   
1.230     stredwic 8956:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8957:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8958: 	    return 'error: unable verify users home machine.';
1.80      www      8959:         }
1.209     matthew  8960:     }   # End of creation of new user
1.80      www      8961: # ---------------------------------------------------------------------- Add ID
                   8962:     if ($uid) {
                   8963:        $uid=~tr/A-Z/a-z/;
                   8964:        my %uidhash=&idrget($udom,$uname);
1.196     www      8965:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8966:          && (!$forceid)) {
1.80      www      8967: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8968: 	      return 'error: user id "'.$uid.'" does not match '.
                   8969:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8970:           }
                   8971:        } else {
1.1300    raeburn  8972: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      8973:        }
                   8974:     }
                   8975: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8976:     my @tmp=&get('environment',
1.899     raeburn  8977: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8978:                     'permanentemail','inststatus'],
1.134     albertel 8979: 		   $udom,$uname);
1.1075    raeburn  8980:     my (%names,%oldnames);
1.313     matthew  8981:     if ($tmp[0] =~ m/^error:.*/) { 
                   8982:         %names=(); 
                   8983:     } else {
                   8984:         %names = @tmp;
1.1075    raeburn  8985:         %oldnames = %names;
1.313     matthew  8986:     }
1.388     www      8987: #
1.1058    raeburn  8988: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8989: # of users did not contain them), do not overwrite existing values
                   8990: # unless field is in $candelete array ref.  
                   8991: #
                   8992: 
                   8993:     my @fields = ('firstname','middlename','lastname','generation',
                   8994:                   'permanentemail','id');
                   8995:     my %newvalues;
                   8996:     if (ref($candelete) eq 'ARRAY') {
                   8997:         foreach my $field (@fields) {
                   8998:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8999:                 if ($field eq 'firstname') {
                   9000:                     $names{$field} = $first;
                   9001:                 } elsif ($field eq 'middlename') {
                   9002:                     $names{$field} = $middle;
                   9003:                 } elsif ($field eq 'lastname') {
                   9004:                     $names{$field} = $last;
                   9005:                 } elsif ($field eq 'generation') { 
                   9006:                     $names{$field} = $gene;
                   9007:                 } elsif ($field eq 'permanentemail') {
                   9008:                     $names{$field} = $email;
                   9009:                 } elsif ($field eq 'id') {
                   9010:                     $names{$field}  = $uid;
                   9011:                 }
                   9012:             }
                   9013:         }
                   9014:     }
1.388     www      9015:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9016:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9017:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9018:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9019:     if ($email) {
                   9020:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9021:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9022:     }
1.899     raeburn  9023:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9024:     if (defined($inststatus)) {
                   9025:         $names{'inststatus'} = '';
                   9026:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9027:         if (ref($usertypes) eq 'HASH') {
                   9028:             my @okstatuses; 
                   9029:             foreach my $item (split(/:/,$inststatus)) {
                   9030:                 if (defined($usertypes->{$item})) {
                   9031:                     push(@okstatuses,$item);  
                   9032:                 }
                   9033:             }
                   9034:             if (@okstatuses) {
                   9035:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9036:             }
                   9037:         }
                   9038:     }
1.1075    raeburn  9039:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9040:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9041:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9042:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9043:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9044:     } else {
                   9045:         $logmsg .= ' during self creation';
                   9046:     }
1.1075    raeburn  9047:     my $changed;
                   9048:     if ($newuser) {
                   9049:         $changed = 1;
                   9050:     } else {
                   9051:         foreach my $field (@fields) {
                   9052:             if ($names{$field} ne $oldnames{$field}) {
                   9053:                 $changed = 1;
                   9054:                 last;
                   9055:             }
                   9056:         }
                   9057:     }
                   9058:     unless ($changed) {
                   9059:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9060:         &logthis($logmsg);
                   9061:         return 'ok';
                   9062:     }
                   9063:     my $reply = &put('environment', \%names, $udom,$uname);
                   9064:     if ($reply ne 'ok') { 
                   9065:         return 'error: '.$reply;
                   9066:     }
1.1087    raeburn  9067:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9068:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9069:     }
1.1075    raeburn  9070:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9071:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9072:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9073:     &logthis($logmsg);
1.134     albertel 9074:     return 'ok';
1.80      www      9075: }
                   9076: 
1.81      www      9077: # -------------------------------------------------------------- Modify student
1.80      www      9078: 
1.81      www      9079: sub modifystudent {
                   9080:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9081:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  9082:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 9083:     if (!$cid) {
1.620     albertel 9084: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9085: 	    return 'not_in_class';
                   9086: 	}
1.80      www      9087:     }
                   9088: # --------------------------------------------------------------- Make the user
1.81      www      9089:     my $reply=&modifyuser
1.209     matthew  9090: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9091:          $desiredhome,$email,$inststatus);
1.80      www      9092:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9093:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9094:     # student's environment
1.297     matthew  9095:     $uid = undef if (!$forceid);
1.455     albertel 9096:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9097:                                         $gene,$usec,$end,$start,$type,$locktype,
                   9098:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  9099:     return $reply;
                   9100: }
                   9101: 
                   9102: sub modify_student_enrollment {
1.1216    raeburn  9103:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   9104:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 9105:     my ($cdom,$cnum,$chome);
                   9106:     if (!$cid) {
1.620     albertel 9107: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9108: 	    return 'not_in_class';
                   9109: 	}
1.620     albertel 9110: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9111: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9112:     } else {
                   9113: 	($cdom,$cnum)=split(/_/,$cid);
                   9114:     }
1.620     albertel 9115:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9116:     if (!$chome) {
1.457     raeburn  9117: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9118:     }
1.455     albertel 9119:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9120:     # Make sure the user exists
1.81      www      9121:     my $uhome=&homeserver($uname,$udom);
                   9122:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9123: 	return 'error: no such user';
                   9124:     }
1.297     matthew  9125:     # Get student data if we were not given enough information
                   9126:     if (!defined($first)  || $first  eq '' || 
                   9127:         !defined($last)   || $last   eq '' || 
                   9128:         !defined($uid)    || $uid    eq '' || 
                   9129:         !defined($middle) || $middle eq '' || 
                   9130:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9131:         # They did not supply us with enough data to enroll the student, so
                   9132:         # we need to pick up more information.
1.297     matthew  9133:         my %tmp = &get('environment',
1.294     matthew  9134:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9135:                        ,$udom,$uname);
                   9136: 
1.800     albertel 9137:         #foreach my $key (keys(%tmp)) {
                   9138:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9139:         #}
1.294     matthew  9140:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9141:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9142:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9143:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9144:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9145:     }
1.556     albertel 9146:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9147:     my $user = "$uname:$udom";
                   9148:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9149:     my $reply=cput('classlist',
1.1148    raeburn  9150: 		   {$user => 
1.1216    raeburn  9151: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 9152: 		   $cdom,$cnum);
1.1148    raeburn  9153:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9154:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9155:     } else { 
1.81      www      9156: 	return 'error: '.$reply;
                   9157:     }
1.297     matthew  9158:     # Add student role to user
1.83      www      9159:     my $uurl='/'.$cid;
1.81      www      9160:     $uurl=~s/\_/\//g;
                   9161:     if ($usec) {
                   9162: 	$uurl.='/'.$usec;
                   9163:     }
1.1148    raeburn  9164:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9165:                              $selfenroll,$context);
                   9166:     if ($result ne 'ok') {
                   9167:         if ($old_entry{$user} ne '') {
                   9168:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9169:         } else {
                   9170:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9171:         }
                   9172:     }
                   9173:     return $result; 
1.21      www      9174: }
                   9175: 
1.556     albertel 9176: sub format_name {
                   9177:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9178:     my $name;
                   9179:     if ($first ne 'lastname') {
                   9180: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9181:     } else {
                   9182: 	if ($lastname=~/\S/) {
                   9183: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9184: 	    $name=~s/\s+,/,/;
                   9185: 	} else {
                   9186: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9187: 	}
                   9188:     }
                   9189:     $name=~s/^\s+//;
                   9190:     $name=~s/\s+$//;
                   9191:     $name=~s/\s+/ /g;
                   9192:     return $name;
                   9193: }
                   9194: 
1.84      www      9195: # ------------------------------------------------- Write to course preferences
                   9196: 
                   9197: sub writecoursepref {
                   9198:     my ($courseid,%prefs)=@_;
                   9199:     $courseid=~s/^\///;
                   9200:     $courseid=~s/\_/\//g;
                   9201:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9202:     my $chome=homeserver($cnum,$cdomain);
                   9203:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9204: 	return 'error: no such course';
                   9205:     }
                   9206:     my $cstring='';
1.800     albertel 9207:     foreach my $pref (keys(%prefs)) {
                   9208: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9209:     }
1.84      www      9210:     $cstring=~s/\&$//;
                   9211:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9212: }
                   9213: 
                   9214: # ---------------------------------------------------------- Make/modify course
                   9215: 
                   9216: sub createcourse {
1.741     raeburn  9217:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9218:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9219:     $url=&declutter($url);
                   9220:     my $cid='';
1.1028    raeburn  9221:     if ($context eq 'requestcourses') {
                   9222:         my $can_create = 0;
                   9223:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9224:         if ($udom eq $ownerdom) {
                   9225:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9226:                                   $context)) {
                   9227:                 $can_create = 1;
                   9228:             }
                   9229:         } else {
                   9230:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9231:                                            $category);
                   9232:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9233:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9234:                 if (@curr > 0) {
                   9235:                     my @options = qw(approval validate autolimit);
                   9236:                     my $optregex = join('|',@options);
                   9237:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9238:                         $can_create = 1;
                   9239:                     }
                   9240:                 }
                   9241:             }
                   9242:         }
                   9243:         if ($can_create) {
                   9244:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9245:                 unless (&allowed('ccc',$udom)) {
                   9246:                     return 'refused'; 
                   9247:                 }
1.1017    raeburn  9248:             }
                   9249:         } else {
                   9250:             return 'refused';
                   9251:         }
1.1028    raeburn  9252:     } elsif (!&allowed('ccc',$udom)) {
                   9253:         return 'refused';
1.84      www      9254:     }
1.1011    raeburn  9255: # --------------------------------------------------------------- Get Unique ID
                   9256:     my $uname;
                   9257:     if ($cnum =~ /^$match_courseid$/) {
                   9258:         my $chome=&homeserver($cnum,$udom,'true');
                   9259:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9260:             $uname = $cnum;
                   9261:         } else {
1.1038    raeburn  9262:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9263:         }
                   9264:     } else {
1.1038    raeburn  9265:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9266:     }
                   9267:     return $uname if ($uname =~ /^error/);
                   9268: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9269:     if (!defined($course_server)) {
                   9270:         if (defined(&domain($udom,'primary'))) {
                   9271:             $course_server = &domain($udom,'primary');
                   9272:         } else {
                   9273:             $course_server = $env{'user.home'}; 
                   9274:         }
                   9275:     }
                   9276:     my %host_servers =
                   9277:         &Apache::lonnet::get_servers($udom,'library');
                   9278:     unless ($host_servers{$course_server}) {
                   9279:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9280:     }
1.84      www      9281: # ------------------------------------------------------------- Make the course
                   9282:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9283:                       $course_server);
1.84      www      9284:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9285:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9286:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9287: 	return 'error: no such course';
                   9288:     }
1.271     www      9289: # ----------------------------------------------------------------- Course made
1.516     raeburn  9290: # log existence
1.1029    raeburn  9291:     my $now = time;
1.918     raeburn  9292:     my $newcourse = {
                   9293:                     $udom.'_'.$uname => {
1.921     raeburn  9294:                                      description => $description,
                   9295:                                      inst_code   => $inst_code,
                   9296:                                      owner       => $course_owner,
                   9297:                                      type        => $crstype,
1.1029    raeburn  9298:                                      creator     => $env{'user.name'}.':'.
                   9299:                                                     $env{'user.domain'},
                   9300:                                      created     => $now,
                   9301:                                      context     => $context,
1.918     raeburn  9302:                                                 },
                   9303:                     };
1.921     raeburn  9304:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9305: # set toplevel url
1.271     www      9306:     my $topurl=$url;
                   9307:     unless ($nonstandard) {
                   9308: # ------------------------------------------ For standard courses, make top url
                   9309:         my $mapurl=&clutter($url);
1.278     www      9310:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9311:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9312: <map>
                   9313: <resource id="1" type="start"></resource>
                   9314: <resource id="2" src="$mapurl"></resource>
                   9315: <resource id="3" type="finish"></resource>
                   9316: <link index="1" from="1" to="2"></link>
                   9317: <link index="2" from="2" to="3"></link>
                   9318: </map>
                   9319: ENDINITMAP
                   9320:         $topurl=&declutter(
1.638     albertel 9321:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9322:                           );
                   9323:     }
                   9324: # ----------------------------------------------------------- Write preferences
1.84      www      9325:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9326:                      ('description'              => $description,
                   9327:                       'url'                      => $topurl,
                   9328:                       'internal.creator'         => $env{'user.name'}.':'.
                   9329:                                                     $env{'user.domain'},
                   9330:                       'internal.created'         => $now,
                   9331:                       'internal.creationcontext' => $context)
                   9332:                     );
1.84      www      9333:     return '/'.$udom.'/'.$uname;
                   9334: }
                   9335: 
1.1011    raeburn  9336: # ------------------------------------------------------------------- Create ID
                   9337: sub generate_coursenum {
1.1038    raeburn  9338:     my ($udom,$crstype) = @_;
1.1011    raeburn  9339:     my $domdesc = &domain($udom);
                   9340:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9341:     my $first;
                   9342:     if ($crstype eq 'Community') {
                   9343:         $first = '0';
                   9344:     } else {
                   9345:         $first = int(1+rand(9)); 
                   9346:     } 
                   9347:     my $uname=$first.
1.1011    raeburn  9348:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9349:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9350:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9351: # ----------------------------------------------- Make sure that does not exist
                   9352:     my $uhome=&homeserver($uname,$udom,'true');
                   9353:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9354:         if ($crstype eq 'Community') {
                   9355:             $first = '0';
                   9356:         } else {
                   9357:             $first = int(1+rand(9));
                   9358:         }
                   9359:         $uname=$first.
1.1011    raeburn  9360:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9361:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9362:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9363:         $uhome=&homeserver($uname,$udom,'true');
                   9364:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9365:             return 'error: unable to generate unique course-ID';
                   9366:         }
                   9367:     }
                   9368:     return $uname;
                   9369: }
                   9370: 
1.813     albertel 9371: sub is_course {
1.1167    droeschl 9372:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9373:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9374: 
                   9375:     return unless $cdom and $cnum;
                   9376: 
                   9377:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9378:         '.');
                   9379: 
1.1219    raeburn  9380:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9381:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9382: }
                   9383: 
1.1015    raeburn  9384: sub store_userdata {
                   9385:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9386:     my $result;
1.1016    raeburn  9387:     if ($datakey ne '') {
1.1013    raeburn  9388:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9389:             if ($udom eq '' || $uname eq '') {
                   9390:                 $udom = $env{'user.domain'};
                   9391:                 $uname = $env{'user.name'};
                   9392:             }
                   9393:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9394:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9395:                 $result = 'error: no_host';
                   9396:             } else {
                   9397:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9398:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9399: 
                   9400:                 my $namevalue='';
                   9401:                 foreach my $key (keys(%{$storehash})) {
                   9402:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9403:                 }
                   9404:                 $namevalue=~s/\&$//;
1.1224    raeburn  9405:                 unless ($namespace eq 'courserequests') {
                   9406:                     $datakey = &escape($datakey);
                   9407:                 }
1.1105    raeburn  9408:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9409:                                   $namevalue,$uhome);
1.1013    raeburn  9410:             }
                   9411:         } else {
                   9412:             $result = 'error: data to store was not a hash reference'; 
                   9413:         }
                   9414:     } else {
                   9415:         $result= 'error: invalid requestkey'; 
                   9416:     }
                   9417:     return $result;
                   9418: }
                   9419: 
1.21      www      9420: # ---------------------------------------------------------- Assign Custom Role
                   9421: 
                   9422: sub assigncustomrole {
1.957     raeburn  9423:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9424:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9425:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9426: }
                   9427: 
                   9428: # ----------------------------------------------------------------- Revoke Role
                   9429: 
                   9430: sub revokerole {
1.957     raeburn  9431:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9432:     my $now=time;
1.965     raeburn  9433:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9434: }
                   9435: 
                   9436: # ---------------------------------------------------------- Revoke Custom Role
                   9437: 
                   9438: sub revokecustomrole {
1.957     raeburn  9439:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9440:     my $now=time;
1.357     www      9441:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9442:            $deleteflag,$selfenroll,$context);
1.17      www      9443: }
                   9444: 
1.533     banghart 9445: # ------------------------------------------------------------ Disk usage
1.535     albertel 9446: sub diskusage {
1.955     raeburn  9447:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9448:     $directorypath =~ s/\/$//;
                   9449:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9450:                        .&escape($getpropath).':'.&escape($uname).':'
                   9451:                        .&escape($udom),homeserver($uname,$udom));
                   9452:     if ($listing eq 'unknown_cmd') {
                   9453:         if ($getpropath) {
                   9454:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9455:         }
                   9456:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9457:     }
1.514     albertel 9458:     return $listing;
1.512     banghart 9459: }
                   9460: 
1.566     banghart 9461: sub is_locked {
1.1096    raeburn  9462:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9463:     my @check;
                   9464:     my $is_locked;
1.1093    raeburn  9465:     push (@check,$file_name);
1.613     albertel 9466:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9467: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9468:     my ($tmp)=keys(%locked);
                   9469:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9470:     
1.566     banghart 9471:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9472:         $is_locked = 'false';
                   9473:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9474:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9475:                $is_locked = 'true';
1.1096    raeburn  9476:                if (ref($which) eq 'ARRAY') {
                   9477:                    push(@{$which},$entry);
                   9478:                } else {
                   9479:                    last;
                   9480:                }
1.745     raeburn  9481:            }
                   9482:        }
1.566     banghart 9483:     } else {
                   9484:         $is_locked = 'false';
                   9485:     }
1.1093    raeburn  9486:     return $is_locked;
1.566     banghart 9487: }
                   9488: 
1.759     albertel 9489: sub declutter_portfile {
                   9490:     my ($file) = @_;
1.833     albertel 9491:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9492:     return $file;
                   9493: }
                   9494: 
1.559     banghart 9495: # ------------------------------------------------------------- Mark as Read Only
                   9496: 
                   9497: sub mark_as_readonly {
                   9498:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9499:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9500:     my ($tmp)=keys(%current_permissions);
                   9501:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9502:     foreach my $file (@{$files}) {
1.759     albertel 9503: 	$file = &declutter_portfile($file);
1.561     banghart 9504:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9505:     }
1.613     albertel 9506:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9507:     return;
                   9508: }
                   9509: 
1.572     banghart 9510: # ------------------------------------------------------------Save Selected Files
                   9511: 
                   9512: sub save_selected_files {
                   9513:     my ($user, $path, @files) = @_;
                   9514:     my $filename = $user."savedfiles";
1.573     banghart 9515:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9516:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9517:     foreach my $file (@files) {
1.620     albertel 9518:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9519:     }
                   9520:     foreach my $file (@other_files) {
1.574     banghart 9521:         print (OUT $file."\n");
1.572     banghart 9522:     }
1.574     banghart 9523:     close (OUT);
1.572     banghart 9524:     return 'ok';
                   9525: }
                   9526: 
1.574     banghart 9527: sub clear_selected_files {
                   9528:     my ($user) = @_;
                   9529:     my $filename = $user."savedfiles";
1.1117    foxr     9530:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9531:     print (OUT undef);
                   9532:     close (OUT);
                   9533:     return ("ok");    
                   9534: }
                   9535: 
1.572     banghart 9536: sub files_in_path {
                   9537:     my ($user, $path) = @_;
                   9538:     my $filename = $user."savedfiles";
                   9539:     my %return_files;
1.1117    foxr     9540:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9541:     while (my $line_in = <IN>) {
1.574     banghart 9542:         chomp ($line_in);
                   9543:         my @paths_and_file = split (m!/!, $line_in);
                   9544:         my $file_part = pop (@paths_and_file);
                   9545:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9546:         $path_part.='/';
                   9547:         my $path_and_file = $path_part.$file_part;
                   9548:         if ($path_part eq $path) {
                   9549:             $return_files{$file_part}= 'selected';
                   9550:         }
                   9551:     }
1.574     banghart 9552:     close (IN);
                   9553:     return (\%return_files);
1.572     banghart 9554: }
                   9555: 
                   9556: # called in portfolio select mode, to show files selected NOT in current directory
                   9557: sub files_not_in_path {
                   9558:     my ($user, $path) = @_;
                   9559:     my $filename = $user."savedfiles";
                   9560:     my @return_files;
                   9561:     my $path_part;
1.1117    foxr     9562:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9563:     while (my $line = <IN>) {
1.572     banghart 9564:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9565:         my @paths_and_file = split(m|/|, $line);
                   9566:         my $file_part = pop(@paths_and_file);
                   9567:         chomp($file_part);
                   9568:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9569:         $path_part .= '/';
                   9570:         my $path_and_file = $path_part.$file_part;
                   9571:         if ($path_part ne $path) {
1.800     albertel 9572:             push(@return_files, ($path_and_file));
1.572     banghart 9573:         }
                   9574:     }
1.800     albertel 9575:     close(OUT);
1.574     banghart 9576:     return (@return_files);
1.572     banghart 9577: }
                   9578: 
1.1273    raeburn  9579: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9580:  
                   9581: sub portfiles_versioning {
                   9582:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9583:     my $portfolio_root = '/userfiles/portfolio';
                   9584:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9585:     foreach my $file (@{$portfiles}) {
                   9586:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9587:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9588:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9589:         my $getpropath = 1;
                   9590:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9591:                                              $stu_name,$getpropath);
                   9592:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9593:         my $new_answer = 
                   9594:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9595:         if ($new_answer ne 'problem getting file') {
                   9596:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9597:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9598:                               [$symb,$env{'request.course.id'},'graded']);
                   9599:         }
                   9600:     }
                   9601: }
                   9602: 
                   9603: sub get_next_version {
                   9604:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9605:     my $version;
                   9606:     if (ref($dir_list) eq 'ARRAY') {
                   9607:         foreach my $row (@{$dir_list}) {
                   9608:             my ($file) = split(/\&/,$row,2);
                   9609:             my ($file_name,$file_version,$file_ext) =
                   9610:                 &file_name_version_ext($file);
                   9611:             if (($file_name eq $answer_name) &&
                   9612:                 ($file_ext eq $answer_ext)) {
                   9613:                      # gets here if filename and extension match,
                   9614:                      # regardless of version
                   9615:                 if ($file_version ne '') {
                   9616:                     # a versioned file is found  so save it for later
                   9617:                     if ($file_version > $version) {
                   9618:                         $version = $file_version;
                   9619:                     }
                   9620:                 }
                   9621:             }
                   9622:         }
                   9623:     }
                   9624:     $version ++;
                   9625:     return($version);
                   9626: }
                   9627: 
                   9628: sub version_selected_portfile {
                   9629:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9630:     my ($answer_name,$answer_ver,$answer_ext) =
                   9631:         &file_name_version_ext($file_name);
                   9632:     my $new_answer;
                   9633:     $env{'form.copy'} =
                   9634:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9635:     if($env{'form.copy'} eq '-1') {
                   9636:         $new_answer = 'problem getting file';
                   9637:     } else {
                   9638:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9639:         my $copy_result = 
                   9640:             &finishuserfileupload($stu_name,$domain,'copy',
                   9641:                                   '/portfolio'.$directory.$new_answer);
                   9642:     }
                   9643:     undef($env{'form.copy'});
                   9644:     return ($new_answer);
                   9645: }
                   9646: 
                   9647: sub file_name_version_ext {
                   9648:     my ($file)=@_;
                   9649:     my @file_parts = split(/\./, $file);
                   9650:     my ($name,$version,$ext);
                   9651:     if (@file_parts > 1) {
                   9652:         $ext=pop(@file_parts);
                   9653:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9654:             $version=pop(@file_parts);
                   9655:         }
                   9656:         $name=join('.',@file_parts);
                   9657:     } else {
                   9658:         $name=join('.',@file_parts);
                   9659:     }
                   9660:     return($name,$version,$ext);
                   9661: }
                   9662: 
1.745     raeburn  9663: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9664: 
1.745     raeburn  9665: sub get_portfile_permissions {
                   9666:     my ($domain,$user) = @_;
1.613     albertel 9667:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9668:     my ($tmp)=keys(%current_permissions);
                   9669:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9670:     return \%current_permissions;
                   9671: }
                   9672: 
                   9673: #---------------------------------------------Get portfolio file access controls
                   9674: 
1.749     raeburn  9675: sub get_access_controls {
1.745     raeburn  9676:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9677:     my %access;
                   9678:     my $real_file = $file;
                   9679:     $file =~ s/\.meta$//;
1.745     raeburn  9680:     if (defined($file)) {
1.749     raeburn  9681:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9682:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9683:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9684:             }
                   9685:         }
1.745     raeburn  9686:     } else {
1.749     raeburn  9687:         foreach my $key (keys(%{$current_permissions})) {
                   9688:             if ($key =~ /\0accesscontrol$/) {
                   9689:                 if (defined($group)) {
                   9690:                     if ($key !~ m-^\Q$group\E/-) {
                   9691:                         next;
                   9692:                     }
                   9693:                 }
                   9694:                 my ($fullpath) = split(/\0/,$key);
                   9695:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9696:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9697:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9698:                     }
                   9699:                 }
                   9700:             }
                   9701:         }
                   9702:     }
                   9703:     return %access;
                   9704: }
                   9705: 
                   9706: sub modify_access_controls {
                   9707:     my ($file_name,$changes,$domain,$user)=@_;
                   9708:     my ($outcome,$deloutcome);
                   9709:     my %store_permissions;
                   9710:     my %new_values;
                   9711:     my %new_control;
                   9712:     my %translation;
                   9713:     my @deletions = ();
                   9714:     my $now = time;
                   9715:     if (exists($$changes{'activate'})) {
                   9716:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9717:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9718:             my $numnew = scalar(@newitems);
                   9719:             for (my $i=0; $i<$numnew; $i++) {
                   9720:                 my $newkey = $newitems[$i];
                   9721:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9722:                 if ($newkey =~ /^\d+:/) { 
                   9723:                     $newkey =~ s/^(\d+)/$newid/;
                   9724:                     $translation{$1} = $newid;
                   9725:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9726:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9727:                     $translation{$1} = $newid;
                   9728:                 }
1.749     raeburn  9729:                 $new_values{$file_name."\0".$newkey} = 
                   9730:                                           $$changes{'activate'}{$newitems[$i]};
                   9731:                 $new_control{$newkey} = $now;
                   9732:             }
                   9733:         }
                   9734:     }
                   9735:     my %todelete;
                   9736:     my %changed_items;
                   9737:     foreach my $action ('delete','update') {
                   9738:         if (exists($$changes{$action})) {
                   9739:             if (ref($$changes{$action}) eq 'HASH') {
                   9740:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9741:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9742:                     if ($action eq 'delete') { 
                   9743:                         $todelete{$itemnum} = 1;
                   9744:                     } else {
                   9745:                         $changed_items{$itemnum} = $key;
                   9746:                     }
                   9747:                 }
1.745     raeburn  9748:             }
                   9749:         }
1.749     raeburn  9750:     }
                   9751:     # get lock on access controls for file.
                   9752:     my $lockhash = {
                   9753:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9754:                                                        ':'.$env{'user.domain'},
                   9755:                    }; 
                   9756:     my $tries = 0;
                   9757:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9758:    
1.1288    damieng  9759:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9760:         $tries ++;
1.1289    damieng  9761:         sleep(0.1);
1.749     raeburn  9762:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9763:     }
                   9764:     if ($gotlock eq 'ok') {
                   9765:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9766:         my ($tmp)=keys(%curr_permissions);
                   9767:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9768:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9769:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9770:             if (ref($curr_controls) eq 'HASH') {
                   9771:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9772:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9773:                     if (defined($todelete{$itemnum})) {
                   9774:                         push(@deletions,$file_name."\0".$control_item);
                   9775:                     } else {
                   9776:                         if (defined($changed_items{$itemnum})) {
                   9777:                             $new_control{$changed_items{$itemnum}} = $now;
                   9778:                             push(@deletions,$file_name."\0".$control_item);
                   9779:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9780:                         } else {
                   9781:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9782:                         }
                   9783:                     }
1.745     raeburn  9784:                 }
                   9785:             }
                   9786:         }
1.970     raeburn  9787:         my ($group);
                   9788:         if (&is_course($domain,$user)) {
                   9789:             ($group,my $file) = split(/\//,$file_name,2);
                   9790:         }
1.749     raeburn  9791:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9792:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9793:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9794:         #  remove lock
                   9795:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9796:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9797:         my $sqlresult =
1.970     raeburn  9798:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9799:                                     $group);
1.749     raeburn  9800:     } else {
                   9801:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9802:     }
1.749     raeburn  9803:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9804: }
                   9805: 
1.827     raeburn  9806: sub make_public_indefinitely {
1.1271    raeburn  9807:     my (@requrl) = @_;
                   9808:     return &automated_portfile_access('public',\@requrl);
                   9809: }
                   9810: 
                   9811: sub automated_portfile_access {
                   9812:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9813:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9814:         return 'invalid';
                   9815:     }
1.1271    raeburn  9816:     my %urls;
                   9817:     if (ref($addsref) eq 'ARRAY') {
                   9818:         foreach my $requrl (@{$addsref}) {
                   9819:             if (&is_portfolio_url($requrl)) {
                   9820:                 unless (exists($urls{$requrl})) {
                   9821:                     $urls{$requrl} = 'add';
                   9822:                 }
                   9823:             }
                   9824:         }
                   9825:     }
                   9826:     if (ref($delsref) eq 'ARRAY') {
                   9827:         foreach my $requrl (@{$delsref}) { 
                   9828:             if (&is_portfolio_url($requrl)) {
                   9829:                 unless (exists($urls{$requrl})) {
                   9830:                     $urls{$requrl} = 'delete'; 
                   9831:                 }
                   9832:             }
                   9833:         }
                   9834:     }
                   9835:     unless (keys(%urls)) {
                   9836:         return 'invalid';
                   9837:     }
                   9838:     my $ip;
                   9839:     if ($accesstype eq 'ip') {
                   9840:         if (ref($info) eq 'HASH') {
                   9841:             if ($info->{'ip'} ne '') {
                   9842:                 $ip = $info->{'ip'};
                   9843:             }
                   9844:         }
                   9845:         if ($ip eq '') {
                   9846:             return 'invalid';
                   9847:         }
                   9848:     }
                   9849:     my $errors;
1.827     raeburn  9850:     my $now = time;
1.1271    raeburn  9851:     my %current_perms;
                   9852:     foreach my $requrl (sort(keys(%urls))) {
                   9853:         my $action;
                   9854:         if ($urls{$requrl} eq 'add') {
                   9855:             $action = 'activate';
                   9856:         } else {
                   9857:             $action = 'none';
                   9858:         }
                   9859:         my $aclnum = 0;
1.827     raeburn  9860:         my (undef,$udom,$unum,$file_name,$group) =
                   9861:             &parse_portfolio_url($requrl);
1.1271    raeburn  9862:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9863:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9864:         }
                   9865:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9866:                                                    $group,$file_name);
                   9867:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9868:             my ($num,$scope,$end,$start) = 
                   9869:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9870:             if ($scope eq $accesstype) {
                   9871:                 if (($start <= $now) && ($end == 0)) {
                   9872:                     if ($accesstype eq 'ip') {
                   9873:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9874:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9875:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9876:                                     if ($urls{$requrl} eq 'add') {
                   9877:                                         $action = 'none';
                   9878:                                         last;
                   9879:                                     } else {
                   9880:                                         $action = 'delete';
                   9881:                                         $aclnum = $num;
                   9882:                                         last;
                   9883:                                     }
                   9884:                                 }
                   9885:                             }
                   9886:                         }
                   9887:                     } elsif ($accesstype eq 'public') {
                   9888:                         if ($urls{$requrl} eq 'add') {
                   9889:                             $action = 'none';
                   9890:                             last;
                   9891:                         } else {
                   9892:                             $action = 'delete';
                   9893:                             $aclnum = $num;
                   9894:                             last;
                   9895:                         }
                   9896:                     }
                   9897:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9898:                     $action = 'update';
                   9899:                     $aclnum = $num;
1.1271    raeburn  9900:                     last;
1.827     raeburn  9901:                 }
                   9902:             }
                   9903:         }
                   9904:         if ($action eq 'none') {
1.1271    raeburn  9905:             next;
1.827     raeburn  9906:         } else {
                   9907:             my %changes;
                   9908:             my $newend = 0;
                   9909:             my $newstart = $now;
1.1271    raeburn  9910:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9911:             $changes{$action}{$newkey} = {
1.1271    raeburn  9912:                 type => $accesstype,
1.827     raeburn  9913:                 time => {
                   9914:                     start => $newstart,
                   9915:                     end   => $newend,
                   9916:                 },
                   9917:             };
1.1271    raeburn  9918:             if ($accesstype eq 'ip') {
                   9919:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9920:             }
1.827     raeburn  9921:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9922:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9923:             unless ($outcome eq 'ok') {
                   9924:                 $errors .= $outcome.' ';
                   9925:             }
1.827     raeburn  9926:         }
1.1271    raeburn  9927:     }
                   9928:     if ($errors) {
                   9929:         $errors =~ s/\s$//;
                   9930:         return $errors;
1.827     raeburn  9931:     } else {
1.1271    raeburn  9932:         return 'ok';
1.827     raeburn  9933:     }
                   9934: }
                   9935: 
1.745     raeburn  9936: #------------------------------------------------------Get Marked as Read Only
                   9937: 
                   9938: sub get_marked_as_readonly {
                   9939:     my ($domain,$user,$what,$group) = @_;
                   9940:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9941:     my @readonly_files;
1.629     banghart 9942:     my $cmp1=$what;
                   9943:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9944:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9945:         if (defined($group)) {
                   9946:             if ($file_name !~ m-^\Q$group\E/-) {
                   9947:                 next;
                   9948:             }
                   9949:         }
1.561     banghart 9950:         if (ref($value) eq "ARRAY"){
                   9951:             foreach my $stored_what (@{$value}) {
1.629     banghart 9952:                 my $cmp2=$stored_what;
1.759     albertel 9953:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9954:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9955:                 }
1.629     banghart 9956:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9957:                     push(@readonly_files, $file_name);
1.745     raeburn  9958:                     last;
1.563     banghart 9959:                 } elsif (!defined($what)) {
                   9960:                     push(@readonly_files, $file_name);
1.745     raeburn  9961:                     last;
1.561     banghart 9962:                 }
                   9963:             }
1.745     raeburn  9964:         }
1.561     banghart 9965:     }
                   9966:     return @readonly_files;
                   9967: }
1.577     banghart 9968: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9969: 
1.577     banghart 9970: sub get_marked_as_readonly_hash {
1.745     raeburn  9971:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9972:     my %readonly_files;
1.745     raeburn  9973:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9974:         if (defined($group)) {
                   9975:             if ($file_name !~ m-^\Q$group\E/-) {
                   9976:                 next;
                   9977:             }
                   9978:         }
1.577     banghart 9979:         if (ref($value) eq "ARRAY"){
                   9980:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9981:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9982:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9983:                         if ($lock_descriptor eq 'graded') {
                   9984:                             $readonly_files{$file_name} = 'graded';
                   9985:                         } elsif ($lock_descriptor eq 'handback') {
                   9986:                             $readonly_files{$file_name} = 'handback';
                   9987:                         } else {
                   9988:                             if (!exists($readonly_files{$file_name})) {
                   9989:                                 $readonly_files{$file_name} = 'locked';
                   9990:                             }
                   9991:                         }
1.745     raeburn  9992:                     }
1.750     banghart 9993:                 } 
1.577     banghart 9994:             }
                   9995:         } 
                   9996:     }
                   9997:     return %readonly_files;
                   9998: }
1.559     banghart 9999: # ------------------------------------------------------------ Unmark as Read Only
                   10000: 
                   10001: sub unmark_as_readonly {
1.629     banghart 10002:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10003:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10004:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10005:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10006:     my $symb_crs = $what;
                   10007:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10008:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10009:     my ($tmp)=keys(%current_permissions);
                   10010:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10011:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10012:     foreach my $file (@readonly_files) {
1.759     albertel 10013: 	my $clean_file = &declutter_portfile($file);
                   10014: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10015: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10016:         my @new_locks;
                   10017:         my @del_keys;
                   10018:         if (ref($current_locks) eq "ARRAY"){
                   10019:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10020:                 my $compare=$locker;
1.749     raeburn  10021:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10022:                     $compare=join('',@{$locker});
1.746     raeburn  10023:                     if ($compare ne $symb_crs) {
                   10024:                         push(@new_locks, $locker);
                   10025:                     }
1.563     banghart 10026:                 }
                   10027:             }
1.650     albertel 10028:             if (scalar(@new_locks) > 0) {
1.563     banghart 10029:                 $current_permissions{$file} = \@new_locks;
                   10030:             } else {
                   10031:                 push(@del_keys, $file);
1.613     albertel 10032:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10033:                 delete($current_permissions{$file});
1.563     banghart 10034:             }
                   10035:         }
1.561     banghart 10036:     }
1.613     albertel 10037:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10038:     return;
                   10039: }
1.512     banghart 10040: 
1.17      www      10041: # ------------------------------------------------------------ Directory lister
                   10042: 
                   10043: sub dirlist {
1.955     raeburn  10044:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10045:     $uri=~s/^\///;
                   10046:     $uri=~s/\/$//;
1.253     stredwic 10047:     my ($udom, $uname);
1.955     raeburn  10048:     if ($getuserdir) {
1.253     stredwic 10049:         $udom = $userdomain;
                   10050:         $uname = $username;
1.955     raeburn  10051:     } else {
                   10052:         (undef,$udom,$uname)=split(/\//,$uri);
                   10053:         if(defined($userdomain)) {
                   10054:             $udom = $userdomain;
                   10055:         }
                   10056:         if(defined($username)) {
                   10057:             $uname = $username;
                   10058:         }
1.253     stredwic 10059:     }
1.955     raeburn  10060:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10061: 
1.955     raeburn  10062:     $dirRoot = $perlvar{'lonDocRoot'};
                   10063:     if (defined($getpropath)) {
                   10064:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10065:         $dirRoot =~ s/\/$//;
1.955     raeburn  10066:     } elsif (defined($getuserdir)) {
                   10067:         my $subdir=$uname.'__';
                   10068:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10069:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10070:                    ."/$udom/$subdir/$uname";
                   10071:     } elsif (defined($alternateRoot)) {
                   10072:         $dirRoot = $alternateRoot;
1.751     banghart 10073:     }
1.253     stredwic 10074: 
                   10075:     if($udom) {
                   10076:         if($uname) {
1.1135    raeburn  10077:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10078:             if ($uhome eq 'no_host') {
                   10079:                 return ([],'no_host');
                   10080:             }
1.955     raeburn  10081:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10082:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10083:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10084:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10085:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10086:             } else {
                   10087:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10088:             }
1.605     matthew  10089:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10090:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10091:                 @listing_results = split(/:/,$listing);
                   10092:             } else {
                   10093:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10094:             }
1.1135    raeburn  10095:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10096:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10097:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10098:                 return ([],$listing);
                   10099:             } else {
                   10100:                 return (\@listing_results);
1.1135    raeburn  10101:             }
1.955     raeburn  10102:         } elsif(!$alternateRoot) {
1.1136    raeburn  10103:             my (%allusers,%listerror);
1.841     albertel 10104: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10105:  	    foreach my $tryserver (keys(%servers)) {
                   10106:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10107:                                   &escape($udom),$tryserver);
                   10108:                 if ($listing eq 'unknown_cmd') {
                   10109: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10110: 				      $udom, $tryserver);
                   10111:                 } else {
                   10112:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10113:                 }
1.841     albertel 10114: 		if ($listing eq 'unknown_cmd') {
                   10115: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10116: 				      $udom, $tryserver);
                   10117: 		    @listing_results = split(/:/,$listing);
                   10118: 		} else {
                   10119: 		    @listing_results =
                   10120: 			map { &unescape($_); } split(/:/,$listing);
                   10121: 		}
1.1136    raeburn  10122:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10123:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10124:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10125:                     $listerror{$tryserver} = $listing;
                   10126:                 } else {
1.841     albertel 10127: 		    foreach my $line (@listing_results) {
                   10128: 			my ($entry) = split(/&/,$line,2);
                   10129: 			$allusers{$entry} = 1;
                   10130: 		    }
                   10131: 		}
1.253     stredwic 10132:             }
1.1136    raeburn  10133:             my @alluserslist=();
1.800     albertel 10134:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10135:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10136:             }
1.1136    raeburn  10137:             return (\@alluserslist);
1.253     stredwic 10138:         } else {
1.1136    raeburn  10139:             return ([],'missing username');
1.253     stredwic 10140:         }
1.955     raeburn  10141:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10142:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10143:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10144:         return (\@all_domains);
1.955     raeburn  10145:     } else {
1.1136    raeburn  10146:         return ([],'missing domain');
1.275     stredwic 10147:     }
                   10148: }
                   10149: 
                   10150: # --------------------------------------------- GetFileTimestamp
                   10151: # This function utilizes dirlist and returns the date stamp for
                   10152: # when it was last modified.  It will also return an error of -1
                   10153: # if an error occurs
                   10154: 
                   10155: sub GetFileTimestamp {
1.955     raeburn  10156:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10157:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10158:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10159:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10160:                                     undef,$getuserdir);
                   10161:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10162:         return -1;
                   10163:     }
                   10164:     if (ref($fileref) eq 'ARRAY') {
                   10165:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10166:         # @stats contains first the filename, then the stat output
                   10167:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10168:     } else {
                   10169:         return -1;
1.253     stredwic 10170:     }
1.26      www      10171: }
                   10172: 
1.712     albertel 10173: sub stat_file {
                   10174:     my ($uri) = @_;
1.787     albertel 10175:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10176: 
1.955     raeburn  10177:     my ($udom,$uname,$file);
1.712     albertel 10178:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10179: 	($udom,$uname,$file) =
1.811     albertel 10180: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10181: 	$file = 'userfiles/'.$file;
                   10182:     }
                   10183:     if ($uri =~ m-^/res/-) {
                   10184: 	($udom,$uname) = 
1.807     albertel 10185: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10186: 	$file = $uri;
                   10187:     }
                   10188: 
                   10189:     if (!$udom || !$uname || !$file) {
                   10190: 	# unable to handle the uri
                   10191: 	return ();
                   10192:     }
1.956     raeburn  10193:     my $getpropath;
                   10194:     if ($file =~ /^userfiles\//) {
                   10195:         $getpropath = 1;
                   10196:     }
1.1136    raeburn  10197:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10198:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10199:         return ();
                   10200:     } else {
                   10201:         if (ref($listref) eq 'ARRAY') {
                   10202:             my @stats = split('&',$listref->[0]);
                   10203: 	    shift(@stats); #filename is first
                   10204: 	    return @stats;
                   10205:         }
1.712     albertel 10206:     }
                   10207:     return ();
                   10208: }
                   10209: 
1.26      www      10210: # -------------------------------------------------------- Value of a Condition
                   10211: 
1.713     albertel 10212: # gets the value of a specific preevaluated condition
                   10213: #    stored in the string  $env{user.state.<cid>}
                   10214: # or looks up a condition reference in the bighash and if if hasn't
                   10215: # already been evaluated recurses into docondval to get the value of
                   10216: # the condition, then memoizing it to 
                   10217: #   $env{user.state.<cid>.<condition>}
1.40      www      10218: sub directcondval {
                   10219:     my $number=shift;
1.620     albertel 10220:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10221: 	&Apache::lonuserstate::evalstate();
                   10222:     }
1.713     albertel 10223:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10224: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10225:     } elsif ($number =~ /^_/) {
                   10226: 	my $sub_condition;
                   10227: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10228: 		&GDBM_READER(),0640)) {
                   10229: 	    $sub_condition=$bighash{'conditions'.$number};
                   10230: 	    untie(%bighash);
                   10231: 	}
                   10232: 	my $value = &docondval($sub_condition);
1.949     raeburn  10233: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10234: 	return $value;
                   10235:     }
1.620     albertel 10236:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10237:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10238:     } else {
                   10239:        return 2;
                   10240:     }
                   10241: }
                   10242: 
1.713     albertel 10243: # get the collection of conditions for this resource
1.26      www      10244: sub condval {
                   10245:     my $condidx=shift;
1.54      www      10246:     my $allpathcond='';
1.713     albertel 10247:     foreach my $cond (split(/\|/,$condidx)) {
                   10248: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10249: 	    $allpathcond.=
                   10250: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10251: 	}
1.191     harris41 10252:     }
1.54      www      10253:     $allpathcond=~s/\|$//;
1.713     albertel 10254:     return &docondval($allpathcond);
                   10255: }
                   10256: 
                   10257: #evaluates an expression of conditions
                   10258: sub docondval {
                   10259:     my ($allpathcond) = @_;
                   10260:     my $result=0;
                   10261:     if ($env{'request.course.id'}
                   10262: 	&& defined($allpathcond)) {
                   10263: 	my $operand='|';
                   10264: 	my @stack;
                   10265: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10266: 	    if ($chunk eq '(') {
                   10267: 		push @stack,($operand,$result);
                   10268: 	    } elsif ($chunk eq ')') {
                   10269: 		my $before=pop @stack;
                   10270: 		if (pop @stack eq '&') {
                   10271: 		    $result=$result>$before?$before:$result;
                   10272: 		} else {
                   10273: 		    $result=$result>$before?$result:$before;
                   10274: 		}
                   10275: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10276: 		$operand=$chunk;
                   10277: 	    } else {
                   10278: 		my $new=directcondval($chunk);
                   10279: 		if ($operand eq '&') {
                   10280: 		    $result=$result>$new?$new:$result;
                   10281: 		} else {
                   10282: 		    $result=$result>$new?$result:$new;
                   10283: 		}
                   10284: 	    }
                   10285: 	}
1.26      www      10286:     }
                   10287:     return $result;
1.421     albertel 10288: }
                   10289: 
                   10290: # ---------------------------------------------------- Devalidate courseresdata
                   10291: 
                   10292: sub devalidatecourseresdata {
                   10293:     my ($coursenum,$coursedomain)=@_;
                   10294:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10295:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10296: }
                   10297: 
1.763     www      10298: 
1.200     www      10299: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10300: #
                   10301: #  Parameters:
                   10302: #      $coursenum    - Number of the course.
                   10303: #      $coursedomain - Domain at which the course was created.
                   10304: #  Returns:
                   10305: #     A hash of the course parameters along (I think) with timestamps
                   10306: #     and version info.
1.877     foxr     10307: 
1.624     albertel 10308: sub get_courseresdata {
                   10309:     my ($coursenum,$coursedomain)=@_;
1.200     www      10310:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10311:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10312:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10313:     my %dumpreply;
1.417     albertel 10314:     unless (defined($cached)) {
1.624     albertel 10315: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10316: 	$result=\%dumpreply;
1.251     albertel 10317: 	my ($tmp) = keys(%dumpreply);
                   10318: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10319: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10320: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10321: 	    return $tmp;
1.416     albertel 10322: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10323: 	    $result=undef;
1.599     albertel 10324: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10325: 	}
                   10326:     }
1.624     albertel 10327:     return $result;
                   10328: }
                   10329: 
1.633     albertel 10330: sub devalidateuserresdata {
                   10331:     my ($uname,$udom)=@_;
                   10332:     my $hashid="$udom:$uname";
                   10333:     &devalidate_cache_new('userres',$hashid);
                   10334: }
                   10335: 
1.624     albertel 10336: sub get_userresdata {
                   10337:     my ($uname,$udom)=@_;
                   10338:     #most student don\'t have any data set, check if there is some data
                   10339:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10340: 
                   10341:     my $hashid="$udom:$uname";
                   10342:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10343:     if (!defined($cached)) {
                   10344: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10345: 	$result=\%resourcedata;
                   10346: 	&do_cache_new('userres',$hashid,$result,600);
                   10347:     }
                   10348:     my ($tmp)=keys(%$result);
                   10349:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10350: 	return $result;
                   10351:     }
                   10352:     #error 2 occurs when the .db doesn't exist
                   10353:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10354:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10355: 	    &logthis("<font color=\"blue\">WARNING:".
                   10356: 		     " Trying to get resource data for ".
                   10357: 		     $uname." at ".$udom.": ".
                   10358: 		     $tmp."</font>");
                   10359:         }
1.624     albertel 10360:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10361: 	#&EXT_cache_set($udom,$uname);
                   10362: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10363: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10364:     }
                   10365:     return $tmp;
                   10366: }
1.879     foxr     10367: #----------------------------------------------- resdata - return resource data
                   10368: #  Purpose:
                   10369: #    Return resource data for either users or for a course.
                   10370: #  Parameters:
                   10371: #     $name      - Course/user name.
                   10372: #     $domain    - Name of the domain the user/course is registered on.
1.1311  ! raeburn  10373: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10374: #     $mapp      - decluttered URL of enclosing map  
                   10375: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10376: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10377: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10378: #     $courseid  - CourseID (first part of param identifier).
                   10379: #     $modifier  - Middle part of param identifier.
                   10380: #     $what      - Last part of param identifier.
1.879     foxr     10381: #     @which     - Array of names of resources desired.
                   10382: #  Returns:
                   10383: #     The value of the first reasource in @which that is found in the
                   10384: #     resource hash.
                   10385: #  Exceptional Conditions:
                   10386: #     If the $type passed in is not valid (not the string 'course' or 
                   10387: #     'user', an undefined  reference is returned.
                   10388: #     If none of the resources are found, an undef is returned
1.624     albertel 10389: sub resdata {
1.1301    raeburn  10390:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10391:         $modifier,$what,@which)=@_;
1.624     albertel 10392:     my $result;
                   10393:     if ($type eq 'course') {
                   10394: 	$result=&get_courseresdata($name,$domain);
                   10395:     } elsif ($type eq 'user') {
                   10396: 	$result=&get_userresdata($name,$domain);
                   10397:     }
                   10398:     if (!ref($result)) { return $result; }    
1.251     albertel 10399:     foreach my $item (@which) {
1.1301    raeburn  10400:         if ($item->[1] eq 'course') {
                   10401:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10402:                 unless ($$recursed) {
1.1302    raeburn  10403:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10404:                     $$recursed = 1;
                   10405:                 }
                   10406:                 foreach my $item (@${recurseup}) {
                   10407:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10408:                     last if (defined($result->{$norecursechk}));
                   10409:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10410:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10411:                 }
                   10412:             }
                   10413:         }
                   10414:         if (defined($result->{$item->[0]})) {
1.927     albertel 10415: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10416: 	}
1.250     albertel 10417:     }
1.291     albertel 10418:     return undef;
1.200     www      10419: }
                   10420: 
1.1298    raeburn  10421: sub get_domain_ltitools {
                   10422:     my ($cdom) = @_;
                   10423:     my %ltitools;
                   10424:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10425:     if (defined($cached)) {
                   10426:         if (ref($result) eq 'HASH') {
                   10427:             %ltitools = %{$result};
                   10428:         }
                   10429:     } else {
                   10430:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10431:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10432:             %ltitools = %{$domconfig{'ltitools'}};
                   10433:         }
                   10434:         my $cachetime = 24*60*60;
                   10435:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10436:     }
                   10437:     return %ltitools;
                   10438: }
                   10439: 
1.1236    raeburn  10440: sub get_numsuppfiles {
                   10441:     my ($cnum,$cdom,$ignorecache)=@_;
                   10442:     my $hashid=$cnum.':'.$cdom;
                   10443:     my ($suppcount,$cached);
                   10444:     unless ($ignorecache) {
                   10445:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10446:     }
                   10447:     unless (defined($cached)) {
                   10448:         my $chome=&homeserver($cnum,$cdom);
                   10449:         unless ($chome eq 'no_host') {
                   10450:             ($suppcount,my $errors) = (0,0);
                   10451:             my $suppmap = 'supplemental.sequence';
                   10452:             ($suppcount,$errors) = 
                   10453:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10454:         }
                   10455:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10456:     }
                   10457:     return $suppcount;
                   10458: }
                   10459: 
1.379     matthew  10460: #
                   10461: # EXT resource caching routines
                   10462: #
                   10463: 
1.1302    raeburn  10464: {
                   10465: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10466: #
                   10467: # The course for which we cache
                   10468: my $cachedmapkey='';
                   10469: # The cached recursive maps for this course
                   10470: my %cachedmaps=();
                   10471: # When this was last done
                   10472: my $cachedmaptime='';
                   10473: 
1.379     matthew  10474: sub clear_EXT_cache_status {
1.383     albertel 10475:     &delenv('cache.EXT.');
1.379     matthew  10476: }
                   10477: 
                   10478: sub EXT_cache_status {
                   10479:     my ($target_domain,$target_user) = @_;
1.383     albertel 10480:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10481:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10482:         # We know already the user has no data
                   10483:         return 1;
                   10484:     } else {
                   10485:         return 0;
                   10486:     }
                   10487: }
                   10488: 
                   10489: sub EXT_cache_set {
                   10490:     my ($target_domain,$target_user) = @_;
1.383     albertel 10491:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10492:     #&appenv({$cachename => time});
1.379     matthew  10493: }
                   10494: 
1.28      www      10495: # --------------------------------------------------------- Value of a Variable
1.58      www      10496: sub EXT {
1.715     albertel 10497: 
1.1228    raeburn  10498:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10499:     unless ($varname) { return ''; }
1.218     albertel 10500:     #get real user name/domain, courseid and symb
                   10501:     my $courseid;
1.359     albertel 10502:     my $publicuser;
1.427     www      10503:     if ($symbparm) {
                   10504: 	$symbparm=&get_symb_from_alias($symbparm);
                   10505:     }
1.218     albertel 10506:     if (!($uname && $udom)) {
1.790     albertel 10507:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10508:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10509:     } else {
1.620     albertel 10510: 	$courseid=$env{'request.course.id'};
1.218     albertel 10511:     }
1.48      www      10512:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10513:     my $rest;
1.320     albertel 10514:     if (defined($therest[0])) {
1.48      www      10515:        $rest=join('.',@therest);
                   10516:     } else {
                   10517:        $rest='';
                   10518:     }
1.320     albertel 10519: 
1.57      www      10520:     my $qualifierrest=$qualifier;
                   10521:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10522:     my $spacequalifierrest=$space;
                   10523:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10524:     if ($realm eq 'user') {
1.48      www      10525: # --------------------------------------------------------------- user.resource
                   10526: 	if ($space eq 'resource') {
1.651     albertel 10527: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10528: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10529: 		 &&
1.744     albertel 10530: 		 ($symbparm eq &symbread()) ) {	
                   10531: 		# if we are in the middle of processing the resource the
                   10532: 		# get the value we are planning on committing
                   10533:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10534:                     return $Apache::lonhomework::results{$qualifierrest};
                   10535:                 } else {
                   10536:                     return $Apache::lonhomework::history{$qualifierrest};
                   10537:                 }
1.335     albertel 10538: 	    } else {
1.359     albertel 10539: 		my %restored;
1.620     albertel 10540: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10541: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10542: 		} else {
                   10543: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10544: 		}
1.335     albertel 10545: 		return $restored{$qualifierrest};
                   10546: 	    }
1.48      www      10547: # ----------------------------------------------------------------- user.access
                   10548:         } elsif ($space eq 'access') {
1.218     albertel 10549: 	    # FIXME - not supporting calls for a specific user
1.48      www      10550:             return &allowed($qualifier,$rest);
                   10551: # ------------------------------------------ user.preferences, user.environment
                   10552:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10553: 	    if (($uname eq $env{'user.name'}) &&
                   10554: 		($udom eq $env{'user.domain'})) {
                   10555: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10556: 	    } else {
1.359     albertel 10557: 		my %returnhash;
                   10558: 		if (!$publicuser) {
                   10559: 		    %returnhash=&userenvironment($udom,$uname,
                   10560: 						 $qualifierrest);
                   10561: 		}
1.218     albertel 10562: 		return $returnhash{$qualifierrest};
                   10563: 	    }
1.48      www      10564: # ----------------------------------------------------------------- user.course
                   10565:         } elsif ($space eq 'course') {
1.218     albertel 10566: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10567:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10568: # ------------------------------------------------------------------- user.role
                   10569:         } elsif ($space eq 'role') {
1.218     albertel 10570: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10571:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10572:             if ($qualifier eq 'value') {
                   10573: 		return $role;
                   10574:             } elsif ($qualifier eq 'extent') {
                   10575:                 return $where;
                   10576:             }
                   10577: # ----------------------------------------------------------------- user.domain
                   10578:         } elsif ($space eq 'domain') {
1.218     albertel 10579:             return $udom;
1.48      www      10580: # ------------------------------------------------------------------- user.name
                   10581:         } elsif ($space eq 'name') {
1.218     albertel 10582:             return $uname;
1.48      www      10583: # ---------------------------------------------------- Any other user namespace
1.29      www      10584:         } else {
1.359     albertel 10585: 	    my %reply;
                   10586: 	    if (!$publicuser) {
                   10587: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10588: 	    }
                   10589: 	    return $reply{$qualifierrest};
1.48      www      10590:         }
1.236     www      10591:     } elsif ($realm eq 'query') {
                   10592: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10593:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10594: 						[$spacequalifierrest]);
1.620     albertel 10595: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10596:    } elsif ($realm eq 'request') {
1.48      www      10597: # ------------------------------------------------------------- request.browser
                   10598:         if ($space eq 'browser') {
1.1145    bisitz   10599:             return $env{'browser.'.$qualifier};
1.57      www      10600: # ------------------------------------------------------------ request.filename
                   10601:         } else {
1.620     albertel 10602:             return $env{'request.'.$spacequalifierrest};
1.29      www      10603:         }
1.28      www      10604:     } elsif ($realm eq 'course') {
1.48      www      10605: # ---------------------------------------------------------- course.description
1.620     albertel 10606:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10607:     } elsif ($realm eq 'resource') {
1.165     www      10608: 
1.620     albertel 10609: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10610: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10611: 	}
1.693     albertel 10612: 
1.1232    raeburn  10613:         if ($qualifier eq '') {
                   10614: 	    if ($space eq 'title') {
                   10615: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10616: 	        return &gettitle($symbparm);
                   10617: 	    }
1.693     albertel 10618: 	
1.1232    raeburn  10619: 	    if ($space eq 'map') {
                   10620: 	        my ($map) = &decode_symb($symbparm);
                   10621: 	        return &symbread($map);
                   10622: 	    }
                   10623:             if ($space eq 'maptitle') {
                   10624:                 my ($map) = &decode_symb($symbparm);
                   10625:                 return &gettitle($map);
                   10626:             }
                   10627: 	    if ($space eq 'filename') {
                   10628: 	        if ($symbparm) {
                   10629: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10630: 	        }
                   10631: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10632: 	    }
1.1232    raeburn  10633: 
1.1233    raeburn  10634:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10635:                 if ($space eq 'visibleparts') {
                   10636:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10637:                     my $item;
                   10638:                     if (ref($navmap)) {
                   10639:                         my $res = $navmap->getBySymb($symbparm);
                   10640:                         my $parts = $res->parts();
                   10641:                         if (ref($parts) eq 'ARRAY') {
                   10642:                             $item = join(',',@{$parts});
                   10643:                         }
                   10644:                         undef($navmap);
1.1232    raeburn  10645:                     }
1.1233    raeburn  10646:                     return $item;
1.1232    raeburn  10647:                 }
                   10648:             }
                   10649:         }
1.693     albertel 10650: 
1.1301    raeburn  10651: 	my ($section, $group, @groups, @recurseup, $recursed);
                   10652: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  10653:         if (($courseid eq '') && ($cid)) {
                   10654:             $courseid = $cid;
                   10655:         }
                   10656: 	if (($symbparm && $courseid) && 
                   10657: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10658: 
1.218     albertel 10659: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10660: 
1.60      www      10661: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10662: 	    my $symbp=$symbparm;
1.1301    raeburn  10663: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10664: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  10665:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 10666: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 10667: 	    if (($env{'user.name'} eq $uname) &&
                   10668: 		($env{'user.domain'} eq $udom)) {
                   10669: 		$section=$env{'request.course.sec'};
1.733     raeburn  10670:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10671:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10672: 	    } else {
1.539     albertel 10673: 		if (! defined($usection)) {
1.551     albertel 10674: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10675: 		} else {
                   10676: 		    $section = $usection;
                   10677: 		}
1.733     raeburn  10678:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10679: 	    }
                   10680: 
                   10681: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10682: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  10683:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 10684: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10685: 
1.593     albertel 10686: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10687: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  10688:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 10689: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10690: 
1.60      www      10691: # ----------------------------------------------------------- first, check user
1.624     albertel 10692: 
1.1301    raeburn  10693: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   10694:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 10695: 				       ([$courselevelr,'resource'],
                   10696: 					[$courselevelm,'map'     ],
1.1301    raeburn  10697:                                         [$courseleveli,'map'     ],
1.927     albertel 10698: 					[$courselevel, 'course'  ]));
1.931     albertel 10699: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10700: 
1.594     albertel 10701: # ------------------------------------------------ second, check some of course
1.684     raeburn  10702:             my $coursereply;
1.691     raeburn  10703:             if (@groups > 0) {
                   10704:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  10705:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   10706:                                        $mapp,\$recursed,\@recurseup);
                   10707:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  10708:             }
1.96      www      10709: 
1.684     raeburn  10710: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10711: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10712: 				  'course',$mapp,\$recursed,\@recurseup,
                   10713:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 10714: 				  ([$seclevelr,   'resource'],
                   10715: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  10716:                                    [$secleveli,   'map'     ],
1.927     albertel 10717: 				   [$seclevel,    'course'  ],
                   10718: 				   [$courselevelr,'resource']));
                   10719: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10720: 
1.60      www      10721: # ------------------------------------------------------ third, check map parms
1.218     albertel 10722: 	    my %parmhash=();
                   10723: 	    my $thisparm='';
                   10724: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10725: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10726: 		    &GDBM_READER(),0640)) {
1.218     albertel 10727: 		$thisparm=$parmhash{$symbparm};
                   10728: 		untie(%parmhash);
                   10729: 	    }
1.927     albertel 10730: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10731: 	}
1.594     albertel 10732: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  10733:  
                   10734:         my $what = $spacequalifierrest;
                   10735: 	$what=~s/\./\_/;
1.282     albertel 10736: 	my $filename;
                   10737: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10738: 	if ($symbparm) {
1.409     www      10739: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10740: 	} else {
1.620     albertel 10741: 	    $filename=$env{'request.filename'};
1.282     albertel 10742: 	}
1.1301    raeburn  10743: 	my $metadata=&metadata($filename,$what);
1.927     albertel 10744: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  10745: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 10746: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10747: 
1.1301    raeburn  10748: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 10749: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10750: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10751: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10752: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  10753: 				     'course',$mapp,\$recursed,\@recurseup,
                   10754:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 10755: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  10756:                                       [$courseleveli,'map'   ],
1.927     albertel 10757: 				      [$courselevel, 'course']));
                   10758: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10759: 	}
1.145     www      10760: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10761: 	unless ($space eq '0') {
1.336     albertel 10762: 	    my @parts=split(/_/,$space);
                   10763: 	    my $id=pop(@parts);
                   10764: 	    my $part=join('_',@parts);
                   10765: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10766: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10767: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10768: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10769: 	}
1.395     albertel 10770: 	if ($recurse) { return undef; }
                   10771: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10772: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10773: # ---------------------------------------------------- Any other user namespace
                   10774:     } elsif ($realm eq 'environment') {
                   10775: # ----------------------------------------------------------------- environment
1.620     albertel 10776: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10777: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10778: 	} else {
1.770     albertel 10779: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10780: 		return '';
                   10781: 	    }
1.219     albertel 10782: 	    my %returnhash=&userenvironment($udom,$uname,
                   10783: 					    $spacequalifierrest);
                   10784: 	    return $returnhash{$spacequalifierrest};
                   10785: 	}
1.28      www      10786:     } elsif ($realm eq 'system') {
1.48      www      10787: # ----------------------------------------------------------------- system.time
                   10788: 	if ($space eq 'time') {
                   10789: 	    return time;
                   10790:         }
1.696     albertel 10791:     } elsif ($realm eq 'server') {
                   10792: # ----------------------------------------------------------------- system.time
                   10793: 	if ($space eq 'name') {
                   10794: 	    return $ENV{'SERVER_NAME'};
                   10795:         }
1.28      www      10796:     }
1.48      www      10797:     return '';
1.61      www      10798: }
                   10799: 
1.927     albertel 10800: sub get_reply {
                   10801:     my ($reply_value) = @_;
1.940     raeburn  10802:     if (ref($reply_value) eq 'ARRAY') {
                   10803:         if (wantarray) {
                   10804: 	    return @$reply_value;
                   10805:         }
                   10806:         return $reply_value->[0];
                   10807:     } else {
                   10808:         return $reply_value;
1.927     albertel 10809:     }
                   10810: }
                   10811: 
1.691     raeburn  10812: sub check_group_parms {
1.1301    raeburn  10813:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   10814:         $recursed,$recurseupref) = @_;
                   10815:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   10816:                   [$what,'course']);
                   10817:     my $coursereply;
1.691     raeburn  10818:     foreach my $group (@{$groups}) {
1.1301    raeburn  10819:         my @groupitems = ();
1.691     raeburn  10820:         foreach my $level (@levels) {
1.927     albertel 10821:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10822:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10823:         }
1.1301    raeburn  10824:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10825:                                    $env{'course.'.$courseid.'.domain'},
                   10826:                                    'course',$mapp,$recursed,$recurseupref,
                   10827:                                    $courseid,'.['.$group.'].',$what,
                   10828:                                    @groupitems);
                   10829:         last if (defined($coursereply));
1.691     raeburn  10830:     }
                   10831:     return $coursereply;
                   10832: }
                   10833: 
1.1301    raeburn  10834: sub get_map_hierarchy {
1.1302    raeburn  10835:     my ($mapname,$courseid) = @_;
                   10836:     my @recurseup = ();
1.1301    raeburn  10837:     if ($mapname) {
1.1302    raeburn  10838:         if (($cachedmapkey eq $courseid) &&
                   10839:             (abs($cachedmaptime-time)<5)) {
                   10840:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   10841:                 return @{$cachedmaps{$mapname}};
                   10842:             }
                   10843:         }
1.1301    raeburn  10844:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10845:         if (ref($navmap)) {
                   10846:             @recurseup = $navmap->recurseup_maps($mapname);
                   10847:             undef($navmap);
1.1302    raeburn  10848:             $cachedmaps{$mapname} = \@recurseup;
                   10849:             $cachedmaptime=time;
                   10850:             $cachedmapkey=$courseid;
1.1301    raeburn  10851:         }
                   10852:     }
                   10853:     return @recurseup;
                   10854: }
                   10855: 
1.1302    raeburn  10856: }
                   10857: 
1.691     raeburn  10858: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10859:     my ($courseid,@groups) = @_;
                   10860:     @groups = sort(@groups);
1.691     raeburn  10861:     return @groups;
                   10862: }
                   10863: 
1.395     albertel 10864: sub packages_tab_default {
                   10865:     my ($uri,$varname)=@_;
                   10866:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10867: 
                   10868:     my (@extension,@specifics,$do_default);
                   10869:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10870: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10871: 	if ($pack_type eq 'default') {
                   10872: 	    $do_default=1;
                   10873: 	} elsif ($pack_type eq 'extension') {
                   10874: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10875: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10876: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10877: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10878: 	}
                   10879:     }
                   10880:     # first look for a package that matches the requested part id
                   10881:     foreach my $package (@specifics) {
                   10882: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10883: 	next if ($pack_part ne $part);
                   10884: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10885: 	    return $packagetab{"$pack_type&$name&default"};
                   10886: 	}
                   10887:     }
                   10888:     # look for any possible matching non extension_ package
                   10889:     foreach my $package (@specifics) {
                   10890: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10891: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10892: 	    return $packagetab{"$pack_type&$name&default"};
                   10893: 	}
1.585     albertel 10894: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10895: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10896: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10897: 	}
                   10898:     }
1.738     albertel 10899:     # look for any posible extension_ match
                   10900:     foreach my $package (@extension) {
                   10901: 	my ($package,$pack_type)=@{$package};
                   10902: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10903: 	    return $packagetab{"$pack_type&$name&default"};
                   10904: 	}
                   10905: 	if (defined($packagetab{$package."&$name&default"})) {
                   10906: 	    return $packagetab{$package."&$name&default"};
                   10907: 	}
                   10908:     }
                   10909:     # look for a global default setting
                   10910:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10911: 	return $packagetab{"default&$name&default"};
                   10912:     }
1.395     albertel 10913:     return undef;
                   10914: }
                   10915: 
1.334     albertel 10916: sub add_prefix_and_part {
                   10917:     my ($prefix,$part)=@_;
                   10918:     my $keyroot;
                   10919:     if (defined($prefix) && $prefix !~ /^__/) {
                   10920: 	# prefix that has a part already
                   10921: 	$keyroot=$prefix;
                   10922:     } elsif (defined($prefix)) {
                   10923: 	# prefix that is missing a part
                   10924: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10925:     } else {
                   10926: 	# no prefix at all
                   10927: 	if (defined($part)) { $keyroot='_'.$part; }
                   10928:     }
                   10929:     return $keyroot;
                   10930: }
                   10931: 
1.71      www      10932: # ---------------------------------------------------------------- Get metadata
                   10933: 
1.599     albertel 10934: my %metaentry;
1.1070    www      10935: my %importedpartids;
1.71      www      10936: sub metadata {
1.176     www      10937:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10938:     $uri=&declutter($uri);
1.288     albertel 10939:     # if it is a non metadata possible uri return quickly
1.529     albertel 10940:     if (($uri eq '') || 
                   10941: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  10942: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  10943:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10944: 	return undef;
                   10945:     }
1.1261    raeburn  10946:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10947: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10948: 	return undef;
1.288     albertel 10949:     }
1.73      www      10950:     my $filename=$uri;
                   10951:     $uri=~s/\.meta$//;
1.172     www      10952: #
                   10953: # Is the metadata already cached?
1.177     www      10954: # Look at timestamp of caching
1.172     www      10955: # Everything is cached by the main uri, libraries are never directly cached
                   10956: #
1.428     albertel 10957:     if (!defined($liburi)) {
1.599     albertel 10958: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10959: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10960:     }
                   10961:     {
1.1069    www      10962: # Imported parts would go here
1.1070    www      10963:         my %importedids=();
                   10964:         my @origfileimportpartids=();
1.1069    www      10965:         my $importedparts=0;
1.172     www      10966: #
                   10967: # Is this a recursive call for a library?
                   10968: #
1.599     albertel 10969: #	if (! exists($metacache{$uri})) {
                   10970: #	    $metacache{$uri}={};
                   10971: #	}
1.924     albertel 10972: 	my $cachetime = 60*60;
1.171     www      10973:         if ($liburi) {
                   10974: 	    $liburi=&declutter($liburi);
                   10975:             $filename=$liburi;
1.401     bowersj2 10976:         } else {
1.599     albertel 10977: 	    &devalidate_cache_new('meta',$uri);
                   10978: 	    undef(%metaentry);
1.401     bowersj2 10979: 	}
1.140     www      10980:         my %metathesekeys=();
1.73      www      10981:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10982: 	my $metastring;
1.1140    www      10983: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10984: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10985: 	    $metastring = 
1.929     albertel 10986: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10987: 					  ('grade_target' => 'meta'));
                   10988: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10989: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10990:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10991: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10992: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10993: 	    $metastring=&getfile($file);
1.489     albertel 10994: 	}
1.208     albertel 10995:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10996:         my $token;
1.140     www      10997:         undef %metathesekeys;
1.71      www      10998:         while ($token=$parser->get_token) {
1.339     albertel 10999: 	    if ($token->[0] eq 'S') {
                   11000: 		if (defined($token->[2]->{'package'})) {
1.172     www      11001: #
                   11002: # This is a package - get package info
                   11003: #
1.339     albertel 11004: 		    my $package=$token->[2]->{'package'};
                   11005: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11006: 		    if (defined($token->[2]->{'id'})) { 
                   11007: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11008: 		    }
1.599     albertel 11009: 		    if ($metaentry{':packages'}) {
                   11010: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11011: 		    } else {
1.599     albertel 11012: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11013: 		    }
1.736     albertel 11014: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11015: 			my $part=$keyroot;
                   11016: 			$part=~s/^\_//;
1.736     albertel 11017: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11018: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11019: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11020: 			    # ignore package.tab specified default values
                   11021:                             # here &package_tab_default() will fetch those
                   11022: 			    if ($subp eq 'default') { next; }
1.736     albertel 11023: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11024: 			    my $unikey;
                   11025: 			    if ($pack =~ /_0$/) {
                   11026: 				$unikey='parameter_0_'.$name;
                   11027: 				$part=0;
                   11028: 			    } else {
                   11029: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11030: 			    }
1.339     albertel 11031: 			    if ($subp eq 'display') {
                   11032: 				$value.=' [Part: '.$part.']';
                   11033: 			    }
1.599     albertel 11034: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11035: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11036: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11037: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11038: 			    }
1.599     albertel 11039: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11040: 				$metaentry{':'.$unikey}=
                   11041: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11042: 			    }
1.339     albertel 11043: 			}
                   11044: 		    }
                   11045: 		} else {
1.172     www      11046: #
                   11047: # This is not a package - some other kind of start tag
1.339     albertel 11048: #
                   11049: 		    my $entry=$token->[1];
1.1068    www      11050: 		    my $unikey='';
1.175     www      11051: 
1.339     albertel 11052: 		    if ($entry eq 'import') {
1.175     www      11053: #
                   11054: # Importing a library here
1.339     albertel 11055: #
1.1067    www      11056:                         my $location=$parser->get_text('/import');
                   11057:                         my $dir=$filename;
                   11058:                         $dir=~s|[^/]*$||;
                   11059:                         $location=&filelocation($dir,$location);
1.1069    www      11060:                        
1.1068    www      11061:                         my $importmode=$token->[2]->{'importmode'};
                   11062:                         if ($importmode eq 'problem') {
1.1069    www      11063: # Import as problem/response
1.1068    www      11064:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11065:                         } elsif ($importmode eq 'part') {
                   11066: # Import as part(s)
1.1069    www      11067:                            $importedparts=1;
                   11068: # We need to get the original file and the imported file to get the part order correct
                   11069: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11070: # Load and inspect original file
1.1070    www      11071:                            if ($#origfileimportpartids<0) {
                   11072:                               undef(%importedpartids);
                   11073:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11074:                               my $origfile=&getfile($origfilelocation);
                   11075:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11076:                            }
                   11077: 
1.1069    www      11078: # Load and inspect imported file
                   11079:                            my $impfile=&getfile($location);
                   11080:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11081:                            if ($#impfilepartids>=0) {
                   11082: # This problem had parts
1.1070    www      11083:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11084:                            } else {
                   11085: # Importing by turning a single problem into a problem part
                   11086: # It gets the import-tags ID as part-ID
                   11087:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11088:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11089:                            }
1.1068    www      11090:                         } else {
                   11091: # Normal import
                   11092:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11093:                            if (defined($token->[2]->{'id'})) {
                   11094:                               $unikey.='_'.$token->[2]->{'id'};
                   11095:                            }
1.1067    www      11096:                         }
                   11097: 
1.339     albertel 11098: 			if ($depthcount<20) {
1.736     albertel 11099: 			    my $metadata = 
                   11100: 				&metadata($uri,'keys', $location,$unikey,
                   11101: 					  $depthcount+1);
                   11102: 			    foreach my $meta (split(',',$metadata)) {
                   11103: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11104: 				$metathesekeys{$meta}=1;
1.339     albertel 11105: 			    }
1.1068    www      11106: 			
                   11107:                         }
1.1067    www      11108: 		    } else {
                   11109: #
                   11110: # Not importing, some other kind of non-package, non-library start tag
                   11111: # 
                   11112:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11113:                         if (defined($token->[2]->{'id'})) {
                   11114:                             $unikey.='_'.$token->[2]->{'id'};
                   11115:                         }
1.339     albertel 11116: 			if (defined($token->[2]->{'name'})) { 
                   11117: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11118: 			}
                   11119: 			$metathesekeys{$unikey}=1;
1.736     albertel 11120: 			foreach my $param (@{$token->[3]}) {
                   11121: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11122: 				$token->[2]->{$param};
1.339     albertel 11123: 			}
                   11124: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11125: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11126: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11127: 		 # only ws inside the tag, and not in default, so use default
                   11128: 		 # as value
1.599     albertel 11129: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11130: 			} elsif ( $internaltext =~ /\S/ ) {
                   11131: 		  # something interesting inside the tag
                   11132: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11133: 			} else {
1.908     albertel 11134: 		  # no interesting values, don't set a default
1.339     albertel 11135: 			}
1.172     www      11136: # end of not-a-package not-a-library import
1.339     albertel 11137: 		    }
1.172     www      11138: # end of not-a-package start tag
1.339     albertel 11139: 		}
1.172     www      11140: # the next is the end of "start tag"
1.339     albertel 11141: 	    }
                   11142: 	}
1.483     albertel 11143: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11144: 	$extension = lc($extension);
                   11145: 	if ($extension eq 'htm') { $extension='html'; }
                   11146: 
1.737     albertel 11147: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11148: 	    #no specific packages #how's our extension
                   11149: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11150: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11151: 					 \%metathesekeys);
                   11152: 	}
1.883     albertel 11153: 
                   11154: 	if (!exists($metaentry{':packages'})
                   11155: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11156: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11157: 		#no specific packages well let's get default then
                   11158: 		if ($key!~/^default&/) { next; }
1.488     albertel 11159: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11160: 					     \%metathesekeys);
                   11161: 	    }
                   11162: 	}
1.338     www      11163: # are there custom rights to evaluate
1.599     albertel 11164: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11165: 
1.338     www      11166:     #
                   11167:     # Importing a rights file here
1.339     albertel 11168:     #
                   11169: 	    unless ($depthcount) {
1.599     albertel 11170: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11171: 		my $dir=$filename;
                   11172: 		$dir=~s|[^/]*$||;
                   11173: 		$location=&filelocation($dir,$location);
1.736     albertel 11174: 		my $rights_metadata =
                   11175: 		    &metadata($uri,'keys',$location,'_rights',
                   11176: 			      $depthcount+1);
                   11177: 		foreach my $rights (split(',',$rights_metadata)) {
                   11178: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11179: 		    $metathesekeys{$rights}=1;
1.339     albertel 11180: 		}
                   11181: 	    }
                   11182: 	}
1.737     albertel 11183: 	# uniqifiy package listing
                   11184: 	my %seen;
                   11185: 	my @uniq_packages =
                   11186: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11187: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11188: 
1.1070    www      11189:         if ($importedparts) {
                   11190: # We had imported parts and need to rebuild partorder
                   11191:            $metaentry{':partorder'}='';
                   11192:            $metathesekeys{'partorder'}=1;
                   11193:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11194:                if ($origfileimportpartids[$index] eq 'part') {
                   11195: # original part, part of the problem
                   11196:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11197:                } else {
                   11198: # we have imported parts at this position
                   11199:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11200:                }
                   11201:            }
                   11202:            $metaentry{':partorder'}=~s/^\,//;
                   11203:         }
                   11204: 
1.737     albertel 11205: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11206: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11207: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11208: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11209: # this is the end of "was not already recently cached
1.71      www      11210:     }
1.599     albertel 11211:     return $metaentry{':'.$what};
1.261     albertel 11212: }
                   11213: 
1.488     albertel 11214: sub metadata_create_package_def {
1.483     albertel 11215:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11216:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11217:     if ($subp eq 'default') { next; }
                   11218:     
1.599     albertel 11219:     if (defined($metaentry{':packages'})) {
                   11220: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11221:     } else {
1.599     albertel 11222: 	$metaentry{':packages'}=$package;
1.483     albertel 11223:     }
                   11224:     my $value=$packagetab{$key};
                   11225:     my $unikey;
                   11226:     $unikey='parameter_0_'.$name;
1.599     albertel 11227:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11228:     $$metathesekeys{$unikey}=1;
1.599     albertel 11229:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11230: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11231:     }
1.599     albertel 11232:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11233: 	$metaentry{':'.$unikey}=
                   11234: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11235:     }
                   11236: }
                   11237: 
1.261     albertel 11238: sub metadata_generate_part0 {
                   11239:     my ($metadata,$metacache,$uri) = @_;
                   11240:     my %allnames;
1.737     albertel 11241:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11242: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11243: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11244: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11245: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11246: 	    $allnames{$name}=$part;
                   11247: 	  }
                   11248: 	}
                   11249:     }
                   11250:     foreach my $name (keys(%allnames)) {
                   11251:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11252:       my $key=":parameter_0_$name";
1.261     albertel 11253:       $$metacache{"$key.part"}='0';
                   11254:       $$metacache{"$key.name"}=$name;
1.428     albertel 11255:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11256: 					   $allnames{$name}.'_'.$name.
                   11257: 					   '.type'};
1.428     albertel 11258:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11259: 			     '.display'};
1.644     www      11260:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11261:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11262:       $$metacache{"$key.display"}=$olddis;
                   11263:     }
1.71      www      11264: }
                   11265: 
1.764     albertel 11266: # ------------------------------------------------------ Devalidate title cache
                   11267: 
                   11268: sub devalidate_title_cache {
                   11269:     my ($url)=@_;
                   11270:     if (!$env{'request.course.id'}) { return; }
                   11271:     my $symb=&symbread($url);
                   11272:     if (!$symb) { return; }
                   11273:     my $key=$env{'request.course.id'}."\0".$symb;
                   11274:     &devalidate_cache_new('title',$key);
                   11275: }
                   11276: 
1.1014    droeschl 11277: # ------------------------------------------------- Get the title of a course
                   11278: 
                   11279: sub current_course_title {
                   11280:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11281: }
1.301     www      11282: # ------------------------------------------------- Get the title of a resource
                   11283: 
                   11284: sub gettitle {
                   11285:     my $urlsymb=shift;
                   11286:     my $symb=&symbread($urlsymb);
1.534     albertel 11287:     if ($symb) {
1.620     albertel 11288: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11289: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11290: 	if (defined($cached)) { 
                   11291: 	    return $result;
                   11292: 	}
1.534     albertel 11293: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11294: 	my $title='';
1.907     albertel 11295: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11296: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11297: 	} else {
                   11298: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11299: 		    &GDBM_READER(),0640)) {
                   11300: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11301: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11302: 		untie(%bighash);
                   11303: 	    }
1.534     albertel 11304: 	}
                   11305: 	$title=~s/\&colon\;/\:/gs;
                   11306: 	if ($title) {
1.1159    www      11307: # Remember both $symb and $title for dynamic metadata
                   11308:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11309:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11310: # Cache this title and then return it
1.599     albertel 11311: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11312: 	}
                   11313: 	$urlsymb=$url;
                   11314:     }
                   11315:     my $title=&metadata($urlsymb,'title');
                   11316:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11317:     return $title;
1.301     www      11318: }
1.613     albertel 11319: 
1.614     albertel 11320: sub get_slot {
                   11321:     my ($which,$cnum,$cdom)=@_;
                   11322:     if (!$cnum || !$cdom) {
1.790     albertel 11323: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11324: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11325: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11326:     }
1.703     albertel 11327:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11328:     my %slotinfo;
                   11329:     if (exists($remembered{$key})) {
                   11330: 	$slotinfo{$which} = $remembered{$key};
                   11331:     } else {
                   11332: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11333: 	&Apache::lonhomework::showhash(%slotinfo);
                   11334: 	my ($tmp)=keys(%slotinfo);
                   11335: 	if ($tmp=~/^error:/) { return (); }
                   11336: 	$remembered{$key} = $slotinfo{$which};
                   11337:     }
1.616     albertel 11338:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11339: 	return %{$slotinfo{$which}};
                   11340:     }
                   11341:     return $slotinfo{$which};
1.614     albertel 11342: }
1.1150    raeburn  11343: 
                   11344: sub get_reservable_slots {
                   11345:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11346:     my $now = time;
                   11347:     my $reservable_info;
                   11348:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11349:     if (exists($remembered{$key})) {
                   11350:         $reservable_info = $remembered{$key};
                   11351:     } else {
                   11352:         my %resv;
                   11353:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11354:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11355:         $reservable_info = \%resv;
                   11356:         $remembered{$key} = $reservable_info;
                   11357:     }
                   11358:     return $reservable_info;
                   11359: }
                   11360: 
                   11361: sub get_course_slots {
                   11362:     my ($cnum,$cdom) = @_;
                   11363:     my $hashid=$cnum.':'.$cdom;
                   11364:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11365:     if (defined($cached)) {
                   11366:         if (ref($result) eq 'HASH') {
                   11367:             return %{$result};
                   11368:         }
                   11369:     } else {
                   11370:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11371:         my ($tmp) = keys(%slots);
                   11372:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11373:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11374:             return %slots;
                   11375:         }
                   11376:     }
                   11377:     return;
                   11378: }
                   11379: 
                   11380: sub devalidate_slots_cache {
                   11381:     my ($cnum,$cdom)=@_;
                   11382:     my $hashid=$cnum.':'.$cdom;
                   11383:     &devalidate_cache_new('allslots',$hashid);
                   11384: }
                   11385: 
1.1181    raeburn  11386: sub get_coursechange {
                   11387:     my ($cdom,$cnum) = @_;
                   11388:     if ($cdom eq '' || $cnum eq '') {
                   11389:         return unless ($env{'request.course.id'});
                   11390:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11391:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11392:     }
                   11393:     my $hashid=$cdom.'_'.$cnum;
                   11394:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11395:     if ((defined($cached)) && ($change ne '')) {
                   11396:         return $change;
                   11397:     } else {
                   11398:         my %crshash;
                   11399:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11400:         if ($crshash{'internal.contentchange'} eq '') {
                   11401:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11402:             if ($change eq '') {
                   11403:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11404:                 $change = $crshash{'internal.created'};
                   11405:             }
                   11406:         } else {
                   11407:             $change = $crshash{'internal.contentchange'};
                   11408:         }
                   11409:         my $cachetime = 600;
                   11410:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11411:     }
                   11412:     return $change;
                   11413: }
                   11414: 
                   11415: sub devalidate_coursechange_cache {
                   11416:     my ($cnum,$cdom)=@_;
                   11417:     my $hashid=$cnum.':'.$cdom;
                   11418:     &devalidate_cache_new('crschange',$hashid);
                   11419: }
                   11420: 
1.31      www      11421: # ------------------------------------------------- Update symbolic store links
                   11422: 
                   11423: sub symblist {
                   11424:     my ($mapname,%newhash)=@_;
1.438     www      11425:     $mapname=&deversion(&declutter($mapname));
1.31      www      11426:     my %hash;
1.620     albertel 11427:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11428:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11429:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11430: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11431: 		next if ($url eq 'last_known'
                   11432: 			 && $env{'form.no_update_last_known'});
                   11433: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11434: 						    $newhash{$url}->[1],
                   11435: 						    $newhash{$url}->[0]);
1.191     harris41 11436:             }
1.31      www      11437:             if (untie(%hash)) {
                   11438: 		return 'ok';
                   11439:             }
                   11440:         }
                   11441:     }
                   11442:     return 'error';
1.212     www      11443: }
                   11444: 
                   11445: # --------------------------------------------------------------- Verify a symb
                   11446: 
                   11447: sub symbverify {
1.1190    raeburn  11448:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11449:     my $thisfn=$thisurl;
1.439     www      11450:     $thisfn=&declutter($thisfn);
1.215     www      11451: # direct jump to resource in page or to a sequence - will construct own symbs
                   11452:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11453: # check URL part
1.409     www      11454:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11455: 
1.431     www      11456:     unless ($url eq $thisfn) { return 0; }
1.213     www      11457: 
1.216     www      11458:     $symb=&symbclean($symb);
1.510     www      11459:     $thisurl=&deversion($thisurl);
1.439     www      11460:     $thisfn=&deversion($thisfn);
1.213     www      11461: 
                   11462:     my %bighash;
                   11463:     my $okay=0;
1.431     www      11464: 
1.620     albertel 11465:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11466:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11467:         my $noclutter;
1.1032    raeburn  11468:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11469:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11470:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11471:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11472:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11473:                 $noclutter = 1;
                   11474:             }
                   11475:         }
                   11476:         my $ids;
                   11477:         if ($noclutter) {
                   11478:             $ids=$bighash{'ids_'.$thisurl};
                   11479:         } else {
                   11480:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11481:         }
1.1102    raeburn  11482:         unless ($ids) {
                   11483:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11484:             $ids=$bighash{$idkey};
1.216     www      11485:         }
                   11486:         if ($ids) {
                   11487: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11488:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11489:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11490:             }
1.800     albertel 11491: 	    foreach my $id (split(/\,/,$ids)) {
                   11492: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11493:                if (
                   11494:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11495:    eq $symb) {
                   11496:                    if (ref($encstate)) {
                   11497:                        $$encstate = $bighash{'encrypted_'.$id};
                   11498:                    }
1.620     albertel 11499: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11500: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11501:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11502: 		       $okay=1;
1.1202    raeburn  11503:                        last;
1.582     albertel 11504: 		   }
                   11505: 	       }
1.216     www      11506: 	   }
                   11507:         }
1.213     www      11508: 	untie(%bighash);
                   11509:     }
                   11510:     return $okay;
1.31      www      11511: }
                   11512: 
1.210     www      11513: # --------------------------------------------------------------- Clean-up symb
                   11514: 
                   11515: sub symbclean {
                   11516:     my $symb=shift;
1.568     albertel 11517:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11518: # remove version from map
                   11519:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11520: 
1.210     www      11521: # remove version from URL
                   11522:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11523: 
1.507     www      11524: # remove wrapper
                   11525: 
1.510     www      11526:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11527:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11528:     return $symb;
1.409     www      11529: }
                   11530: 
                   11531: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11532: 
                   11533: sub encode_symb {
                   11534:     my ($map,$resid,$url)=@_;
                   11535:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11536: }
1.409     www      11537: 
                   11538: sub decode_symb {
1.568     albertel 11539:     my $symb=shift;
                   11540:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11541:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11542:     return (&fixversion($map),$resid,&fixversion($url));
                   11543: }
                   11544: 
                   11545: sub fixversion {
                   11546:     my $fn=shift;
1.609     banghart 11547:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11548:     my %bighash;
                   11549:     my $uri=&clutter($fn);
1.620     albertel 11550:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11551: # is this cached?
1.599     albertel 11552:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11553:     if (defined($cached)) { return $result; }
                   11554: # unfortunately not cached, or expired
1.620     albertel 11555:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11556: 	    &GDBM_READER(),0640)) {
                   11557:  	if ($bighash{'version_'.$uri}) {
                   11558:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11559:  	    unless (($version eq 'mostrecent') || 
                   11560: 		    ($version==&getversion($uri))) {
1.440     www      11561:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11562:  	    }
                   11563:  	}
                   11564:  	untie %bighash;
1.413     www      11565:     }
1.599     albertel 11566:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11567: }
                   11568: 
                   11569: sub deversion {
                   11570:     my $url=shift;
                   11571:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11572:     return $url;
1.210     www      11573: }
                   11574: 
1.31      www      11575: # ------------------------------------------------------ Return symb list entry
                   11576: 
                   11577: sub symbread {
1.1282    raeburn  11578:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11579:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11580:     if (defined($env{$cache_str})) {
                   11581:         if ($ignorecachednull) {
                   11582:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11583:         } else {
                   11584:             return $env{$cache_str};
                   11585:         }
                   11586:     }
1.242     www      11587: # no filename provided? try from environment
1.1265    raeburn  11588:     unless ($thisfn) {
1.620     albertel 11589:         if ($env{'request.symb'}) {
                   11590: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11591: 	}
1.620     albertel 11592: 	$thisfn=$env{'request.filename'};
1.44      www      11593:     }
1.569     albertel 11594:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11595: # is that filename actually a symb? Verify, clean, and return
                   11596:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11597: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11598: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11599: 	}
1.242     www      11600:     }
1.44      www      11601:     $thisfn=declutter($thisfn);
1.31      www      11602:     my %hash;
1.37      www      11603:     my %bighash;
                   11604:     my $syval='';
1.620     albertel 11605:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11606:         my $targetfn = $thisfn;
1.609     banghart 11607:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11608:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11609:         }
1.687     albertel 11610: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11611: 	    $targetfn=$1;
                   11612: 	}
1.620     albertel 11613:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11614:                       &GDBM_READER(),0640)) {
1.481     raeburn  11615: 	    $syval=$hash{$targetfn};
1.37      www      11616:             untie(%hash);
                   11617:         }
                   11618: # ---------------------------------------------------------- There was an entry
                   11619:         if ($syval) {
1.601     albertel 11620: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11621: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11622: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11623: 		    #return $env{$cache_str}='';
1.601     albertel 11624: 		#}    
                   11625: 		#$syval.=$1;
                   11626: 	    #}
1.37      www      11627:         } else {
                   11628: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11629:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11630:                             &GDBM_READER(),0640)) {
1.37      www      11631: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11632:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11633:               unless ($ids) { 
                   11634:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11635:               }
                   11636:               unless ($ids) {
                   11637: # alias?
                   11638: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11639:               }
1.37      www      11640:               if ($ids) {
                   11641: # ------------------------------------------------------------------- Has ID(s)
                   11642:                  my @possibilities=split(/\,/,$ids);
1.39      www      11643:                  if ($#possibilities==0) {
                   11644: # ----------------------------------------------- There is only one possibility
1.37      www      11645: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11646: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11647: 						    $resid,$thisfn);
1.1282    raeburn  11648:                      if (ref($possibles) eq 'HASH') {
                   11649:                          $possibles->{$syval} = 1;    
                   11650:                      }
                   11651:                      if ($checkforblock) {
                   11652:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11653:                          if (@blockers) {
                   11654:                              $syval = '';
                   11655:                              return;
                   11656:                          }
                   11657:                      }
                   11658:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11659: # ------------------------------------------ There is more than one possibility
                   11660:                      my $realpossible=0;
1.800     albertel 11661:                      foreach my $id (@possibilities) {
                   11662: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11663:                          my $canaccess;
                   11664:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11665:                              $canaccess = 1;
                   11666:                          } else { 
                   11667:                              $canaccess = &allowed('bre',$file);
                   11668:                          }
                   11669:                          if ($canaccess) {
                   11670:          		     my ($mapid,$resid)=split(/\./,$id);
                   11671:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11672:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11673: 						             $resid,$thisfn);
                   11674:                                  if (ref($possibles) eq 'HASH') {
                   11675:                                      $possibles->{$syval} = 1;
                   11676:                                  }
                   11677:                                  if ($checkforblock) {
                   11678:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11679:                                      unless (@blockers > 0) {
                   11680:                                          $syval = $poss_syval;
                   11681:                                          $realpossible++;
                   11682:                                      }
                   11683:                                  } else {
                   11684:                                      $syval = $poss_syval;
                   11685:                                      $realpossible++;
                   11686:                                  }
                   11687:                              }
1.39      www      11688: 			 }
1.191     harris41 11689:                      }
1.39      www      11690: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11691:                  } else {
                   11692:                      $syval='';
1.37      www      11693:                  }
                   11694: 	      }
1.1282    raeburn  11695:               untie(%bighash);
1.481     raeburn  11696:            }
1.31      www      11697:         }
1.62      www      11698:         if ($syval) {
1.620     albertel 11699: 	    return $env{$cache_str}=$syval;
1.62      www      11700:         }
1.31      www      11701:     }
1.949     raeburn  11702:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11703:     return $env{$cache_str}='';
1.31      www      11704: }
                   11705: 
                   11706: # ---------------------------------------------------------- Return random seed
                   11707: 
1.32      www      11708: sub numval {
                   11709:     my $txt=shift;
                   11710:     $txt=~tr/A-J/0-9/;
                   11711:     $txt=~tr/a-j/0-9/;
                   11712:     $txt=~tr/K-T/0-9/;
                   11713:     $txt=~tr/k-t/0-9/;
                   11714:     $txt=~tr/U-Z/0-5/;
                   11715:     $txt=~tr/u-z/0-5/;
                   11716:     $txt=~s/\D//g;
1.564     albertel 11717:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11718:     return int($txt);
1.368     albertel 11719: }
                   11720: 
1.484     albertel 11721: sub numval2 {
                   11722:     my $txt=shift;
                   11723:     $txt=~tr/A-J/0-9/;
                   11724:     $txt=~tr/a-j/0-9/;
                   11725:     $txt=~tr/K-T/0-9/;
                   11726:     $txt=~tr/k-t/0-9/;
                   11727:     $txt=~tr/U-Z/0-5/;
                   11728:     $txt=~tr/u-z/0-5/;
                   11729:     $txt=~s/\D//g;
                   11730:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11731:     my $total;
                   11732:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11733:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11734:     return int($total);
                   11735: }
                   11736: 
1.575     albertel 11737: sub numval3 {
                   11738:     use integer;
                   11739:     my $txt=shift;
                   11740:     $txt=~tr/A-J/0-9/;
                   11741:     $txt=~tr/a-j/0-9/;
                   11742:     $txt=~tr/K-T/0-9/;
                   11743:     $txt=~tr/k-t/0-9/;
                   11744:     $txt=~tr/U-Z/0-5/;
                   11745:     $txt=~tr/u-z/0-5/;
                   11746:     $txt=~s/\D//g;
                   11747:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11748:     my $total;
                   11749:     foreach my $val (@txts) { $total+=$val; }
                   11750:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11751:     return $total;
                   11752: }
                   11753: 
1.675     albertel 11754: sub digest {
                   11755:     my ($data)=@_;
                   11756:     my $digest=&Digest::MD5::md5($data);
                   11757:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11758:     my ($e,$f);
                   11759:     {
                   11760:         use integer;
                   11761:         $e=($a+$b);
                   11762:         $f=($c+$d);
                   11763:         if ($_64bit) {
                   11764:             $e=(($e<<32)>>32);
                   11765:             $f=(($f<<32)>>32);
                   11766:         }
                   11767:     }
                   11768:     if (wantarray) {
                   11769: 	return ($e,$f);
                   11770:     } else {
                   11771: 	my $g;
                   11772: 	{
                   11773: 	    use integer;
                   11774: 	    $g=($e+$f);
                   11775: 	    if ($_64bit) {
                   11776: 		$g=(($g<<32)>>32);
                   11777: 	    }
                   11778: 	}
                   11779: 	return $g;
                   11780:     }
                   11781: }
                   11782: 
1.368     albertel 11783: sub latest_rnd_algorithm_id {
1.675     albertel 11784:     return '64bit5';
1.366     albertel 11785: }
1.32      www      11786: 
1.503     albertel 11787: sub get_rand_alg {
                   11788:     my ($courseid)=@_;
1.790     albertel 11789:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11790:     if ($courseid) {
1.620     albertel 11791: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11792:     }
                   11793:     return &latest_rnd_algorithm_id();
                   11794: }
                   11795: 
1.562     albertel 11796: sub validCODE {
                   11797:     my ($CODE)=@_;
                   11798:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11799:     return 0;
                   11800: }
                   11801: 
1.491     albertel 11802: sub getCODE {
1.620     albertel 11803:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11804:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11805: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11806: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11807: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11808:     }
                   11809:     return undef;
                   11810: }
1.1133    foxr     11811: #
                   11812: #  Determines the random seed for a specific context:
                   11813: #
                   11814: # parameters:
                   11815: #   symb      - in course context the symb for the seed.
                   11816: #   course_id - The course id of the form domain_coursenum.
                   11817: #   domain    - Domain for the user.
                   11818: #   course    - Course for the user.
                   11819: #   cenv      - environment of the course.
                   11820: #
                   11821: # NOTE:
                   11822: #   All parameters are picked out of the environment if missing
                   11823: #   or not defined.
                   11824: #   If a symb cannot be determined the current time is used instead.
                   11825: #
                   11826: #  For a given well defined symb, courside, domain, username,
                   11827: #  and course environment, the seed is reproducible.
                   11828: #
1.31      www      11829: sub rndseed {
1.1133    foxr     11830:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11831:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11832:     if (!defined($symb)) {
1.366     albertel 11833: 	unless ($symb=$wsymb) { return time; }
                   11834:     }
1.1146    foxr     11835:     if (!defined $courseid) { 
                   11836: 	$courseid=$wcourseid; 
                   11837:     }
                   11838:     if (!defined $domain) { $domain=$wdomain; }
                   11839:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11840: 
                   11841:     my $which;
                   11842:     if (defined($cenv->{'rndseed'})) {
                   11843: 	$which = $cenv->{'rndseed'};
                   11844:     } else {
                   11845: 	$which =&get_rand_alg($courseid);
                   11846:     }
1.491     albertel 11847:     if (defined(&getCODE())) {
1.1133    foxr     11848: 
1.675     albertel 11849: 	if ($which eq '64bit5') {
                   11850: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11851: 	} elsif ($which eq '64bit4') {
1.575     albertel 11852: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11853: 	} else {
                   11854: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11855: 	}
1.675     albertel 11856:     } elsif ($which eq '64bit5') {
                   11857: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11858:     } elsif ($which eq '64bit4') {
                   11859: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11860:     } elsif ($which eq '64bit3') {
                   11861: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11862:     } elsif ($which eq '64bit2') {
                   11863: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11864:     } elsif ($which eq '64bit') {
                   11865: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11866:     }
                   11867:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11868: }
                   11869: 
                   11870: sub rndseed_32bit {
                   11871:     my ($symb,$courseid,$domain,$username)=@_;
                   11872:     {
                   11873: 	use integer;
                   11874: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11875: 	my $symbseed=numval($symb) << 22;
                   11876: 	my $namechck=unpack("%32C*",$username) << 17;
                   11877: 	my $nameseed=numval($username) << 12;
                   11878: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11879: 	my $courseseed=unpack("%32C*",$courseid);
                   11880: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11881: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11882: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11883: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11884: 	return $num;
                   11885:     }
                   11886: }
                   11887: 
                   11888: sub rndseed_64bit {
                   11889:     my ($symb,$courseid,$domain,$username)=@_;
                   11890:     {
                   11891: 	use integer;
                   11892: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11893: 	my $symbseed=numval($symb) << 10;
                   11894: 	my $namechck=unpack("%32S*",$username);
                   11895: 	
                   11896: 	my $nameseed=numval($username) << 21;
                   11897: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11898: 	my $courseseed=unpack("%32S*",$courseid);
                   11899: 	
                   11900: 	my $num1=$symbchck+$symbseed+$namechck;
                   11901: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11902: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11903: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11904: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11905: 	return "$num1,$num2";
1.155     albertel 11906:     }
1.366     albertel 11907: }
                   11908: 
1.443     albertel 11909: sub rndseed_64bit2 {
                   11910:     my ($symb,$courseid,$domain,$username)=@_;
                   11911:     {
                   11912: 	use integer;
                   11913: 	# strings need to be an even # of cahracters long, it it is odd the
                   11914:         # last characters gets thrown away
                   11915: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11916: 	my $symbseed=numval($symb) << 10;
                   11917: 	my $namechck=unpack("%32S*",$username.' ');
                   11918: 	
                   11919: 	my $nameseed=numval($username) << 21;
1.501     albertel 11920: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11921: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11922: 	
                   11923: 	my $num1=$symbchck+$symbseed+$namechck;
                   11924: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11925: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11926: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11927: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11928: 	return "$num1,$num2";
                   11929:     }
                   11930: }
                   11931: 
                   11932: sub rndseed_64bit3 {
                   11933:     my ($symb,$courseid,$domain,$username)=@_;
                   11934:     {
                   11935: 	use integer;
                   11936: 	# strings need to be an even # of cahracters long, it it is odd the
                   11937:         # last characters gets thrown away
                   11938: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11939: 	my $symbseed=numval2($symb) << 10;
                   11940: 	my $namechck=unpack("%32S*",$username.' ');
                   11941: 	
                   11942: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11943: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11944: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11945: 	
                   11946: 	my $num1=$symbchck+$symbseed+$namechck;
                   11947: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11948: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11949: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11950: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11951: 	
1.503     albertel 11952: 	return "$num1:$num2";
1.443     albertel 11953:     }
                   11954: }
                   11955: 
1.575     albertel 11956: sub rndseed_64bit4 {
                   11957:     my ($symb,$courseid,$domain,$username)=@_;
                   11958:     {
                   11959: 	use integer;
                   11960: 	# strings need to be an even # of cahracters long, it it is odd the
                   11961:         # last characters gets thrown away
                   11962: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11963: 	my $symbseed=numval3($symb) << 10;
                   11964: 	my $namechck=unpack("%32S*",$username.' ');
                   11965: 	
                   11966: 	my $nameseed=numval3($username) << 21;
                   11967: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11968: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11969: 	
                   11970: 	my $num1=$symbchck+$symbseed+$namechck;
                   11971: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11972: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11973: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11974: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11975: 	
1.575     albertel 11976: 	return "$num1:$num2";
                   11977:     }
                   11978: }
                   11979: 
1.675     albertel 11980: sub rndseed_64bit5 {
                   11981:     my ($symb,$courseid,$domain,$username)=@_;
                   11982:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11983:     return "$num1:$num2";
                   11984: }
                   11985: 
1.366     albertel 11986: sub rndseed_CODE_64bit {
                   11987:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11988:     {
1.366     albertel 11989: 	use integer;
1.443     albertel 11990: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11991: 	my $symbseed=numval2($symb);
1.491     albertel 11992: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11993: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11994: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11995: 	my $num1=$symbseed+$CODEchck;
                   11996: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11997: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11998: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11999: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12000: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12001: 	return "$num1:$num2";
1.366     albertel 12002:     }
                   12003: }
                   12004: 
1.575     albertel 12005: sub rndseed_CODE_64bit4 {
                   12006:     my ($symb,$courseid,$domain,$username)=@_;
                   12007:     {
                   12008: 	use integer;
                   12009: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12010: 	my $symbseed=numval3($symb);
                   12011: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12012: 	my $CODEseed=numval3(&getCODE());
                   12013: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12014: 	my $num1=$symbseed+$CODEchck;
                   12015: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12016: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12017: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12018: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12019: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12020: 	return "$num1:$num2";
                   12021:     }
                   12022: }
                   12023: 
1.675     albertel 12024: sub rndseed_CODE_64bit5 {
                   12025:     my ($symb,$courseid,$domain,$username)=@_;
                   12026:     my $code = &getCODE();
                   12027:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12028:     return "$num1:$num2";
                   12029: }
                   12030: 
1.366     albertel 12031: sub setup_random_from_rndseed {
                   12032:     my ($rndseed)=@_;
1.503     albertel 12033:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12034:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12035:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12036:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12037:         } else {
                   12038:             &Math::Random::random_set_seed($num1,$num2);
                   12039:         }
1.366     albertel 12040:     } else {
                   12041: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12042:     }
1.36      albertel 12043: }
                   12044: 
1.474     albertel 12045: sub latest_receipt_algorithm_id {
1.835     albertel 12046:     return 'receipt3';
1.474     albertel 12047: }
                   12048: 
1.480     www      12049: sub recunique {
                   12050:     my $fucourseid=shift;
                   12051:     my $unique;
1.835     albertel 12052:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12053: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12054: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12055:     } else {
                   12056: 	$unique=$perlvar{'lonReceipt'};
                   12057:     }
                   12058:     return unpack("%32C*",$unique);
                   12059: }
                   12060: 
                   12061: sub recprefix {
                   12062:     my $fucourseid=shift;
                   12063:     my $prefix;
1.835     albertel 12064:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12065: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12066: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12067:     } else {
                   12068: 	$prefix=$perlvar{'lonHostID'};
                   12069:     }
                   12070:     return unpack("%32C*",$prefix);
                   12071: }
                   12072: 
1.76      www      12073: sub ireceipt {
1.474     albertel 12074:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12075: 
                   12076:     my $return =&recprefix($fucourseid).'-';
                   12077: 
                   12078:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12079: 	$env{'request.state'} eq 'construct') {
                   12080: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12081: 	return $return;
                   12082:     }
                   12083: 
1.76      www      12084:     my $cuname=unpack("%32C*",$funame);
                   12085:     my $cudom=unpack("%32C*",$fudom);
                   12086:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12087:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12088:     my $cunique=&recunique($fucourseid);
1.474     albertel 12089:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12090:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12091: 
1.790     albertel 12092: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12093: 			       
                   12094: 	$return.= ($cunique%$cuname+
                   12095: 		   $cunique%$cudom+
                   12096: 		   $cusymb%$cuname+
                   12097: 		   $cusymb%$cudom+
                   12098: 		   $cucourseid%$cuname+
                   12099: 		   $cucourseid%$cudom+
                   12100: 		   $cpart%$cuname+
                   12101: 		   $cpart%$cudom);
                   12102:     } else {
                   12103: 	$return.= ($cunique%$cuname+
                   12104: 		   $cunique%$cudom+
                   12105: 		   $cusymb%$cuname+
                   12106: 		   $cusymb%$cudom+
                   12107: 		   $cucourseid%$cuname+
                   12108: 		   $cucourseid%$cudom);
                   12109:     }
                   12110:     return $return;
1.76      www      12111: }
                   12112: 
                   12113: sub receipt {
1.474     albertel 12114:     my ($part)=@_;
1.790     albertel 12115:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12116:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12117: }
1.260     ng       12118: 
1.790     albertel 12119: sub whichuser {
                   12120:     my ($passedsymb)=@_;
                   12121:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12122:     if (defined($env{'form.grade_symb'})) {
                   12123: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12124: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12125: 	if (!$allowed &&
                   12126: 	    exists($env{'request.course.sec'}) &&
                   12127: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12128: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12129: 			      '/'.$env{'request.course.sec'});
                   12130: 	}
                   12131: 	if ($allowed) {
                   12132: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12133: 	    $courseid=$tmp_courseid;
                   12134: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12135: 	    ($name)=&get_env_multiple('form.grade_username');
                   12136: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12137: 	}
                   12138:     }
                   12139:     if (!$passedsymb) {
                   12140: 	$symb=&symbread();
                   12141:     } else {
                   12142: 	$symb=$passedsymb;
                   12143:     }
                   12144:     $courseid=$env{'request.course.id'};
                   12145:     $domain=$env{'user.domain'};
                   12146:     $name=$env{'user.name'};
                   12147:     if ($name eq 'public' && $domain eq 'public') {
                   12148: 	if (!defined($env{'form.username'})) {
                   12149: 	    $env{'form.username'}.=time.rand(10000000);
                   12150: 	}
                   12151: 	$name.=$env{'form.username'};
                   12152:     }
                   12153:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12154: 
                   12155: }
                   12156: 
1.36      albertel 12157: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12158: # returns either the contents of the file or 
                   12159: # -1 if the file doesn't exist
1.481     raeburn  12160: #
                   12161: # if the target is a file that was uploaded via DOCS, 
                   12162: # a check will be made to see if a current copy exists on the local server,
                   12163: # if it does this will be served, otherwise a copy will be retrieved from
                   12164: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12165: # the local server.   
1.472     albertel 12166: 
1.36      albertel 12167: sub getfile {
1.538     albertel 12168:     my ($file) = @_;
1.609     banghart 12169:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12170:     &repcopy($file);
                   12171:     return &readfile($file);
                   12172: }
                   12173: 
                   12174: sub repcopy_userfile {
                   12175:     my ($file)=@_;
1.1142    raeburn  12176:     my $londocroot = $perlvar{'lonDocRoot'};
                   12177:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12178:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12179:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12180: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12181:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12182:     if (-e "$file") {
1.828     www      12183: # we already have a local copy, check it out
1.538     albertel 12184: 	my @fileinfo = stat($file);
1.828     www      12185: 	my $rtncode;
                   12186: 	my $info;
1.538     albertel 12187: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12188: 	if ($lwpresp ne 'ok') {
1.828     www      12189: # there is no such file anymore, even though we had a local copy
1.482     albertel 12190: 	    if ($rtncode eq '404') {
1.538     albertel 12191: 		unlink($file);
1.482     albertel 12192: 	    }
                   12193: 	    return -1;
                   12194: 	}
                   12195: 	if ($info < $fileinfo[9]) {
1.828     www      12196: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12197: 	    return 'ok';
1.828     www      12198: 	} else {
                   12199: # the file is outdated, get rid of it
                   12200: 	    unlink($file);
1.482     albertel 12201: 	}
1.828     www      12202:     }
                   12203: # one way or the other, at this point, we don't have the file
                   12204: # construct the correct path for the file
                   12205:     my @parts = ($cdom,$cnum); 
                   12206:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12207: 	push @parts, split(/\//,$1);
                   12208:     }
                   12209:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12210:     foreach my $part (@parts) {
                   12211: 	$path .= '/'.$part;
                   12212: 	if (!-e $path) {
                   12213: 	    mkdir($path,0770);
1.482     albertel 12214: 	}
                   12215:     }
1.828     www      12216: # now the path exists for sure
                   12217: # get a user agent
                   12218:     my $ua=new LWP::UserAgent;
                   12219:     my $transferfile=$file.'.in.transfer';
                   12220: # FIXME: this should flock
                   12221:     if (-e $transferfile) { return 'ok'; }
                   12222:     my $request;
                   12223:     $uri=~s/^\///;
1.980     raeburn  12224:     my $homeserver = &homeserver($cnum,$cdom);
                   12225:     my $protocol = $protocol{$homeserver};
                   12226:     $protocol = 'http' if ($protocol ne 'https');
                   12227:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12228:     my $response=$ua->request($request,$transferfile);
                   12229: # did it work?
                   12230:     if ($response->is_error()) {
                   12231: 	unlink($transferfile);
                   12232: 	&logthis("Userfile repcopy failed for $uri");
                   12233: 	return -1;
                   12234:     }
                   12235: # worked, rename the transfer file
                   12236:     rename($transferfile,$file);
1.607     raeburn  12237:     return 'ok';
1.481     raeburn  12238: }
                   12239: 
1.517     albertel 12240: sub tokenwrapper {
                   12241:     my $uri=shift;
1.980     raeburn  12242:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12243:     $uri=~s|^/||;
1.620     albertel 12244:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12245:     my $token=$1;
1.552     albertel 12246:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12247:     if ($udom && $uname && $file) {
                   12248: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12249:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12250:         my $homeserver = &homeserver($uname,$udom);
                   12251:         my $protocol = $protocol{$homeserver};
                   12252:         $protocol = 'http' if ($protocol ne 'https');
                   12253:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12254:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12255:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12256:     } else {
                   12257:         return '/adm/notfound.html';
                   12258:     }
                   12259: }
                   12260: 
1.828     www      12261: # call with reqtype HEAD: get last modification time
                   12262: # call with reqtype GET: get the file contents
                   12263: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12264: #
1.481     raeburn  12265: sub getuploaded {
                   12266:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12267:     $uri=~s/^\///;
1.980     raeburn  12268:     my $homeserver = &homeserver($cnum,$cdom);
                   12269:     my $protocol = $protocol{$homeserver};
                   12270:     $protocol = 'http' if ($protocol ne 'https');
                   12271:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12272:     my $ua=new LWP::UserAgent;
                   12273:     my $request=new HTTP::Request($reqtype,$uri);
                   12274:     my $response=$ua->request($request);
                   12275:     $$rtncode = $response->code;
1.482     albertel 12276:     if (! $response->is_success()) {
                   12277: 	return 'failed';
                   12278:     }      
                   12279:     if ($reqtype eq 'HEAD') {
1.486     www      12280: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12281:     } elsif ($reqtype eq 'GET') {
                   12282: 	$$info = $response->content;
1.472     albertel 12283:     }
1.482     albertel 12284:     return 'ok';
1.36      albertel 12285: }
                   12286: 
1.481     raeburn  12287: sub readfile {
                   12288:     my $file = shift;
                   12289:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12290:     my $fh;
                   12291:     open($fh,"<$file");
                   12292:     my $a='';
1.800     albertel 12293:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12294:     return $a;
                   12295: }
                   12296: 
1.36      albertel 12297: sub filelocation {
1.590     banghart 12298:     my ($dir,$file) = @_;
                   12299:     my $location;
                   12300:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12301: 
                   12302:     if ($file =~ m-^/adm/-) {
                   12303: 	$file=~s-^/adm/wrapper/-/-;
                   12304: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12305:     }
1.882     albertel 12306: 
1.1139    www      12307:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12308:         $location = $file;
1.609     banghart 12309:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12310:         my ($udom,$uname,$filename)=
1.811     albertel 12311:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12312:         my $home=&homeserver($uname,$udom);
                   12313:         my $is_me=0;
                   12314:         my @ids=&current_machine_ids();
                   12315:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12316:         if ($is_me) {
1.1117    foxr     12317:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12318:         } else {
                   12319:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12320:   	      $udom.'/'.$uname.'/'.$filename;
                   12321:         }
1.882     albertel 12322:     } elsif ($file =~ m-^/adm/-) {
                   12323: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12324:     } else {
                   12325:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12326:         $file=~s:^/(res|priv)/:/:;
                   12327:         my $space=$1;
1.590     banghart 12328:         if ( !( $file =~ m:^/:) ) {
                   12329:             $location = $dir. '/'.$file;
                   12330:         } else {
1.1142    raeburn  12331:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12332:         }
1.59      albertel 12333:     }
1.590     banghart 12334:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12335:     while ($location=~m{/\.\./}) {
                   12336: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12337: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12338: 	} else {
                   12339: 	    $location=~ s{/\.\./}{/}g;
                   12340: 	}
                   12341:     } #remove dir/..
1.590     banghart 12342:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12343:     return $location;
1.46      www      12344: }
1.36      albertel 12345: 
1.46      www      12346: sub hreflocation {
                   12347:     my ($dir,$file)=@_;
1.980     raeburn  12348:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12349: 	$file=filelocation($dir,$file);
1.700     albertel 12350:     } elsif ($file=~m-^/adm/-) {
                   12351: 	$file=~s-^/adm/wrapper/-/-;
                   12352: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12353:     }
                   12354:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12355: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12356:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12357: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12358: 	        {/uploaded/$1/$2/}x;
1.46      www      12359:     }
1.913     albertel 12360:     if ($file=~ m{^/userfiles/}) {
                   12361: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12362:     }
1.462     albertel 12363:     return $file;
1.465     albertel 12364: }
                   12365: 
1.1139    www      12366: 
                   12367: 
                   12368: 
                   12369: 
1.465     albertel 12370: sub current_machine_domains {
1.853     albertel 12371:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12372: }
                   12373: 
                   12374: sub machine_domains {
                   12375:     my ($hostname) = @_;
1.465     albertel 12376:     my @domains;
1.838     albertel 12377:     my %hostname = &all_hostnames();
1.465     albertel 12378:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12379: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12380: 	if ($hostname eq $name) {
1.844     albertel 12381: 	    push(@domains,&host_domain($id));
1.465     albertel 12382: 	}
                   12383:     }
                   12384:     return @domains;
                   12385: }
                   12386: 
                   12387: sub current_machine_ids {
1.853     albertel 12388:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12389: }
                   12390: 
                   12391: sub machine_ids {
                   12392:     my ($hostname) = @_;
                   12393:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12394:     my @ids;
1.888     albertel 12395:     my %name_to_host = &all_names();
1.889     albertel 12396:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12397: 	return @{ $name_to_host{$hostname} };
                   12398:     }
                   12399:     return;
1.31      www      12400: }
                   12401: 
1.824     raeburn  12402: sub additional_machine_domains {
                   12403:     my @domains;
                   12404:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12405:     while( my $line = <$fh>) {
                   12406:         $line =~ s/\s//g;
                   12407:         push(@domains,$line);
                   12408:     }
                   12409:     return @domains;
                   12410: }
                   12411: 
                   12412: sub default_login_domain {
                   12413:     my $domain = $perlvar{'lonDefDomain'};
                   12414:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12415:     foreach my $posdom (&current_machine_domains(),
                   12416:                         &additional_machine_domains()) {
                   12417:         if (lc($posdom) eq lc($testdomain)) {
                   12418:             $domain=$posdom;
                   12419:             last;
                   12420:         }
                   12421:     }
                   12422:     return $domain;
                   12423: }
                   12424: 
1.31      www      12425: # ------------------------------------------------------------- Declutters URLs
                   12426: 
                   12427: sub declutter {
                   12428:     my $thisfn=shift;
1.569     albertel 12429:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12430:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12431:         $thisfn=~s{^/home/httpd/html}{};
                   12432:     }
1.31      www      12433:     $thisfn=~s/^\///;
1.697     albertel 12434:     $thisfn=~s|^adm/wrapper/||;
                   12435:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12436:     $thisfn=~s/^res\///;
1.1172    bisitz   12437:     $thisfn=~s/^priv\///;
1.1032    raeburn  12438:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12439:         $thisfn=~s/\?.+$//;
                   12440:     }
1.268     www      12441:     return $thisfn;
                   12442: }
                   12443: 
                   12444: # ------------------------------------------------------------- Clutter up URLs
                   12445: 
                   12446: sub clutter {
                   12447:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12448:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12449: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12450:        $thisfn='/res'.$thisfn; 
                   12451:     }
1.1031    raeburn  12452:     if ($thisfn !~m|^/adm|) {
                   12453: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12454: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12455: 	} else {
                   12456: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12457: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12458: 	    if ($embstyle eq 'ssi'
                   12459: 		|| ($embstyle eq 'hdn')
                   12460: 		|| ($embstyle eq 'rat')
                   12461: 		|| ($embstyle eq 'prv')
                   12462: 		|| ($embstyle eq 'ign')) {
                   12463: 		#do nothing with these
                   12464: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12465: 		|| ($embstyle eq 'emb')
                   12466: 		|| ($embstyle eq 'wrp')) {
                   12467: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12468: 	    } elsif ($embstyle eq 'unk'
                   12469: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12470: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12471: 	    } else {
1.718     www      12472: #		&logthis("Got a blank emb style");
1.695     albertel 12473: 	    }
1.694     albertel 12474: 	}
1.1298    raeburn  12475:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12476:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12477:     }
1.31      www      12478:     return $thisfn;
1.12      www      12479: }
                   12480: 
1.787     albertel 12481: sub clutter_with_no_wrapper {
                   12482:     my $uri = &clutter(shift);
                   12483:     if ($uri =~ m-^/adm/-) {
                   12484: 	$uri =~ s-^/adm/wrapper/-/-;
                   12485: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12486:     }
                   12487:     return $uri;
                   12488: }
                   12489: 
1.557     albertel 12490: sub freeze_escape {
                   12491:     my ($value)=@_;
                   12492:     if (ref($value)) {
                   12493: 	$value=&nfreeze($value);
                   12494: 	return '__FROZEN__'.&escape($value);
                   12495:     }
                   12496:     return &escape($value);
                   12497: }
                   12498: 
1.11      www      12499: 
1.557     albertel 12500: sub thaw_unescape {
                   12501:     my ($value)=@_;
                   12502:     if ($value =~ /^__FROZEN__/) {
                   12503: 	substr($value,0,10,undef);
                   12504: 	$value=&unescape($value);
                   12505: 	return &thaw($value);
                   12506:     }
                   12507:     return &unescape($value);
                   12508: }
                   12509: 
1.436     albertel 12510: sub correct_line_ends {
                   12511:     my ($result)=@_;
                   12512:     $$result =~s/\r\n/\n/mg;
                   12513:     $$result =~s/\r/\n/mg;
1.415     albertel 12514: }
1.1       albertel 12515: # ================================================================ Main Program
                   12516: 
1.184     www      12517: sub goodbye {
1.204     albertel 12518:    &logthis("Starting Shut down");
1.443     albertel 12519: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12520:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12521: #converted
1.599     albertel 12522: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12523:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12524: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12525: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12526: #1.1 only
1.870     albertel 12527: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12528: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12529: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12530: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12531:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12532:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12533:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12534:    &flushcourselogs();
                   12535:    &logthis("Shutting down");
                   12536: }
                   12537: 
1.852     albertel 12538: sub get_dns {
1.1210    raeburn  12539:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12540:     if (!$ignore_cache) {
                   12541: 	my ($content,$cached)=
                   12542: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12543: 	if ($cached) {
1.1210    raeburn  12544: 	    &$func($content,$hashref);
1.869     albertel 12545: 	    return;
                   12546: 	}
                   12547:     }
                   12548: 
                   12549:     my %alldns;
1.852     albertel 12550:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12551:     foreach my $dns (<$config>) {
                   12552: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12553:         my $line = $1;
                   12554:         my ($host,$protocol) = split(/:/,$line);
                   12555:         if ($protocol ne 'https') {
                   12556:             $protocol = 'http';
                   12557:         }
                   12558: 	$alldns{$host} = $protocol;
1.869     albertel 12559:     }
                   12560:     while (%alldns) {
1.1263    raeburn  12561: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12562: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12563:         $ua->timeout(30);
1.979     raeburn  12564: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12565: 	my $response=$ua->request($request);
1.979     raeburn  12566:         delete($alldns{$dns});
1.852     albertel 12567: 	next if ($response->is_error());
                   12568: 	my @content = split("\n",$response->content);
1.1210    raeburn  12569: 	unless ($nocache) {
1.1219    raeburn  12570: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12571: 	}
                   12572: 	&$func(\@content,$hashref);
1.869     albertel 12573: 	return;
1.852     albertel 12574:     }
                   12575:     close($config);
1.871     albertel 12576:     my $which = (split('/',$url))[3];
                   12577:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12578:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12579:     my @content = <$config>;
1.1210    raeburn  12580:     &$func(\@content,$hashref);
                   12581:     return;
                   12582: }
                   12583: 
                   12584: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12585: sub parse_dns_checksums_tab {
1.1210    raeburn  12586:     my ($lines,$hashref) = @_;
1.1264    raeburn  12587:     my $lonhost = $perlvar{'lonHostID'};
                   12588:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12589:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12590:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12591:     my $webconfdir = '/etc/httpd/conf';
                   12592:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12593:         $webconfdir = '/etc/apache2';
                   12594:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12595:         if ($1 >= 10) {
                   12596:             $webconfdir = '/etc/apache2';
                   12597:         }
                   12598:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12599:         if ($1 >= 10.0) {
                   12600:             $webconfdir = '/etc/apache2';
                   12601:         }
                   12602:     }
1.1210    raeburn  12603:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12604:     my (%chksum,%revnum);
                   12605:     if (ref($lines) eq 'ARRAY') {
                   12606:         chomp(@{$lines});
1.1238    raeburn  12607:         my $version = shift(@{$lines});
                   12608:         if ($version eq $release) {  
1.1210    raeburn  12609:             foreach my $line (@{$lines}) {
1.1238    raeburn  12610:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12611:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12612:                     if ($webconfdir eq '/etc/apache2') {
                   12613:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12614:                     }
                   12615:                 }
1.1238    raeburn  12616:                 $chksum{$file} = $shasum;
                   12617:                 $revnum{$file} = $version;
1.1210    raeburn  12618:             }
                   12619:             if (ref($hashref) eq 'HASH') {
                   12620:                 %{$hashref} = (
                   12621:                                 sums     => \%chksum,
                   12622:                                 versions => \%revnum,
                   12623:                               );
                   12624:             }
                   12625:         }
                   12626:     }
1.869     albertel 12627:     return;
1.852     albertel 12628: }
1.1210    raeburn  12629: 
                   12630: sub fetch_dns_checksums {
1.1238    raeburn  12631:     my %checksums;
                   12632:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12633:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12634:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12635:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12636:              \%checksums);
1.1210    raeburn  12637:     return \%checksums;
                   12638: }
                   12639: 
1.327     albertel 12640: # ------------------------------------------------------------ Read domain file
                   12641: {
1.852     albertel 12642:     my $loaded;
1.846     albertel 12643:     my %domain;
                   12644: 
1.852     albertel 12645:     sub parse_domain_tab {
                   12646: 	my ($lines) = @_;
                   12647: 	foreach my $line (@$lines) {
                   12648: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12649: 
1.846     albertel 12650: 	    chomp($line);
1.852     albertel 12651: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12652: 	    my %this_domain;
                   12653: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12654: 			       'lang_def', 'city', 'longi', 'lati',
                   12655: 			       'primary') {
                   12656: 		$this_domain{$field} = shift(@elements);
                   12657: 	    }
                   12658: 	    $domain{$name} = \%this_domain;
1.852     albertel 12659: 	}
                   12660:     }
1.864     albertel 12661: 
                   12662:     sub reset_domain_info {
                   12663: 	undef($loaded);
                   12664: 	undef(%domain);
                   12665:     }
                   12666: 
1.852     albertel 12667:     sub load_domain_tab {
1.1293    raeburn  12668: 	my ($ignore_cache,$nocache) = @_;
                   12669: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12670: 	my $fh;
                   12671: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12672: 	    my @lines = <$fh>;
                   12673: 	    &parse_domain_tab(\@lines);
1.448     albertel 12674: 	}
1.852     albertel 12675: 	close($fh);
                   12676: 	$loaded = 1;
1.327     albertel 12677:     }
1.846     albertel 12678: 
                   12679:     sub domain {
1.852     albertel 12680: 	&load_domain_tab() if (!$loaded);
                   12681: 
1.846     albertel 12682: 	my ($name,$what) = @_;
                   12683: 	return if ( !exists($domain{$name}) );
                   12684: 
                   12685: 	if (!$what) {
                   12686: 	    return $domain{$name}{'description'};
                   12687: 	}
                   12688: 	return $domain{$name}{$what};
                   12689:     }
1.974     raeburn  12690: 
                   12691:     sub domain_info {
                   12692:         &load_domain_tab() if (!$loaded);
                   12693:         return %domain;
                   12694:     }
                   12695: 
1.327     albertel 12696: }
                   12697: 
                   12698: 
1.1       albertel 12699: # ------------------------------------------------------------- Read hosts file
                   12700: {
1.838     albertel 12701:     my %hostname;
1.844     albertel 12702:     my %hostdom;
1.845     albertel 12703:     my %libserv;
1.852     albertel 12704:     my $loaded;
1.888     albertel 12705:     my %name_to_host;
1.1074    raeburn  12706:     my %internetdom;
1.1107    raeburn  12707:     my %LC_dns_serv;
1.852     albertel 12708: 
                   12709:     sub parse_hosts_tab {
                   12710: 	my ($file) = @_;
                   12711: 	foreach my $configline (@$file) {
                   12712: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12713:             chomp($configline);
                   12714: 	    if ($configline =~ /^\^/) {
                   12715:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12716:                     $LC_dns_serv{$1} = 1;
                   12717:                 }
                   12718:                 next;
                   12719:             }
1.1074    raeburn  12720: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12721: 	    $name=~s/\s//g;
                   12722: 	    if ($id && $domain && $role && $name) {
                   12723: 		$hostname{$id}=$name;
1.888     albertel 12724: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12725: 		$hostdom{$id}=$domain;
                   12726: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12727:                 if (defined($protocol)) {
                   12728:                     if ($protocol eq 'https') {
                   12729:                         $protocol{$id} = $protocol;
                   12730:                     } else {
                   12731:                         $protocol{$id} = 'http'; 
                   12732:                     }
1.968     raeburn  12733:                 } else {
1.969     raeburn  12734:                     $protocol{$id} = 'http';
1.968     raeburn  12735:                 }
1.1074    raeburn  12736:                 if (defined($intdom)) {
                   12737:                     $internetdom{$id} = $intdom;
                   12738:                 }
1.852     albertel 12739: 	    }
                   12740: 	}
                   12741:     }
1.864     albertel 12742:     
                   12743:     sub reset_hosts_info {
1.897     albertel 12744: 	&purge_remembered();
1.864     albertel 12745: 	&reset_domain_info();
                   12746: 	&reset_hosts_ip_info();
1.892     albertel 12747: 	undef(%name_to_host);
1.864     albertel 12748: 	undef(%hostname);
                   12749: 	undef(%hostdom);
                   12750: 	undef(%libserv);
                   12751: 	undef($loaded);
                   12752:     }
1.1       albertel 12753: 
1.852     albertel 12754:     sub load_hosts_tab {
1.1293    raeburn  12755: 	my ($ignore_cache,$nocache) = @_;
                   12756: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12757: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12758: 	my @config = <$config>;
                   12759: 	&parse_hosts_tab(\@config);
                   12760: 	close($config);
                   12761: 	$loaded=1;
1.1       albertel 12762:     }
1.852     albertel 12763: 
1.838     albertel 12764:     sub hostname {
1.852     albertel 12765: 	&load_hosts_tab() if (!$loaded);
                   12766: 
1.838     albertel 12767: 	my ($lonid) = @_;
                   12768: 	return $hostname{$lonid};
                   12769:     }
1.845     albertel 12770: 
1.838     albertel 12771:     sub all_hostnames {
1.852     albertel 12772: 	&load_hosts_tab() if (!$loaded);
                   12773: 
1.838     albertel 12774: 	return %hostname;
                   12775:     }
1.845     albertel 12776: 
1.888     albertel 12777:     sub all_names {
1.1293    raeburn  12778:         my ($ignore_cache,$nocache) = @_;
                   12779: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12780: 
                   12781: 	return %name_to_host;
                   12782:     }
                   12783: 
1.974     raeburn  12784:     sub all_host_domain {
                   12785:         &load_hosts_tab() if (!$loaded);
                   12786:         return %hostdom;
                   12787:     }
                   12788: 
1.845     albertel 12789:     sub is_library {
1.852     albertel 12790: 	&load_hosts_tab() if (!$loaded);
                   12791: 
1.845     albertel 12792: 	return exists($libserv{$_[0]});
                   12793:     }
                   12794: 
                   12795:     sub all_library {
1.852     albertel 12796: 	&load_hosts_tab() if (!$loaded);
                   12797: 
1.845     albertel 12798: 	return %libserv;
                   12799:     }
                   12800: 
1.1062    droeschl 12801:     sub unique_library {
                   12802: 	#2x reverse removes all hostnames that appear more than once
                   12803:         my %unique = reverse &all_library();
                   12804:         return reverse %unique;
                   12805:     }
                   12806: 
1.841     albertel 12807:     sub get_servers {
1.852     albertel 12808: 	&load_hosts_tab() if (!$loaded);
                   12809: 
1.841     albertel 12810: 	my ($domain,$type) = @_;
                   12811: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12812: 	                                          : %hostname;
                   12813: 	my %result;
1.842     albertel 12814: 	if (ref($domain) eq 'ARRAY') {
                   12815: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12816: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12817: 		    $result{$host} = $hostname;
                   12818: 		}
                   12819: 	    }
                   12820: 	} else {
                   12821: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12822: 		if ($hostdom{$host} eq $domain) {
                   12823: 		    $result{$host} = $hostname;
                   12824: 		}
1.841     albertel 12825: 	    }
                   12826: 	}
                   12827: 	return %result;
                   12828:     }
1.845     albertel 12829: 
1.1062    droeschl 12830:     sub get_unique_servers {
                   12831:         my %unique = reverse &get_servers(@_);
                   12832: 	return reverse %unique;
                   12833:     }
                   12834: 
1.844     albertel 12835:     sub host_domain {
1.852     albertel 12836: 	&load_hosts_tab() if (!$loaded);
                   12837: 
1.844     albertel 12838: 	my ($lonid) = @_;
                   12839: 	return $hostdom{$lonid};
                   12840:     }
                   12841: 
1.841     albertel 12842:     sub all_domains {
1.852     albertel 12843: 	&load_hosts_tab() if (!$loaded);
                   12844: 
1.841     albertel 12845: 	my %seen;
                   12846: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12847: 	return @uniq;
                   12848:     }
1.1074    raeburn  12849: 
                   12850:     sub internet_dom {
                   12851:         &load_hosts_tab() if (!$loaded);
                   12852: 
                   12853:         my ($lonid) = @_;
                   12854:         return $internetdom{$lonid};
                   12855:     }
1.1107    raeburn  12856: 
                   12857:     sub is_LC_dns {
                   12858:         &load_hosts_tab() if (!$loaded);
                   12859: 
                   12860:         my ($hostname) = @_;
                   12861:         return exists($LC_dns_serv{$hostname});
                   12862:     }
                   12863: 
1.1       albertel 12864: }
                   12865: 
1.847     albertel 12866: { 
                   12867:     my %iphost;
1.856     albertel 12868:     my %name_to_ip;
                   12869:     my %lonid_to_ip;
1.869     albertel 12870: 
1.847     albertel 12871:     sub get_hosts_from_ip {
                   12872: 	my ($ip) = @_;
                   12873: 	my %iphosts = &get_iphost();
                   12874: 	if (ref($iphosts{$ip})) {
                   12875: 	    return @{$iphosts{$ip}};
                   12876: 	}
                   12877: 	return;
1.839     albertel 12878:     }
1.864     albertel 12879:     
                   12880:     sub reset_hosts_ip_info {
                   12881: 	undef(%iphost);
                   12882: 	undef(%name_to_ip);
                   12883: 	undef(%lonid_to_ip);
                   12884:     }
1.856     albertel 12885: 
                   12886:     sub get_host_ip {
                   12887: 	my ($lonid) = @_;
                   12888: 	if (exists($lonid_to_ip{$lonid})) {
                   12889: 	    return $lonid_to_ip{$lonid};
                   12890: 	}
                   12891: 	my $name=&hostname($lonid);
                   12892:    	my $ip = gethostbyname($name);
                   12893: 	return if (!$ip || length($ip) ne 4);
                   12894: 	$ip=inet_ntoa($ip);
                   12895: 	$name_to_ip{$name}   = $ip;
                   12896: 	$lonid_to_ip{$lonid} = $ip;
                   12897: 	return $ip;
                   12898:     }
1.847     albertel 12899:     
                   12900:     sub get_iphost {
1.1293    raeburn  12901: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12902: 
1.869     albertel 12903: 	if (!$ignore_cache) {
                   12904: 	    if (%iphost) {
                   12905: 		return %iphost;
                   12906: 	    }
                   12907: 	    my ($ip_info,$cached)=
                   12908: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12909: 	    if ($cached) {
                   12910: 		%iphost      = %{$ip_info->[0]};
                   12911: 		%name_to_ip  = %{$ip_info->[1]};
                   12912: 		%lonid_to_ip = %{$ip_info->[2]};
                   12913: 		return %iphost;
                   12914: 	    }
                   12915: 	}
1.894     albertel 12916: 
                   12917: 	# get yesterday's info for fallback
                   12918: 	my %old_name_to_ip;
                   12919: 	my ($ip_info,$cached)=
                   12920: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12921: 	if ($cached) {
                   12922: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12923: 	}
                   12924: 
1.1293    raeburn  12925: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 12926: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12927: 	    my $ip;
                   12928: 	    if (!exists($name_to_ip{$name})) {
                   12929: 		$ip = gethostbyname($name);
                   12930: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12931: 		    if (defined($old_name_to_ip{$name})) {
                   12932: 			$ip = $old_name_to_ip{$name};
                   12933: 			&logthis("Can't find $name defaulting to old $ip");
                   12934: 		    } else {
                   12935: 			&logthis("Name $name no IP found");
                   12936: 			next;
                   12937: 		    }
                   12938: 		} else {
                   12939: 		    $ip=inet_ntoa($ip);
1.847     albertel 12940: 		}
                   12941: 		$name_to_ip{$name} = $ip;
                   12942: 	    } else {
                   12943: 		$ip = $name_to_ip{$name};
1.653     albertel 12944: 	    }
1.888     albertel 12945: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12946: 		$lonid_to_ip{$id} = $ip;
                   12947: 	    }
                   12948: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12949: 	}
1.1293    raeburn  12950:         unless ($nocache) {
                   12951: 	    &do_cache_new('iphost','iphost',
                   12952: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12953: 		          48*60*60);
                   12954:         }
1.869     albertel 12955: 
1.847     albertel 12956: 	return %iphost;
1.598     albertel 12957:     }
                   12958: 
1.992     raeburn  12959:     #
                   12960:     #  Given a DNS returns the loncapa host name for that DNS 
                   12961:     # 
                   12962:     sub host_from_dns {
                   12963:         my ($dns) = @_;
                   12964:         my @hosts;
                   12965:         my $ip;
                   12966: 
1.993     raeburn  12967:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12968:             $ip = $name_to_ip{$dns};
                   12969:         }
                   12970:         if (!$ip) {
                   12971:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12972:             if (length($ip) == 4) { 
                   12973: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12974:             }
                   12975:         }
                   12976:         if ($ip) {
                   12977: 	    @hosts = get_hosts_from_ip($ip);
                   12978: 	    return $hosts[0];
                   12979:         }
                   12980:         return undef;
1.986     foxr     12981:     }
1.992     raeburn  12982: 
1.1074    raeburn  12983:     sub get_internet_names {
                   12984:         my ($lonid) = @_;
                   12985:         return if ($lonid eq '');
                   12986:         my ($idnref,$cached)=
                   12987:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12988:         if ($cached) {
                   12989:             return $idnref;
                   12990:         }
                   12991:         my $ip = &get_host_ip($lonid);
                   12992:         my @hosts = &get_hosts_from_ip($ip);
                   12993:         my %iphost = &get_iphost();
                   12994:         my (@idns,%seen);
                   12995:         foreach my $id (@hosts) {
                   12996:             my $dom = &host_domain($id);
                   12997:             my $prim_id = &domain($dom,'primary');
                   12998:             my $prim_ip = &get_host_ip($prim_id);
                   12999:             next if ($seen{$prim_ip});
                   13000:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13001:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13002:                     my $intdom = &internet_dom($id);
                   13003:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13004:                         push(@idns,$intdom);
                   13005:                     }
                   13006:                 }
                   13007:             }
                   13008:             $seen{$prim_ip} = 1;
                   13009:         }
1.1219    raeburn  13010:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13011:     }
                   13012: 
1.986     foxr     13013: }
                   13014: 
1.1079    raeburn  13015: sub all_loncaparevs {
1.1249    raeburn  13016:     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  13017: }
                   13018: 
1.1227    raeburn  13019: # ---------------------------------------------------------- Read loncaparev table
                   13020: {
                   13021:     sub load_loncaparevs { 
                   13022:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13023:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13024:                 while (my $configline=<$config>) {
                   13025:                     chomp($configline);
                   13026:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13027:                     $loncaparevs{$hostid}=$loncaparev;
                   13028:                 }
                   13029:                 close($config);
                   13030:             }
                   13031:         }
                   13032:     }
                   13033: }
                   13034: 
                   13035: # ---------------------------------------------------------- Read serverhostID table
                   13036: {
                   13037:     sub load_serverhomeIDs {
                   13038:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13039:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13040:                 while (my $configline=<$config>) {
                   13041:                     chomp($configline);
                   13042:                     my ($name,$id)=split(/:/,$configline);
                   13043:                     $serverhomeIDs{$name}=$id;
                   13044:                 }
                   13045:                 close($config);
                   13046:             }
                   13047:         }
                   13048:     }
                   13049: }
                   13050: 
                   13051: 
1.862     albertel 13052: BEGIN {
                   13053: 
                   13054: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13055:     unless ($readit) {
                   13056: {
                   13057:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13058:     %perlvar = (%perlvar,%{$configvars});
                   13059: }
                   13060: 
                   13061: 
1.1       albertel 13062: # ------------------------------------------------------ Read spare server file
                   13063: {
1.448     albertel 13064:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13065: 
                   13066:     while (my $configline=<$config>) {
                   13067:        chomp($configline);
1.284     matthew  13068:        if ($configline) {
1.784     albertel 13069: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13070: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13071: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13072:        }
                   13073:     }
1.448     albertel 13074:     close($config);
1.1       albertel 13075: }
1.11      www      13076: # ------------------------------------------------------------ Read permissions
                   13077: {
1.448     albertel 13078:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13079: 
                   13080:     while (my $configline=<$config>) {
1.448     albertel 13081: 	chomp($configline);
                   13082: 	if ($configline) {
                   13083: 	    my ($role,$perm)=split(/ /,$configline);
                   13084: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13085: 	}
1.11      www      13086:     }
1.448     albertel 13087:     close($config);
1.11      www      13088: }
                   13089: 
                   13090: # -------------------------------------------- Read plain texts for permissions
                   13091: {
1.448     albertel 13092:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13093: 
                   13094:     while (my $configline=<$config>) {
1.448     albertel 13095: 	chomp($configline);
                   13096: 	if ($configline) {
1.742     raeburn  13097: 	    my ($short,@plain)=split(/:/,$configline);
                   13098:             %{$prp{$short}} = ();
                   13099: 	    if (@plain > 0) {
                   13100:                 $prp{$short}{'std'} = $plain[0];
                   13101:                 for (my $i=1; $i<@plain; $i++) {
                   13102:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13103:                 }
                   13104:             }
1.448     albertel 13105: 	}
1.135     www      13106:     }
1.448     albertel 13107:     close($config);
1.135     www      13108: }
                   13109: 
                   13110: # ---------------------------------------------------------- Read package table
                   13111: {
1.448     albertel 13112:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13113: 
                   13114:     while (my $configline=<$config>) {
1.483     albertel 13115: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13116: 	chomp($configline);
                   13117: 	my ($short,$plain)=split(/:/,$configline);
                   13118: 	my ($pack,$name)=split(/\&/,$short);
                   13119: 	if ($plain ne '') {
                   13120: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13121: 	    $packagetab{$short}=$plain; 
                   13122: 	}
1.11      www      13123:     }
1.448     albertel 13124:     close($config);
1.329     matthew  13125: }
                   13126: 
1.1073    raeburn  13127: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13128: 
                   13129: &load_loncaparevs();
1.1073    raeburn  13130: 
1.1074    raeburn  13131: # ---------------------------------------------------------- Read serverhostID table
                   13132: 
1.1227    raeburn  13133: &load_serverhomeIDs();
                   13134: 
                   13135: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13136: {
                   13137:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13138:     if (-e $file) {
                   13139:         my $parser = HTML::LCParser->new($file);
                   13140:         while (my $token = $parser->get_token()) {
                   13141:             if ($token->[0] eq 'S') {
                   13142:                 my $item = $token->[1];
                   13143:                 my $name = $token->[2]{'name'};
                   13144:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13145:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13146:                 my $namematch = $token->[2]{'namematch'};
                   13147:                 if ($item eq 'parameter') {
                   13148:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13149:                         my $release = $parser->get_text();
                   13150:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13151:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13152:                     }
                   13153:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13154:                     my $release = $parser->get_text();
                   13155:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13156:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13157:                 }
                   13158:             }
                   13159:         }
                   13160:     }
1.1073    raeburn  13161: }
                   13162: 
1.1138    raeburn  13163: # ---------------------------------------------------------- Read managers table
                   13164: {
                   13165:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13166:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13167:             while (my $configline=<$config>) {
                   13168:                 chomp($configline);
                   13169:                 next if ($configline =~ /^\#/);
                   13170:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13171:                     $managerstab{$configline} = 1;
                   13172:                 }
                   13173:             }
                   13174:             close($config);
                   13175:         }
                   13176:     }
                   13177: }
                   13178: 
1.329     matthew  13179: # ------------- set up temporary directory
                   13180: {
1.1117    foxr     13181:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13182: 
1.11      www      13183: }
                   13184: 
1.794     albertel 13185: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13186: 				'compress_threshold'=> 20_000,
                   13187:  			        });
1.185     www      13188: 
1.281     www      13189: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13190: $dumpcount=0;
1.958     www      13191: $locknum=0;
1.22      www      13192: 
1.163     harris41 13193: &logtouch();
1.672     albertel 13194: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13195: $readit=1;
1.564     albertel 13196:     {
                   13197: 	use integer;
                   13198: 	my $test=(2**32)+1;
1.568     albertel 13199: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13200: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13201:     }
1.195     www      13202: }
1.1       albertel 13203: }
1.179     www      13204: 
1.1       albertel 13205: 1;
1.191     harris41 13206: __END__
                   13207: 
1.243     albertel 13208: =pod
                   13209: 
1.191     harris41 13210: =head1 NAME
                   13211: 
1.243     albertel 13212: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13213: 
                   13214: =head1 SYNOPSIS
                   13215: 
1.243     albertel 13216: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13217: 
                   13218:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13219: 
1.243     albertel 13220: Common parameters:
                   13221: 
                   13222: =over 4
                   13223: 
                   13224: =item *
                   13225: 
                   13226: $uname : an internal username (if $cname expecting a course Id specifically)
                   13227: 
                   13228: =item *
                   13229: 
                   13230: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13231: 
                   13232: =item *
                   13233: 
                   13234: $symb : a resource instance identifier
                   13235: 
                   13236: =item *
                   13237: 
                   13238: $namespace : the name of a .db file that contains the data needed or
                   13239: being set.
                   13240: 
                   13241: =back
                   13242: 
1.394     bowersj2 13243: =head1 OVERVIEW
1.191     harris41 13244: 
1.394     bowersj2 13245: lonnet provides subroutines which interact with the
                   13246: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13247: about classes, users, and resources.
1.243     albertel 13248: 
                   13249: For many of these objects you can also use this to store data about
                   13250: them or modify them in various ways.
1.191     harris41 13251: 
1.394     bowersj2 13252: =head2 Symbs
1.191     harris41 13253: 
1.394     bowersj2 13254: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13255: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13256: map, the resource number of the resource in the map, and the URL of
                   13257: the resource itself. The latter is somewhat redundant, but might help
                   13258: if maps change.
                   13259: 
                   13260: An example is
                   13261: 
                   13262:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13263: 
                   13264: The respective map entry is
                   13265: 
                   13266:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13267:   title="Problem 2">
                   13268:  </resource>
                   13269: 
                   13270: Symbs are used by the random number generator, as well as to store and
                   13271: restore data specific to a certain instance of for example a problem.
                   13272: 
                   13273: =head2 Storing And Retrieving Data
                   13274: 
                   13275: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13276: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13277: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13278: is is the non-critical message twin of cstore. These functions are for
                   13279: handlers to store a perl hash to a user's permanent data space in an
                   13280: easy manner, and to retrieve it again on another call. It is expected
                   13281: that a handler would use this once at the beginning to retrieve data,
                   13282: and then again once at the end to send only the new data back.
                   13283: 
                   13284: The data is stored in the user's data directory on the user's
                   13285: homeserver under the ID of the course.
                   13286: 
                   13287: The hash that is returned by restore will have all of the previous
                   13288: value for all of the elements of the hash.
                   13289: 
                   13290: Example:
                   13291: 
                   13292:  #creating a hash
                   13293:  my %hash;
                   13294:  $hash{'foo'}='bar';
                   13295: 
                   13296:  #storing it
                   13297:  &Apache::lonnet::cstore(\%hash);
                   13298: 
                   13299:  #changing a value
                   13300:  $hash{'foo'}='notbar';
                   13301: 
                   13302:  #adding a new value
                   13303:  $hash{'bar'}='foo';
                   13304:  &Apache::lonnet::cstore(\%hash);
                   13305: 
                   13306:  #retrieving the hash
                   13307:  my %history=&Apache::lonnet::restore();
                   13308: 
                   13309:  #print the hash
                   13310:  foreach my $key (sort(keys(%history))) {
                   13311:    print("\%history{$key} = $history{$key}");
                   13312:  }
                   13313: 
                   13314: Will print out:
1.191     harris41 13315: 
1.394     bowersj2 13316:  %history{1:foo} = bar
                   13317:  %history{1:keys} = foo:timestamp
                   13318:  %history{1:timestamp} = 990455579
                   13319:  %history{2:bar} = foo
                   13320:  %history{2:foo} = notbar
                   13321:  %history{2:keys} = foo:bar:timestamp
                   13322:  %history{2:timestamp} = 990455580
                   13323:  %history{bar} = foo
                   13324:  %history{foo} = notbar
                   13325:  %history{timestamp} = 990455580
                   13326:  %history{version} = 2
                   13327: 
                   13328: Note that the special hash entries C<keys>, C<version> and
                   13329: C<timestamp> were added to the hash. C<version> will be equal to the
                   13330: total number of versions of the data that have been stored. The
                   13331: C<timestamp> attribute will be the UNIX time the hash was
                   13332: stored. C<keys> is available in every historical section to list which
                   13333: keys were added or changed at a specific historical revision of a
                   13334: hash.
                   13335: 
                   13336: B<Warning>: do not store the hash that restore returns directly. This
                   13337: will cause a mess since it will restore the historical keys as if the
                   13338: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13339: 
1.394     bowersj2 13340: Calling convention:
1.191     harris41 13341: 
1.1225    raeburn  13342:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13343:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13344: 
1.394     bowersj2 13345: For more detailed information, see lonnet specific documentation.
1.191     harris41 13346: 
1.394     bowersj2 13347: =head1 RETURN MESSAGES
1.191     harris41 13348: 
1.394     bowersj2 13349: =over 4
1.191     harris41 13350: 
1.394     bowersj2 13351: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13352: 
1.394     bowersj2 13353: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13354: when the connection is brought back up
1.191     harris41 13355: 
1.394     bowersj2 13356: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13357: for later delivery
1.191     harris41 13358: 
1.967     bisitz   13359: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13360: 
1.394     bowersj2 13361: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13362: that was requested
1.191     harris41 13363: 
1.243     albertel 13364: =back
1.191     harris41 13365: 
1.243     albertel 13366: =head1 PUBLIC SUBROUTINES
1.191     harris41 13367: 
1.243     albertel 13368: =head2 Session Environment Functions
1.191     harris41 13369: 
1.243     albertel 13370: =over 4
1.191     harris41 13371: 
1.394     bowersj2 13372: =item * 
                   13373: X<appenv()>
1.949     raeburn  13374: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13375: the user envirnoment file, and will be restored for each access this
1.620     albertel 13376: user makes during this session, also modifies the %env for the current
1.949     raeburn  13377: process. Optional rolesarrayref - if defined contains a reference to an array
                   13378: of roles which are exempt from the restriction on modifying user.role entries 
                   13379: in the user's environment.db and in %env.    
1.191     harris41 13380: 
                   13381: =item *
1.394     bowersj2 13382: X<delenv()>
1.987     raeburn  13383: B<delenv($delthis,$regexp)>: removes all items from the session
                   13384: environment file that begin with $delthis. If the 
                   13385: optional second arg - $regexp - is true, $delthis is treated as a 
                   13386: regular expression, otherwise \Q$delthis\E is used. 
                   13387: The values are also deleted from the current processes %env.
1.191     harris41 13388: 
1.795     albertel 13389: =item * get_env_multiple($name) 
                   13390: 
                   13391: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13392: values may be defined and end up as an array ref.
                   13393: 
                   13394: returns an array of values
                   13395: 
1.243     albertel 13396: =back
                   13397: 
                   13398: =head2 User Information
1.191     harris41 13399: 
1.243     albertel 13400: =over 4
1.191     harris41 13401: 
                   13402: =item *
1.394     bowersj2 13403: X<queryauthenticate()>
                   13404: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13405: authentication scheme
                   13406: 
                   13407: =item *
1.394     bowersj2 13408: X<authenticate()>
1.1073    raeburn  13409: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13410: authenticate user from domain's lib servers (first use the current
                   13411: one). C<$upass> should be the users password.
1.1073    raeburn  13412: $checkdefauth is optional (value is 1 if a check should be made to
                   13413:    authenticate user using default authentication method, and allow
                   13414:    account creation if username does not have account in the domain).
                   13415: $clientcancheckhost is optional (value is 1 if checking whether the
                   13416:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13417: 
                   13418: =item *
1.394     bowersj2 13419: X<homeserver()>
                   13420: B<homeserver($uname,$udom)>: find the server which has
                   13421: the user's directory and files (there must be only one), this caches
                   13422: the answer, and also caches if there is a borken connection.
1.191     harris41 13423: 
                   13424: =item *
1.394     bowersj2 13425: X<idget()>
1.1300    raeburn  13426: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13427: a list of student/employee IDs or clicker IDs
                   13428: (student/employee IDs are a unique resource in a domain, there must be 
                   13429: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13430: clickerIDs are not necessarily unique, as students might share clickers.
                   13431: (returns hash: id=>name,id=>name)
1.191     harris41 13432: 
                   13433: =item *
1.394     bowersj2 13434: X<idrget()>
                   13435: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13436: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13437: 
                   13438: =item *
1.394     bowersj2 13439: X<idput()>
1.1300    raeburn  13440: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13441: names and associated student/employee IDs or clicker IDs.
                   13442: 
                   13443: =item *
                   13444: X<iddel()>
                   13445: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13446: student/employee ID or clicker ID username look-ups from domain.
                   13447: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13448: If no $uhome is provided, it will be determined usig &homeserver()
                   13449: for each user.  If no $namespace is provided, the default is ids.
                   13450: 
                   13451: =item *
                   13452: X<updateclickers()>
                   13453: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13454: clicker ID-to-username look-ups in clickers.db on library server.
                   13455: Permitted actions are add or del (i.e., add or delete). The 
                   13456: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13457: value is an escaped comma-separated list of usernames (for whom the
                   13458: library server is the homeserver), who registered that particular ID.
                   13459: If $critical is true, the update will be sent via &critical, otherwise
                   13460: &reply() will be used.
1.191     harris41 13461: 
                   13462: =item *
1.394     bowersj2 13463: X<rolesinit()>
1.1169    droeschl 13464: B<rolesinit($udom,$username)>: get user privileges.
                   13465: returns user role, first access and timer interval hashes
1.243     albertel 13466: 
                   13467: =item *
1.1171    droeschl 13468: X<privileged()>
                   13469: B<privileged($username,$domain)>: returns a true if user has a
                   13470: privileged and active role (i.e. su or dc), false otherwise.
                   13471: 
                   13472: =item *
1.551     albertel 13473: X<getsection()>
                   13474: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13475: course $cname, return section name/number or '' for "not in course"
                   13476: and '-1' for "no section"
                   13477: 
                   13478: =item *
1.394     bowersj2 13479: X<userenvironment()>
                   13480: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13481: passed in @what from the requested user's environment, returns a hash
                   13482: 
1.858     raeburn  13483: =item * 
                   13484: X<userlog_query()>
1.859     albertel 13485: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13486: activity.log file. %filters defines filters applied when parsing the
                   13487: log file. These can be start or end timestamps, or the type of action
                   13488: - log to look for Login or Logout events, check for Checkin or
                   13489: Checkout, role for role selection. The response is in the form
                   13490: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13491: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13492: 
1.243     albertel 13493: =back
                   13494: 
                   13495: =head2 User Roles
                   13496: 
                   13497: =over 4
                   13498: 
                   13499: =item *
                   13500: 
1.1284    raeburn  13501: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13502: returns codes for allowed actions.
                   13503: 
                   13504: The first argument is required, all others are optional.
                   13505: 
                   13506: $priv is the privilege being checked.
                   13507: $uri contains additional information about what is being checked for access (e.g.,
                   13508: URL, course ID etc.). 
                   13509: $symb is the unique resource instance identifier in a course; if needed,
                   13510: but not provided, it will be retrieved via a call to &symbread(). 
                   13511: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13512: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13513: files).
                   13514: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13515: prevents recursive calls to &allowed.
                   13516: 
1.243     albertel 13517:  F: full access
                   13518:  U,I,K: authentication modes (cxx only)
                   13519:  '': forbidden
                   13520:  1: user needs to choose course
                   13521:  2: browse allowed
1.766     albertel 13522:  A: passphrase authentication needed
1.1284    raeburn  13523:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13524: 
                   13525: =item *
                   13526: 
1.1192    raeburn  13527: constructaccess($url,$setpriv) : check for access to construction space URL
                   13528: 
                   13529: See if the owner domain and name in the URL match those in the
                   13530: expected environment.  If so, return three element list
                   13531: ($ownername,$ownerdomain,$ownerhome).
                   13532: 
                   13533: Otherwise return the null string.
                   13534: 
                   13535: If second argument 'setpriv' is true, it assigns the privileges,
                   13536: and returns the same three element list, unless the owner has
                   13537: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13538: in which case the null string is returned.
                   13539: 
                   13540: =item *
                   13541: 
1.243     albertel 13542: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13543: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13544: and course level
                   13545: 
                   13546: =item *
                   13547: 
1.988     raeburn  13548: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13549: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13550: $type is Course (default) or Community.
1.988     raeburn  13551: If $forcedefault evaluates to true, text returned will be default 
                   13552: text for $type. Otherwise, if this is a course, the text returned 
                   13553: will be a custom name for the role (if defined in the course's 
                   13554: environment).  If no custom name is defined the default is returned.
                   13555:    
1.832     raeburn  13556: =item *
                   13557: 
1.1219    raeburn  13558: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13559: All arguments are optional. Returns a hash of a roles, either for
                   13560: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13561: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13562: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13563: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13564: For each key, value is set to colon-separated start and end times for
                   13565: the role.  If no username and domain are specified, will default to
1.934     raeburn  13566: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13567: of role statuses (active, future or previous), roles 
                   13568: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13569: to restrict the list of roles reported. If no array ref is 
                   13570: provided for types, will default to return only active roles.
1.834     albertel 13571: 
1.1195    raeburn  13572: =item *
                   13573: 
                   13574: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13575: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13576: 
                   13577: Additional optional arguments are: $type (if role checking is to be restricted 
                   13578: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13579: available roles) or future (roles available in the future), and
                   13580: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13581: have active Domain Coordinator role in course's domain or in additional
                   13582: domains (specified in 'Domains to check for privileged users' in course
                   13583: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13584: 
                   13585: =item *
                   13586: 
                   13587: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13588: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13589: $possdomains and $possroles are optional array refs -- to domains to check and
                   13590: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13591: users' roles.db to check for a dc or su role in any domain. This can be
                   13592: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13593: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13594: this then allows &privileged_by_domain() to be used, which caches the identity
                   13595: of privileged users, eliminating the need for repeated calls to &dump().
                   13596: 
                   13597: =item *
                   13598: 
                   13599: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13600: where the outer hash keys are domains specified in the $possdomains array ref,
                   13601: next inner hash keys are privileged roles specified in the $roles array ref,
                   13602: and the innermost hash contains key = value pairs for username:domain = end:start
                   13603: for active or future "privileged" users with that role in that domain. To avoid
                   13604: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13605: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13606: 
1.243     albertel 13607: =back
                   13608: 
                   13609: =head2 User Modification
                   13610: 
                   13611: =over 4
                   13612: 
                   13613: =item *
                   13614: 
1.957     raeburn  13615: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13616: user for the level given by URL.  Optional start and end dates (leave empty
                   13617: string or zero for "no date")
1.191     harris41 13618: 
                   13619: =item *
                   13620: 
1.243     albertel 13621: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13622: change a users, password, possible return values are: ok,
                   13623: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13624: refused
1.191     harris41 13625: 
                   13626: =item *
                   13627: 
1.243     albertel 13628: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13629: 
                   13630: =item *
                   13631: 
1.1058    raeburn  13632: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13633:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13634: 
                   13635: will update user information (firstname,middlename,lastname,generation,
                   13636: permanentemail), and if forceid is true, student/employee ID also.
                   13637: A user's institutional affiliation(s) can also be updated.
                   13638: User information fields will not be overwritten with empty entries 
                   13639: unless the field is included in the $candelete array reference.
                   13640: This array is included when a single user is modified via "Manage Users",
                   13641: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13642: 
                   13643: =item *
                   13644: 
1.286     matthew  13645: modifystudent
                   13646: 
1.957     raeburn  13647: modify a student's enrollment and identification information.
1.1235    raeburn  13648: The course id is resolved based on the current user's environment.  
                   13649: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13650: associated with a course.
                   13651: 
1.297     matthew  13652: This call is essentially a wrapper for lonnet::modifyuser and
                   13653: lonnet::modify_student_enrollment
1.286     matthew  13654: 
                   13655: Inputs: 
                   13656: 
                   13657: =over 4
                   13658: 
1.957     raeburn  13659: =item B<$udom> Student's loncapa domain
1.286     matthew  13660: 
1.957     raeburn  13661: =item B<$uname> Student's loncapa login name
1.286     matthew  13662: 
1.964     bisitz   13663: =item B<$uid> Student/Employee ID
1.286     matthew  13664: 
1.957     raeburn  13665: =item B<$umode> Student's authentication mode
1.286     matthew  13666: 
1.957     raeburn  13667: =item B<$upass> Student's password
1.286     matthew  13668: 
1.957     raeburn  13669: =item B<$first> Student's first name
1.286     matthew  13670: 
1.957     raeburn  13671: =item B<$middle> Student's middle name
1.286     matthew  13672: 
1.957     raeburn  13673: =item B<$last> Student's last name
1.286     matthew  13674: 
1.957     raeburn  13675: =item B<$gene> Student's generation
1.286     matthew  13676: 
1.957     raeburn  13677: =item B<$usec> Student's section in course
1.286     matthew  13678: 
                   13679: =item B<$end> Unix time of the roles expiration
                   13680: 
                   13681: =item B<$start> Unix time of the roles start date
                   13682: 
                   13683: =item B<$forceid> If defined, allow $uid to be changed
                   13684: 
                   13685: =item B<$desiredhome> server to use as home server for student
                   13686: 
1.957     raeburn  13687: =item B<$email> Student's permanent e-mail address
                   13688: 
                   13689: =item B<$type> Type of enrollment (auto or manual)
                   13690: 
1.963     raeburn  13691: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13692: 
                   13693: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13694: 
1.963     raeburn  13695: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13696: 
1.963     raeburn  13697: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13698: 
1.1216    raeburn  13699: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13700: 
                   13701: =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  13702: 
1.286     matthew  13703: =back
1.297     matthew  13704: 
                   13705: =item *
                   13706: 
                   13707: modify_student_enrollment
                   13708: 
1.1235    raeburn  13709: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13710: 'role.request.course' must be defined for this function to proceed.
                   13711: 
                   13712: Inputs:
                   13713: 
                   13714: =over 4
                   13715: 
1.1235    raeburn  13716: =item $udom, student's domain
1.297     matthew  13717: 
1.1235    raeburn  13718: =item $uname, student's name
1.297     matthew  13719: 
1.1235    raeburn  13720: =item $uid, student's user id
1.297     matthew  13721: 
1.1235    raeburn  13722: =item $first, student's first name
1.297     matthew  13723: 
                   13724: =item $middle
                   13725: 
                   13726: =item $last
                   13727: 
                   13728: =item $gene
                   13729: 
                   13730: =item $usec
                   13731: 
                   13732: =item $end
                   13733: 
                   13734: =item $start
                   13735: 
1.957     raeburn  13736: =item $type
                   13737: 
                   13738: =item $locktype
                   13739: 
                   13740: =item $cid
                   13741: 
                   13742: =item $selfenroll
                   13743: 
                   13744: =item $context
                   13745: 
1.1216    raeburn  13746: =item $credits, number of credits student will earn from this class
                   13747: 
1.297     matthew  13748: =back
                   13749: 
1.191     harris41 13750: 
                   13751: =item *
                   13752: 
1.243     albertel 13753: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13754: custom role; give a custom role to a user for the level given by URL.  Specify
                   13755: name and domain of role author, and role name
1.191     harris41 13756: 
                   13757: =item *
                   13758: 
1.243     albertel 13759: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13760: 
                   13761: =item *
                   13762: 
1.243     albertel 13763: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13764: 
                   13765: =back
                   13766: 
                   13767: =head2 Course Infomation
                   13768: 
                   13769: =over 4
1.191     harris41 13770: 
                   13771: =item *
                   13772: 
1.1118    foxr     13773: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13774: specified course id, including all environment settings for the
                   13775: course, the description of the course will be in the hash under the
                   13776: key 'description'
1.191     harris41 13777: 
1.1118    foxr     13778: $options is an optional parameter that if supplied is a hash reference that controls
                   13779: what how this function works.  It has the following key/values:
                   13780: 
                   13781: =over 4
                   13782: 
                   13783: =item freshen_cache
                   13784: 
                   13785: If defined, and the environment cache for the course is valid, it is 
                   13786: returned in the returned hash.
                   13787: 
                   13788: =item one_time
                   13789: 
                   13790: If defined, the last cache time is set to _now_
                   13791: 
                   13792: =item user
                   13793: 
                   13794: If defined, the supplied username is used instead of the current user.
                   13795: 
                   13796: 
                   13797: =back
                   13798: 
1.191     harris41 13799: =item *
                   13800: 
1.624     albertel 13801: resdata($name,$domain,$type,@which) : request for current parameter
                   13802: setting for a specific $type, where $type is either 'course' or 'user',
                   13803: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13804: answers for 10 minutes.
1.243     albertel 13805: 
1.877     foxr     13806: =item *
                   13807: 
                   13808: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13809: data base, returning a hash that is keyed by the resource name and has
                   13810: values that are the resource value.  I believe that the timestamps and
                   13811: versions are also returned.
                   13812: 
1.1236    raeburn  13813: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13814: supplemental content area. This routine caches the number of files for 
                   13815: 10 minutes.
                   13816: 
1.243     albertel 13817: =back
                   13818: 
                   13819: =head2 Course Modification
                   13820: 
                   13821: =over 4
1.191     harris41 13822: 
                   13823: =item *
                   13824: 
1.243     albertel 13825: writecoursepref($courseid,%prefs) : write preferences (environment
                   13826: database) for a course
1.191     harris41 13827: 
                   13828: =item *
                   13829: 
1.1011    raeburn  13830: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13831: 
                   13832: =item *
                   13833: 
1.1038    raeburn  13834: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13835: 
1.1167    droeschl 13836: =item *
                   13837: 
                   13838: is_course($courseid), is_course($cdom, $cnum)
                   13839: 
                   13840: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13841: two component version $cdom, $cnum. It checks if the specified course exists.
                   13842: 
                   13843: Returns:
                   13844:     undef if the course doesn't exist, otherwise
                   13845:     in scalar context the combined courseid.
                   13846:     in list context the two components of the course identifier, domain and 
                   13847:     courseid.    
                   13848: 
1.243     albertel 13849: =back
                   13850: 
                   13851: =head2 Resource Subroutines
                   13852: 
                   13853: =over 4
1.191     harris41 13854: 
                   13855: =item *
                   13856: 
1.243     albertel 13857: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13858: 
                   13859: =item *
                   13860: 
1.243     albertel 13861: repcopy($filename) : subscribes to the requested file, and attempts to
                   13862: replicate from the owning library server, Might return
1.607     raeburn  13863: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13864: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13865: resource. Expects the local filesystem pathname
                   13866: (/home/httpd/html/res/....)
                   13867: 
                   13868: =back
                   13869: 
                   13870: =head2 Resource Information
                   13871: 
                   13872: =over 4
1.191     harris41 13873: 
                   13874: =item *
                   13875: 
1.1228    raeburn  13876: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13877: and returns the value of a variety of different possible values,
                   13878: $varname should be a request string, and the other parameters can be
                   13879: used to specify who and what one is asking about. Ordinarily, $cid 
                   13880: does not need to be specified, as it is retrived from 
                   13881: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13882: within lonuserstate::loadmap() when initializing a course, before
                   13883: $env{'request.course.id'} has been set, so it needs to be provided
                   13884: in that one case.
1.243     albertel 13885: 
                   13886: Possible values for $varname are environment.lastname (or other item
                   13887: from the envirnment hash), user.name (or someother aspect about the
                   13888: user), resource.0.maxtries (or some other part and parameter of a
                   13889: resource)
1.204     albertel 13890: 
                   13891: =item *
                   13892: 
1.243     albertel 13893: directcondval($number) : get current value of a condition; reads from a state
                   13894: string
1.204     albertel 13895: 
                   13896: =item *
                   13897: 
1.243     albertel 13898: condval($condidx) : value of condition index based on state
1.204     albertel 13899: 
                   13900: =item *
                   13901: 
1.243     albertel 13902: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13903: resource's metadata, $what should be either a specific key, or either
                   13904: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13905: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13906: 
                   13907: this function automatically caches all requests
1.191     harris41 13908: 
                   13909: =item *
                   13910: 
1.243     albertel 13911: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13912: network of library servers; returns file handle of where SQL and regex results
                   13913: will be stored for query
1.191     harris41 13914: 
                   13915: =item *
                   13916: 
1.1282    raeburn  13917: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   13918: return symbolic list entry (all arguments optional). 
                   13919: 
                   13920: Args: filename is the filename (including path) for the file for which a symb 
                   13921: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   13922: to check access status if more than one resource was found in the bighash 
                   13923: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   13924: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   13925: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13926: cause possible symbs to be checked to determine if they are subject to content
                   13927: blocking, if so they will not be included as possible symbs; possibles is a
                   13928: ref to a hash, which, as a side effect, will be populated with all possible 
                   13929: symbs (content blocking not tested).
                   13930:  
1.243     albertel 13931: returns the data handle
1.191     harris41 13932: 
                   13933: =item *
                   13934: 
1.1190    raeburn  13935: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13936: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13937: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13938: on failure, user must be in a course, as it assumes the existence of
                   13939: the course initial hash, and uses $env('request.course.id'}.  The third
                   13940: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13941: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13942: encrypted; otherwise it will be null.  
1.191     harris41 13943: 
                   13944: =item *
                   13945: 
1.243     albertel 13946: symbclean($symb) : removes versions numbers from a symb, returns the
                   13947: cleaned symb
1.191     harris41 13948: 
                   13949: =item *
                   13950: 
1.243     albertel 13951: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13952: course map, user must be in a course for it to work.
1.191     harris41 13953: 
                   13954: =item *
                   13955: 
1.243     albertel 13956: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13957: 
                   13958: =item *
                   13959: 
1.243     albertel 13960: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13961: a random seed, all arguments are optional, if they aren't sent it uses the
                   13962: environment to derive them. Note: if symb isn't sent and it can't get one
                   13963: from &symbread it will use the current time as its return value
1.191     harris41 13964: 
                   13965: =item *
                   13966: 
1.243     albertel 13967: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13968: unfakeable, receipt
1.191     harris41 13969: 
                   13970: =item *
                   13971: 
1.620     albertel 13972: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13973: 
                   13974: =item *
                   13975: 
1.243     albertel 13976: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13977: 
                   13978: =item *
                   13979: 
1.243     albertel 13980: 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 13981: 
                   13982: =item *
                   13983: 
1.243     albertel 13984: 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 13985: 
                   13986: =item *
                   13987: 
1.243     albertel 13988: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13989: 
                   13990: =item *
                   13991: 
1.243     albertel 13992: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13993: forcing spreadsheet to reevaluate the resource scores next time.
                   13994: 
1.1195    raeburn  13995: =item * 
                   13996: 
1.1196    raeburn  13997: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13998: when viewing in course context.
1.1195    raeburn  13999: 
1.1196    raeburn  14000:  input: six args -- filename (decluttered), course number, course domain,
                   14001:                     url, symb (if registered) and group (if this is a 
                   14002:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14003: 
1.1196    raeburn  14004:  output: array of five scalars --
1.1195    raeburn  14005:          $cfile -- url for file editing if editable on current server
                   14006:          $home -- homeserver of resource (i.e., for author if published,
                   14007:                                           or course if uploaded.).
                   14008:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14009:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14010:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14011: 
                   14012: =item *
                   14013: 
                   14014: is_course_upload($file,$cnum,$cdom)
                   14015: 
                   14016: Used in course context to determine if current file was uploaded to 
                   14017: the course (i.e., would be found in /userfiles/docs on the course's 
                   14018: homeserver.
                   14019: 
                   14020:   input: 3 args -- filename (decluttered), course number and course domain.
                   14021:   output: boolean -- 1 if file was uploaded.
                   14022: 
1.243     albertel 14023: =back
                   14024: 
                   14025: =head2 Storing/Retreiving Data
                   14026: 
                   14027: =over 4
1.191     harris41 14028: 
                   14029: =item *
                   14030: 
1.1269    raeburn  14031: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14032: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14033: the remaining args aren't required and if they aren't passed or are '' they will
                   14034: be derived from the env (with the exception of $laststore, which is an 
                   14035: optional arg used when a user's submission is stored in grading).
                   14036: $laststore is $version=$timestamp, where $version is the most recent version
                   14037: number retrieved for the corresponding $symb in the $namespace db file, and
                   14038: $timestamp is the timestamp for that transaction (UNIX time).
                   14039: $laststore is currently only passed when cstore() is called by 
                   14040: structuretags::finalize_storage().
1.191     harris41 14041: 
                   14042: =item *
                   14043: 
1.1269    raeburn  14044: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14045: but uses critical subroutine
1.191     harris41 14046: 
                   14047: =item *
                   14048: 
1.243     albertel 14049: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14050: all args are optional
1.191     harris41 14051: 
                   14052: =item *
                   14053: 
1.717     albertel 14054: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14055: dumps the complete (or key matching regexp) namespace into a hash
                   14056: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14057: normally &store()ed into
                   14058: 
                   14059: $range should be either an integer '100' (give me the first 100
                   14060:                                            matching records)
                   14061:               or be  two integers sperated by a - with no spaces
                   14062:                  '30-50' (give me the 30th through the 50th matching
                   14063:                           records)
                   14064: 
                   14065: 
                   14066: =item *
                   14067: 
1.1269    raeburn  14068: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14069: replaces a &store() version of data with a replacement set of data
                   14070: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14071: reference. If $tolog is true, the transaction is logged in the courselog
                   14072: with an action=PUTSTORE.
1.717     albertel 14073: 
                   14074: =item *
                   14075: 
1.243     albertel 14076: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14077: works very similar to store/cstore, but all data is stored in a
                   14078: temporary location and can be reset using tmpreset, $storehash should
                   14079: be a hash reference, returns nothing on success
1.191     harris41 14080: 
                   14081: =item *
                   14082: 
1.243     albertel 14083: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14084: similar to restore, but all data is stored in a temporary location and
                   14085: can be reset using tmpreset. Returns a hash of values on success,
                   14086: error string otherwise.
1.191     harris41 14087: 
                   14088: =item *
                   14089: 
1.243     albertel 14090: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14091: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14092: 
                   14093: =item *
                   14094: 
1.243     albertel 14095: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14096: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14097: 
                   14098: =item *
                   14099: 
1.243     albertel 14100: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14101: namesp ($udom and $uname are optional)
1.191     harris41 14102: 
                   14103: =item *
                   14104: 
1.702     albertel 14105: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14106: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14107: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14108: 
1.702     albertel 14109: $range should be either an integer '100' (give me the first 100
                   14110:                                            matching records)
                   14111:               or be  two integers sperated by a - with no spaces
                   14112:                  '30-50' (give me the 30th through the 50th matching
                   14113:                           records)
1.449     matthew  14114: =item *
                   14115: 
                   14116: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14117: $store can be a scalar, an array reference, or if the amount to be 
                   14118: incremented is > 1, a hash reference.
                   14119: 
                   14120: ($udom and $uname are optional)
1.191     harris41 14121: 
                   14122: =item *
                   14123: 
1.243     albertel 14124: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14125: ($udom and $uname are optional)
1.191     harris41 14126: 
                   14127: =item *
                   14128: 
1.243     albertel 14129: cput($namespace,$storehash,$udom,$uname) : critical put
                   14130: ($udom and $uname are optional)
1.191     harris41 14131: 
                   14132: =item *
                   14133: 
1.748     albertel 14134: newput($namespace,$storehash,$udom,$uname) :
                   14135: 
                   14136: Attempts to store the items in the $storehash, but only if they don't
                   14137: currently exist, if this succeeds you can be certain that you have 
                   14138: successfully created a new key value pair in the $namespace db.
                   14139: 
                   14140: 
                   14141: Args:
                   14142:  $namespace: name of database to store values to
                   14143:  $storehash: hashref to store to the db
                   14144:  $udom: (optional) domain of user containing the db
                   14145:  $uname: (optional) name of user caontaining the db
                   14146: 
                   14147: Returns:
                   14148:  'ok' -> succeeded in storing all keys of $storehash
                   14149:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14150:                         least <key> already existed in the db (other
                   14151:                         requested keys may also already exist)
1.967     bisitz   14152:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14153:  'con_lost' -> unable to contact request server
                   14154:  'refused' -> action was not allowed by remote machine
                   14155: 
                   14156: 
                   14157: =item *
                   14158: 
1.243     albertel 14159: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14160: reference filled in from namesp (encrypts the return communication)
                   14161: ($udom and $uname are optional)
1.191     harris41 14162: 
                   14163: =item *
                   14164: 
1.243     albertel 14165: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14166: critical subroutine
                   14167: 
1.806     raeburn  14168: =item *
                   14169: 
1.860     raeburn  14170: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14171: array reference filled in from namespace found in domain level on either
                   14172: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14173: 
                   14174: =item *
                   14175: 
1.860     raeburn  14176: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14177: domain level either on specified domain server ($uhome) or primary domain 
                   14178: server ($udom and $uhome are optional)
1.806     raeburn  14179: 
1.943     raeburn  14180: =item * 
                   14181: 
1.1240    raeburn  14182: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14183: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14184: the target domain.
                   14185: 
                   14186: May also include additional key => value pairs for the following groups:
                   14187: 
                   14188: =over
                   14189: 
                   14190: =item
                   14191: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14192: 
                   14193: =over
                   14194: 
                   14195: =item defaultquota, authorquota
                   14196: 
                   14197: =back
                   14198: 
                   14199: =item
                   14200: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14201: portfolio for users).
                   14202: 
                   14203: =over
                   14204: 
                   14205: =item
                   14206: aboutme, blog, webdav, portfolio
                   14207: 
                   14208: =back
                   14209: 
                   14210: =item
                   14211: requestcourses: ability to request courses, and how requests are processed.
                   14212: 
                   14213: =over
                   14214: 
                   14215: =item
1.1305    raeburn  14216: official, unofficial, community, textbook, placement
1.1240    raeburn  14217: 
                   14218: =back
                   14219: 
                   14220: =item
                   14221: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14222: 
                   14223: =over
                   14224: 
                   14225: =item
1.1256    raeburn  14226: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14227: 
                   14228: =back
                   14229: 
                   14230: =item
                   14231: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14232: for course's uploaded content.
                   14233: 
                   14234: =over
                   14235: 
                   14236: =item
1.1246    raeburn  14237: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14238: communityquota, textbookquota, placementquota
1.1240    raeburn  14239: 
                   14240: =back
                   14241: 
                   14242: =item
                   14243: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14244: on your servers.
                   14245: 
                   14246: =over
                   14247: 
                   14248: =item 
                   14249: remotesessions, hostedsessions
                   14250: 
                   14251: =back
                   14252: 
                   14253: =back
                   14254: 
                   14255: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14256: utility to create a configuration.db file on a domain's primary library server 
                   14257: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14258: -- corresponding values are authentication type (internal, krb4, krb5,
                   14259: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14260: will be available. Values are retrieved from cache (if current), unless the
                   14261: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14262: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14263: 
                   14264: Typical usage:
1.943     raeburn  14265: 
1.1240    raeburn  14266: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14267: 
1.243     albertel 14268: =back
                   14269: 
                   14270: =head2 Network Status Functions
                   14271: 
                   14272: =over 4
1.191     harris41 14273: 
                   14274: =item *
                   14275: 
1.1137    raeburn  14276: dirlist() : return directory list based on URI (first arg).
                   14277: 
                   14278: Inputs: 1 required, 5 optional.
                   14279: 
                   14280: =over
                   14281: 
                   14282: =item 
                   14283: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14284: 
                   14285: =item
                   14286: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14287: 
                   14288: =item
                   14289: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14290: 
                   14291: =item
                   14292: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14293: 
                   14294: =item
                   14295: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14296: 
                   14297: =item 
                   14298: $alternateRoot - path to prepend in place of path from $uri.
                   14299: 
                   14300: =back
                   14301: 
                   14302: Returns: Array of up to two items.
                   14303: 
                   14304: =over
                   14305: 
                   14306: a reference to an array of files/subdirectories
                   14307: 
                   14308: =over
                   14309: 
                   14310: Each element in the array of files/subdirectories is a & separated list of
                   14311: item name and the result of running stat on the item.  If dirlist was requested
                   14312: for a file instead of a directory, the item name will be ''. For a directory 
                   14313: listing, if the item is a metadata file, the element will end &N&M 
                   14314: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14315: default copyright set (1).  
                   14316: 
                   14317: =back
                   14318: 
                   14319: a scalar containing error condition (if encountered).
                   14320: 
                   14321: =over
                   14322: 
                   14323: =item 
                   14324: no_host (no homeserver identified for $username:$domain).
                   14325: 
                   14326: =item 
                   14327: no_such_host (server contacted for listing not identified as valid host).
                   14328: 
                   14329: =item 
                   14330: con_lost (connection to remote server failed).
                   14331: 
                   14332: =item 
                   14333: refused (invalid $username:$domain received on lond side).
                   14334: 
                   14335: =item 
                   14336: no_such_dir (directory at specified path on lond side does not exist). 
                   14337: 
                   14338: =item 
                   14339: empty (directory at specified path on lond side is empty).
                   14340: 
                   14341: =over
                   14342: 
                   14343: This is currently not encountered because the &ls3, &ls2, 
                   14344: &ls (_handler) routines on the lond side do not filter out
                   14345: . and .. from a directory listing. 
                   14346: 
                   14347: =back
                   14348: 
                   14349: =back
                   14350: 
                   14351: =back
1.191     harris41 14352: 
                   14353: =item *
                   14354: 
1.243     albertel 14355: spareserver() : find server with least workload from spare.tab
                   14356: 
1.986     foxr     14357: 
                   14358: =item *
                   14359: 
                   14360: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14361: if there is no corresponding loncapa host.
                   14362: 
1.243     albertel 14363: =back
                   14364: 
1.986     foxr     14365: 
1.243     albertel 14366: =head2 Apache Request
                   14367: 
                   14368: =over 4
1.191     harris41 14369: 
                   14370: =item *
                   14371: 
1.243     albertel 14372: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14373: localhost, posts hash
                   14374: 
                   14375: =back
                   14376: 
                   14377: =head2 Data to String to Data
                   14378: 
                   14379: =over 4
1.191     harris41 14380: 
                   14381: =item *
                   14382: 
1.243     albertel 14383: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14384: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14385: 
                   14386: =item *
                   14387: 
1.243     albertel 14388: hashref2str($hashref) : convert a hashref into a string complete with
                   14389: escaping and '=' and '&' separators, supports elements that are
                   14390: arrayrefs and hashrefs
1.191     harris41 14391: 
                   14392: =item *
                   14393: 
1.243     albertel 14394: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14395: with escaping and '&' separators, supports elements that are arrayrefs
                   14396: and hashrefs
1.191     harris41 14397: 
                   14398: =item *
                   14399: 
1.243     albertel 14400: str2hash($string) : convert string to hash using unescaping and
                   14401: splitting on '=' and '&', supports elements that are arrayrefs and
                   14402: hashrefs
1.191     harris41 14403: 
                   14404: =item *
                   14405: 
1.243     albertel 14406: str2array($string) : convert string to hash using unescaping and
                   14407: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14408: 
                   14409: =back
                   14410: 
                   14411: =head2 Logging Routines
                   14412: 
                   14413: 
                   14414: These routines allow one to make log messages in the lonnet.log and
                   14415: lonnet.perm logfiles.
1.191     harris41 14416: 
1.1119    foxr     14417: =over 4
                   14418: 
1.191     harris41 14419: =item *
                   14420: 
1.243     albertel 14421: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14422: 
                   14423: =item *
                   14424: 
1.243     albertel 14425: logthis() : append message to the normal lonnet.log file, it gets
                   14426: preiodically rolled over and deleted.
1.191     harris41 14427: 
                   14428: =item *
                   14429: 
1.243     albertel 14430: logperm() : append a permanent message to lonnet.perm.log, this log
                   14431: file never gets deleted by any automated portion of the system, only
                   14432: messages of critical importance should go in here.
                   14433: 
1.1119    foxr     14434: 
1.243     albertel 14435: =back
                   14436: 
                   14437: =head2 General File Helper Routines
                   14438: 
                   14439: =over 4
1.191     harris41 14440: 
                   14441: =item *
                   14442: 
1.481     raeburn  14443: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14444: (a) files in /uploaded
                   14445:   (i) If a local copy of the file exists - 
                   14446:       compares modification date of local copy with last-modified date for 
                   14447:       definitive version stored on home server for course. If local copy is 
                   14448:       stale, requests a new version from the home server and stores it. 
                   14449:       If the original has been removed from the home server, then local copy 
                   14450:       is unlinked.
                   14451:   (ii) If local copy does not exist -
                   14452:       requests the file from the home server and stores it. 
                   14453:   
                   14454:   If $caller is 'uploadrep':  
                   14455:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14456:     for request for files originally uploaded via DOCS. 
                   14457:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14458:   
                   14459:   Otherwise:
                   14460:      This indicates a call from the content generation phase of the request.
                   14461:      -  returns the entire contents of the file or -1.
                   14462:      
                   14463: (b) files in /res
                   14464:    - returns the entire contents of a file or -1; 
                   14465:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14466: 
1.712     albertel 14467: 
                   14468: =item *
                   14469: 
                   14470: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14471:                   reference
                   14472: 
                   14473: returns either a stat() list of data about the file or an empty list
                   14474: if the file doesn't exist or couldn't find out about it (connection
                   14475: problems or user unknown)
                   14476: 
1.191     harris41 14477: =item *
                   14478: 
1.243     albertel 14479: filelocation($dir,$file) : returns file system location of a file
                   14480: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14481: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14482: and a file of ../bob will become /a/bob)
1.191     harris41 14483: 
                   14484: =item *
                   14485: 
                   14486: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14487: filelocation except for hrefs
                   14488: 
                   14489: =item *
                   14490: 
1.1261    raeburn  14491: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14492: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14493: 
1.243     albertel 14494: =back
                   14495: 
1.608     albertel 14496: =head2 Usererfile file routines (/uploaded*)
                   14497: 
                   14498: =over 4
                   14499: 
                   14500: =item *
                   14501: 
                   14502: userfileupload(): main rotine for putting a file in a user or course's
                   14503:                   filespace, arguments are,
                   14504: 
1.620     albertel 14505:  formname - required - this is the name of the element in $env where the
1.608     albertel 14506:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14507:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14508:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14509:  context - if coursedoc, store the file in the course of the active role
                   14510:              of the current user; 
                   14511:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14512:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14513:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14514:          if undefined, it will be placed in "unknown"
                   14515: 
                   14516:  (This routine calls clean_filename() to remove any dangerous
                   14517:  characters from the filename, and then calls finuserfileupload() to
                   14518:  complete the transaction)
                   14519: 
                   14520:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14521:  and /adm/notfound.html if unsuccessful
                   14522: 
                   14523: =item *
                   14524: 
                   14525: clean_filename(): routine for cleaing a filename up for storage in
                   14526:                  userfile space, argument is:
                   14527: 
                   14528:  filename - proposed filename
                   14529: 
                   14530: returns: the new clean filename
                   14531: 
                   14532: =item *
                   14533: 
1.1090    raeburn  14534: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14535: userspace, probably shouldn't be called directly
                   14536: 
                   14537:   docuname: username or courseid of destination for the file
                   14538:   docudom: domain of user/course of destination for the file
                   14539:   formname: same as for userfileupload()
1.1090    raeburn  14540:   fname: filename (including subdirectories) for the file
                   14541:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14542:   allfiles: reference to hash used to store objects found by parser
                   14543:   codebase: reference to hash used for codebases of java objects found by parser
                   14544:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14545:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14546:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14547:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14548:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14549:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14550:   mimetype: reference to scalar to accommodate mime type determined
                   14551:             from File::MMagic if $parser = parse.
1.608     albertel 14552: 
                   14553:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14554:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14555:  was 'overwrite').
                   14556:  
1.608     albertel 14557: 
                   14558: =item *
                   14559: 
                   14560: renameuserfile(): renames an existing userfile to a new name
                   14561: 
                   14562:   Args:
                   14563:    docuname: username or courseid of destination for the file
                   14564:    docudom: domain of user/course of destination for the file
                   14565:    old: current file name (including any subdirs under userfiles)
                   14566:    new: desired file name (including any subdirs under userfiles)
                   14567: 
                   14568: =item *
                   14569: 
                   14570: mkdiruserfile(): creates a directory is a userfiles dir
                   14571: 
                   14572:   Args:
                   14573:    docuname: username or courseid of destination for the file
                   14574:    docudom: domain of user/course of destination for the file
                   14575:    dir: dir to create (including any subdirs under userfiles)
                   14576: 
                   14577: =item *
                   14578: 
                   14579: removeuserfile(): removes a file that exists in userfiles
                   14580: 
                   14581:   Args:
                   14582:    docuname: username or courseid of destination for the file
                   14583:    docudom: domain of user/course of destination for the file
                   14584:    fname: filname to delete (including any subdirs under userfiles)
                   14585: 
                   14586: =item *
                   14587: 
                   14588: removeuploadedurl(): convience function for removeuserfile()
                   14589: 
                   14590:   Args:
                   14591:    url:  a full /uploaded/... url to delete
                   14592: 
1.747     albertel 14593: =item * 
                   14594: 
                   14595: get_portfile_permissions():
                   14596:   Args:
                   14597:     domain: domain of user or course contain the portfolio files
                   14598:     user: name of user or num of course contain the portfolio files
                   14599:   Returns:
                   14600:     hashref of a dump of the proper file_permissions.db
                   14601:    
                   14602: 
                   14603: =item * 
                   14604: 
                   14605: get_access_controls():
                   14606: 
                   14607: Args:
                   14608:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14609:   group: (optional) the group you want the files associated with
                   14610:   file: (optional) the file you want access info on
                   14611: 
                   14612: Returns:
1.749     raeburn  14613:     a hash (keys are file names) of hashes containing
                   14614:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14615:         values are XML containing access control settings (see below) 
1.747     albertel 14616: 
                   14617: Internal notes:
                   14618: 
1.749     raeburn  14619:  access controls are stored in file_permissions.db as key=value pairs.
                   14620:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14621:         where scope -> public,guest,course,group,domains or users.
                   14622:               end -> UNIX time for end of access (0 -> no end date)
                   14623:               start -> UNIX time for start of access
                   14624: 
                   14625:     value -> XML description of access control
                   14626:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14627:             <start></start>
                   14628:             <end></end>
                   14629: 
                   14630:             <password></password>  for scope type = guest
                   14631: 
                   14632:             <domain></domain>     for scope type = course or group
                   14633:             <number></number>
                   14634:             <roles id="">
                   14635:              <role></role>
                   14636:              <access></access>
                   14637:              <section></section>
                   14638:              <group></group>
                   14639:             </roles>
                   14640: 
                   14641:             <dom></dom>         for scope type = domains
                   14642: 
                   14643:             <users>             for scope type = users
                   14644:              <user>
                   14645:               <uname></uname>
                   14646:               <udom></udom>
                   14647:              </user>
                   14648:             </users>
                   14649:            </scope> 
                   14650:               
                   14651:  Access data is also aggregated for each file in an additional key=value pair:
                   14652:  key -> path to file/file_name\0accesscontrol 
                   14653:  value -> reference to hash
                   14654:           hash contains key = value pairs
                   14655:           where key = uniqueID:scope_end_start
                   14656:                 value = UNIX time record was last updated
                   14657: 
                   14658:           Used to improve speed of look-ups of access controls for each file.  
                   14659:  
                   14660:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14661: 
1.1198    raeburn  14662: =item *
                   14663: 
1.749     raeburn  14664: modify_access_controls():
                   14665: 
                   14666: Modifies access controls for a portfolio file
                   14667: Args
                   14668: 1. file name
                   14669: 2. reference to hash of required changes,
                   14670: 3. domain
                   14671: 4. username
                   14672:   where domain,username are the domain of the portfolio owner 
                   14673:   (either a user or a course) 
                   14674: 
                   14675: Returns:
                   14676: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14677: 2. result of deletions ('ok' or 'error', with error message).
                   14678: 3. reference to hash of any new or updated access controls.
                   14679: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14680:    key = integer (inbound ID)
1.1198    raeburn  14681:    value = uniqueID
                   14682: 
                   14683: =item *
                   14684: 
                   14685: get_timebased_id():
                   14686: 
                   14687: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14688: course via the Course Editor (e.g., folders, composite pages, 
                   14689: group bulletin boards).
                   14690: 
                   14691: Args: (first three required; six others optional)
                   14692: 
                   14693: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14694:    docssequence, or name of group
                   14695: 
                   14696: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14697:    e.g., num, boardids
                   14698: 
                   14699: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14700:    file will be named nohist_namespace.db
                   14701: 
                   14702: 4. cdom: domain of course; default is current course domain from %env
                   14703: 
                   14704: 5. cnum: course number; default is current course number from %env
                   14705: 
                   14706: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14707:    unix timestamp to form the suffix, if the plain timestamp is already
                   14708:    in use.  Default is to not do this, but simply increment the unix 
                   14709:    timestamp by 1 until a unique key is obtained.
                   14710: 
                   14711: 7. who: holder of locking key; defaults to user:domain for user.
                   14712: 
                   14713: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14714:    retrying); default is 3.
                   14715: 
                   14716: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14717: 
                   14718: Returns:
                   14719: 
                   14720: 1. suffix obtained (numeric)
                   14721: 
                   14722: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14723: 
                   14724: 3. error: contains (localized) error message if an error occurred.
                   14725: 
1.747     albertel 14726: 
1.608     albertel 14727: =back
                   14728: 
1.243     albertel 14729: =head2 HTTP Helper Routines
                   14730: 
                   14731: =over 4
                   14732: 
1.191     harris41 14733: =item *
                   14734: 
                   14735: escape() : unpack non-word characters into CGI-compatible hex codes
                   14736: 
                   14737: =item *
                   14738: 
                   14739: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14740: 
1.243     albertel 14741: =back
                   14742: 
                   14743: =head1 PRIVATE SUBROUTINES
                   14744: 
                   14745: =head2 Underlying communication routines (Shouldn't call)
                   14746: 
                   14747: =over 4
                   14748: 
                   14749: =item *
                   14750: 
                   14751: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14752: 
                   14753: =item *
                   14754: 
                   14755: reply() : uses subreply to send a message to remote machine, logs all failures
                   14756: 
                   14757: =item *
                   14758: 
                   14759: critical() : passes a critical message to another server; if cannot
                   14760: get through then place message in connection buffer directory and
                   14761: returns con_delayed, if incapable of saving message, returns
                   14762: con_failed
                   14763: 
                   14764: =item *
                   14765: 
                   14766: reconlonc() : tries to reconnect lonc client processes.
                   14767: 
                   14768: =back
                   14769: 
                   14770: =head2 Resource Access Logging
                   14771: 
                   14772: =over 4
                   14773: 
                   14774: =item *
                   14775: 
                   14776: flushcourselogs() : flush (save) buffer logs and access logs
                   14777: 
                   14778: =item *
                   14779: 
                   14780: courselog($what) : save message for course in hash
                   14781: 
                   14782: =item *
                   14783: 
                   14784: courseacclog($what) : save message for course using &courselog().  Perform
                   14785: special processing for specific resource types (problems, exams, quizzes, etc).
                   14786: 
1.191     harris41 14787: =item *
                   14788: 
                   14789: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14790: as a PerlChildExitHandler
1.243     albertel 14791: 
                   14792: =back
                   14793: 
                   14794: =head2 Other
                   14795: 
                   14796: =over 4
                   14797: 
                   14798: =item *
                   14799: 
                   14800: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14801: 
                   14802: =back
                   14803: 
                   14804: =cut
1.877     foxr     14805: 

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