Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1184
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1184 ! raeburn 4: # $Id: lonnet.pm,v 1.1183 2012/08/14 15:45:34 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.871 albertel 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.539 albertel 95: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.550 foxr 108: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1184 ! raeburn 116: # ---------------------------------------------------------------- Role Logging
1.729 www 117: {
118: my $logid;
1.1184 ! raeburn 119: sub write_rolelog {
! 120: my ($context,$hash_name,$storehash,$delflag,$udom,$uname,$cdom,$cnum)=@_;
! 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=¤t_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 {
359: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 360: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 361: return $response;
362: }
363:
1.1 albertel 364: # -------------------------------------------------- Non-critical communication
365: sub subreply {
366: my ($cmd,$server)=@_;
1.838 albertel 367: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 368: #
369: # With loncnew process trimming, there's a timing hole between lonc server
370: # process exit and the master server picking up the listen on the AF_UNIX
371: # socket. In that time interval, a lock file will exist:
372:
373: my $lockfile=$peerfile.".lock";
374: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
375: sleep(1);
376: }
377: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 378: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 379: #
1.550 foxr 380: # We'll give the connection a few tries before abandoning it. If
381: # connection is not possible, we'll con_lost back to the client.
382: #
383: my $client;
384: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
385: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
386: Type => SOCK_STREAM,
387: Timeout => 10);
1.869 albertel 388: if ($client) {
1.550 foxr 389: last; # Connected!
1.850 albertel 390: } else {
1.853 albertel 391: &create_connection(&hostname($server),$server);
1.550 foxr 392: }
1.850 albertel 393: sleep(1); # Try again later if failed connection.
1.550 foxr 394: }
395: my $answer;
396: if ($client) {
1.704 albertel 397: print $client "sethost:$server:$cmd\n";
1.550 foxr 398: $answer=<$client>;
399: if (!$answer) { $answer="con_lost"; }
400: chomp($answer);
401: } else {
402: $answer = 'con_lost'; # Failed connection.
403: }
1.1 albertel 404: return $answer;
405: }
406:
407: sub reply {
408: my ($cmd,$server)=@_;
1.838 albertel 409: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 410: my $answer=subreply($cmd,$server);
1.65 www 411: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 412: &logthis("<font color=\"blue\">WARNING:".
1.12 www 413: " $cmd to $server returned $answer</font>");
414: }
1.1 albertel 415: return $answer;
416: }
417:
418: # ----------------------------------------------------------- Send USR1 to lonc
419:
420: sub reconlonc {
1.891 albertel 421: my ($lonid) = @_;
422: my $hostname = &hostname($lonid);
423: if ($lonid) {
424: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
425: if ($hostname && -e $peerfile) {
426: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
427: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
428: Type => SOCK_STREAM,
429: Timeout => 10);
430: if ($client) {
431: print $client ("reset_retries\n");
432: my $answer=<$client>;
433: #reset just this one.
434: }
435: }
436: return;
437: }
438:
1.836 www 439: &logthis("Trying to reconnect lonc");
1.1 albertel 440: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 441: if (open(my $fh,"<$loncfile")) {
1.1 albertel 442: my $loncpid=<$fh>;
443: chomp($loncpid);
444: if (kill 0 => $loncpid) {
445: &logthis("lonc at pid $loncpid responding, sending USR1");
446: kill USR1 => $loncpid;
447: sleep 1;
1.836 www 448: } else {
1.12 www 449: &logthis(
1.672 albertel 450: "<font color=\"blue\">WARNING:".
1.12 www 451: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 452: }
453: } else {
1.836 www 454: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 455: }
456: }
457:
458: # ------------------------------------------------------ Critical communication
1.12 www 459:
1.1 albertel 460: sub critical {
461: my ($cmd,$server)=@_;
1.838 albertel 462: unless (&hostname($server)) {
1.672 albertel 463: &logthis("<font color=\"blue\">WARNING:".
1.89 www 464: " Critical message to unknown server ($server)</font>");
465: return 'no_such_host';
466: }
1.1 albertel 467: my $answer=reply($cmd,$server);
468: if ($answer eq 'con_lost') {
469: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 470: my $answer=reply($cmd,$server);
1.1 albertel 471: if ($answer eq 'con_lost') {
472: my $now=time;
473: my $middlename=$cmd;
1.5 www 474: $middlename=substr($middlename,0,16);
1.1 albertel 475: $middlename=~s/\W//g;
476: my $dfilename=
1.305 www 477: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
478: $dumpcount++;
1.1 albertel 479: {
1.448 albertel 480: my $dfh;
481: if (open($dfh,">$dfilename")) {
482: print $dfh "$cmd\n";
483: close($dfh);
484: }
1.1 albertel 485: }
486: sleep 2;
487: my $wcmd='';
488: {
1.448 albertel 489: my $dfh;
490: if (open($dfh,"<$dfilename")) {
491: $wcmd=<$dfh>;
492: close($dfh);
493: }
1.1 albertel 494: }
495: chomp($wcmd);
1.7 www 496: if ($wcmd eq $cmd) {
1.672 albertel 497: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 498: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 499: &logperm("D:$server:$cmd");
500: return 'con_delayed';
501: } else {
1.672 albertel 502: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 503: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 504: &logperm("F:$server:$cmd");
505: return 'con_failed';
506: }
507: }
508: }
509: return $answer;
1.405 albertel 510: }
511:
1.755 albertel 512: # ------------------------------------------- check if return value is an error
513:
514: sub error {
515: my ($result) = @_;
1.756 albertel 516: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 517: if ($2 == 2) { return undef; }
518: return $1;
519: }
520: return undef;
521: }
522:
1.783 albertel 523: sub convert_and_load_session_env {
524: my ($lonidsdir,$handle)=@_;
525: my @profile;
526: {
1.917 albertel 527: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
528: if (!$opened) {
1.915 albertel 529: return 0;
530: }
1.783 albertel 531: flock($idf,LOCK_SH);
532: @profile=<$idf>;
533: close($idf);
534: }
535: my %temp_env;
536: foreach my $line (@profile) {
1.786 albertel 537: if ($line !~ m/=/) {
538: return 0;
539: }
1.783 albertel 540: chomp($line);
541: my ($envname,$envvalue)=split(/=/,$line,2);
542: $temp_env{&unescape($envname)} = &unescape($envvalue);
543: }
544: unlink("$lonidsdir/$handle.id");
545: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
546: 0640)) {
547: %disk_env = %temp_env;
548: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
549: untie(%disk_env);
550: }
1.786 albertel 551: return 1;
1.783 albertel 552: }
553:
1.374 www 554: # ------------------------------------------- Transfer profile into environment
1.780 albertel 555: my $env_loaded;
556: sub transfer_profile_to_env {
1.788 albertel 557: my ($lonidsdir,$handle,$force_transfer) = @_;
558: if (!$force_transfer && $env_loaded) { return; }
1.374 www 559:
1.720 albertel 560: if (!defined($lonidsdir)) {
561: $lonidsdir = $perlvar{'lonIDsDir'};
562: }
563: if (!defined($handle)) {
564: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
565: }
566:
1.786 albertel 567: my $convert;
568: {
1.917 albertel 569: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
570: if (!$opened) {
1.915 albertel 571: return;
572: }
1.786 albertel 573: flock($idf,LOCK_SH);
574: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
575: &GDBM_READER(),0640)) {
576: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
577: untie(%disk_env);
578: } else {
579: $convert = 1;
580: }
581: }
582: if ($convert) {
583: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
584: &logthis("Failed to load session, or convert session.");
585: }
1.374 www 586: }
1.783 albertel 587:
1.786 albertel 588: my %remove;
1.783 albertel 589: while ( my $envname = each(%env) ) {
1.433 matthew 590: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
591: if ($time < time-300) {
1.783 albertel 592: $remove{$key}++;
1.433 matthew 593: }
594: }
595: }
1.783 albertel 596:
1.619 albertel 597: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 598: $env_loaded=1;
1.783 albertel 599: foreach my $expired_key (keys(%remove)) {
1.433 matthew 600: &delenv($expired_key);
1.374 www 601: }
1.1 albertel 602: }
603:
1.916 albertel 604: # ---------------------------------------------------- Check for valid session
605: sub check_for_valid_session {
1.1155 raeburn 606: my ($r,$name) = @_;
1.916 albertel 607: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 608: if ($name eq '') {
609: $name = 'lonID';
610: }
611: my $lonid=$cookies{$name};
1.916 albertel 612: return undef if (!$lonid);
613:
614: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 615: my $lonidsdir;
616: if ($name eq 'lonDAV') {
617: $lonidsdir=$r->dir_config('lonDAVsessDir');
618: } else {
619: $lonidsdir=$r->dir_config('lonIDsDir');
620: }
1.916 albertel 621: return undef if (!-e "$lonidsdir/$handle.id");
622:
1.917 albertel 623: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
624: return undef if (!$opened);
1.916 albertel 625:
626: flock($idf,LOCK_SH);
627: my %disk_env;
628: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
629: &GDBM_READER(),0640)) {
630: return undef;
631: }
632:
633: if (!defined($disk_env{'user.name'})
634: || !defined($disk_env{'user.domain'})) {
635: return undef;
636: }
637: return $handle;
638: }
639:
1.830 albertel 640: sub timed_flock {
641: my ($file,$lock_type) = @_;
642: my $failed=0;
643: eval {
644: local $SIG{__DIE__}='DEFAULT';
645: local $SIG{ALRM}=sub {
646: $failed=1;
647: die("failed lock");
648: };
649: alarm(13);
650: flock($file,$lock_type);
651: alarm(0);
652: };
653: if ($failed) {
654: return undef;
655: } else {
656: return 1;
657: }
658: }
659:
1.5 www 660: # ---------------------------------------------------------- Append Environment
661:
662: sub appenv {
1.949 raeburn 663: my ($newenv,$roles) = @_;
664: if (ref($newenv) eq 'HASH') {
665: foreach my $key (keys(%{$newenv})) {
666: my $refused = 0;
667: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
668: $refused = 1;
669: if (ref($roles) eq 'ARRAY') {
670: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
671: if (grep(/^\Q$role\E$/,@{$roles})) {
672: $refused = 0;
673: }
674: }
675: }
676: if ($refused) {
677: &logthis("<font color=\"blue\">WARNING: ".
678: "Attempt to modify environment ".$key." to ".$newenv->{$key}
679: .'</font>');
680: delete($newenv->{$key});
681: } else {
682: $env{$key}=$newenv->{$key};
683: }
684: }
685: my $opened = open(my $env_file,'+<',$env{'user.environment'});
686: if ($opened
687: && &timed_flock($env_file,LOCK_EX)
688: &&
689: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
690: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
691: while (my ($key,$value) = each(%{$newenv})) {
692: $disk_env{$key} = $value;
693: }
694: untie(%disk_env);
1.35 www 695: }
1.191 harris41 696: }
1.56 www 697: return 'ok';
698: }
699: # ----------------------------------------------------- Delete from Environment
700:
701: sub delenv {
1.1104 raeburn 702: my ($delthis,$regexp,$roles) = @_;
703: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
704: my $refused = 1;
705: if (ref($roles) eq 'ARRAY') {
706: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
707: if (grep(/^\Q$role\E$/,@{$roles})) {
708: $refused = 0;
709: }
710: }
711: if ($refused) {
712: &logthis("<font color=\"blue\">WARNING: ".
713: "Attempt to delete from environment ".$delthis);
714: return 'error';
715: }
1.56 www 716: }
1.917 albertel 717: my $opened = open(my $env_file,'+<',$env{'user.environment'});
718: if ($opened
1.915 albertel 719: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 720: &&
721: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
722: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 723: foreach my $key (keys(%disk_env)) {
1.987 raeburn 724: if ($regexp) {
725: if ($key=~/^$delthis/) {
726: delete($env{$key});
727: delete($disk_env{$key});
728: }
729: } else {
730: if ($key=~/^\Q$delthis\E/) {
731: delete($env{$key});
732: delete($disk_env{$key});
733: }
734: }
1.448 albertel 735: }
1.783 albertel 736: untie(%disk_env);
1.5 www 737: }
738: return 'ok';
1.369 albertel 739: }
740:
1.790 albertel 741: sub get_env_multiple {
742: my ($name) = @_;
743: my @values;
744: if (defined($env{$name})) {
745: # exists is it an array
746: if (ref($env{$name})) {
747: @values=@{ $env{$name} };
748: } else {
749: $values[0]=$env{$name};
750: }
751: }
752: return(@values);
753: }
754:
1.958 www 755: # ------------------------------------------------------------------- Locking
756:
757: sub set_lock {
758: my ($text)=@_;
759: $locknum++;
760: my $id=$$.'-'.$locknum;
761: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
762: 'session.lock.'.$id => $text});
763: return $id;
764: }
765:
766: sub get_locks {
767: my $num=0;
768: my %texts=();
769: foreach my $lock (split(/\,/,$env{'session.locks'})) {
770: if ($lock=~/\w/) {
771: $num++;
772: $texts{$lock}=$env{'session.lock.'.$lock};
773: }
774: }
775: return ($num,%texts);
776: }
777:
778: sub remove_lock {
779: my ($id)=@_;
780: my $newlocks='';
781: foreach my $lock (split(/\,/,$env{'session.locks'})) {
782: if (($lock=~/\w/) && ($lock ne $id)) {
783: $newlocks.=','.$lock;
784: }
785: }
786: &appenv({'session.locks' => $newlocks});
787: &delenv('session.lock.'.$id);
788: }
789:
790: sub remove_all_locks {
791: my $activelocks=$env{'session.locks'};
792: foreach my $lock (split(/\,/,$env{'session.locks'})) {
793: if ($lock=~/\w/) {
794: &remove_lock($lock);
795: }
796: }
797: }
798:
799:
1.369 albertel 800: # ------------------------------------------ Find out current server userload
801: sub userload {
802: my $numusers=0;
803: {
804: opendir(LONIDS,$perlvar{'lonIDsDir'});
805: my $filename;
806: my $curtime=time;
807: while ($filename=readdir(LONIDS)) {
1.925 albertel 808: next if ($filename eq '.' || $filename eq '..');
809: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 810: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 811: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 812: }
813: closedir(LONIDS);
814: }
815: my $userloadpercent=0;
816: my $maxuserload=$perlvar{'lonUserLoadLim'};
817: if ($maxuserload) {
1.371 albertel 818: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 819: }
1.372 albertel 820: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 821: return $userloadpercent;
1.283 www 822: }
823:
1.1 albertel 824: # ------------------------------ Find server with least workload from spare.tab
1.11 www 825:
1.1 albertel 826: sub spareserver {
1.1083 raeburn 827: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 828: my $spare_server;
1.370 albertel 829: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 830: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
831: : $userloadpercent;
1.1083 raeburn 832: my ($uint_dom,$remotesessions);
833: if (($udom ne '') && (&domain($udom) ne '')) {
834: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
835: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
836: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
837: $remotesessions = $udomdefaults{'remotesessions'};
838: }
1.1123 raeburn 839: my $spareshash = &this_host_spares($udom);
840: if (ref($spareshash) eq 'HASH') {
841: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
842: foreach my $try_server (@{ $spareshash->{'primary'} }) {
843: if ($uint_dom) {
844: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
845: $try_server));
846: }
847: ($spare_server, $lowest_load) =
848: &compare_server_load($try_server, $spare_server, $lowest_load);
849: }
1.1083 raeburn 850: }
1.784 albertel 851:
1.1123 raeburn 852: my $found_server = ($spare_server ne '' && $lowest_load < 100);
853:
854: if (!$found_server) {
855: if (ref($spareshash->{'default'}) eq 'ARRAY') {
856: foreach my $try_server (@{ $spareshash->{'default'} }) {
857: if ($uint_dom) {
858: next unless (&spare_can_host($udom,$uint_dom,
859: $remotesessions,$try_server));
860: }
861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
864: }
865: }
1.784 albertel 866: }
867:
868: if (!$want_server_name) {
1.968 raeburn 869: my $protocol = 'http';
870: if ($protocol{$spare_server} eq 'https') {
871: $protocol = $protocol{$spare_server};
872: }
1.1001 raeburn 873: if (defined($spare_server)) {
874: my $hostname = &hostname($spare_server);
1.1083 raeburn 875: if (defined($hostname)) {
1.1001 raeburn 876: $spare_server = $protocol.'://'.$hostname;
877: }
878: }
1.784 albertel 879: }
880: return $spare_server;
881: }
882:
883: sub compare_server_load {
884: my ($try_server, $spare_server, $lowest_load) = @_;
885:
886: my $loadans = &reply('load', $try_server);
887: my $userloadans = &reply('userload',$try_server);
888:
889: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 890: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 891: }
892:
893: my $load;
894: if ($loadans =~ /\d/) {
895: if ($userloadans =~ /\d/) {
896: #both are numbers, pick the bigger one
897: $load = ($loadans > $userloadans) ? $loadans
898: : $userloadans;
1.411 albertel 899: } else {
1.784 albertel 900: $load = $loadans;
1.411 albertel 901: }
1.784 albertel 902: } else {
903: $load = $userloadans;
904: }
905:
906: if (($load =~ /\d/) && ($load < $lowest_load)) {
907: $spare_server = $try_server;
908: $lowest_load = $load;
1.370 albertel 909: }
1.784 albertel 910: return ($spare_server,$lowest_load);
1.202 matthew 911: }
1.914 albertel 912:
913: # --------------------------- ask offload servers if user already has a session
914: sub find_existing_session {
915: my ($udom,$uname) = @_;
1.1123 raeburn 916: my $spareshash = &this_host_spares($udom);
917: if (ref($spareshash) eq 'HASH') {
918: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
919: foreach my $try_server (@{ $spareshash->{'primary'} }) {
920: return $try_server if (&has_user_session($try_server, $udom, $uname));
921: }
922: }
923: if (ref($spareshash->{'default'}) eq 'ARRAY') {
924: foreach my $try_server (@{ $spareshash->{'default'} }) {
925: return $try_server if (&has_user_session($try_server, $udom, $uname));
926: }
927: }
1.914 albertel 928: }
929: return;
930: }
931:
932: # -------------------------------- ask if server already has a session for user
933: sub has_user_session {
934: my ($lonid,$udom,$uname) = @_;
935: my $result = &reply(join(':','userhassession',
936: map {&escape($_)} ($udom,$uname)),$lonid);
937: return 1 if ($result eq 'ok');
938:
939: return 0;
940: }
941:
1.1076 raeburn 942: # --------- determine least loaded server in a user's domain which allows login
943:
944: sub choose_server {
1.1115 raeburn 945: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 946: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 947: my %servers = &get_servers($udom);
1.1076 raeburn 948: my $lowest_load = 30000;
1.1151 raeburn 949: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 950: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 951: my $loginvia;
952: if ($checkloginvia) {
953: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 954: if ($loginvia) {
955: my ($server,$path) = split(/:/,$loginvia);
956: ($login_host, $lowest_load) =
957: &compare_server_load($server, $login_host, $lowest_load);
958: if ($login_host eq $server) {
959: $portal_path = $path;
1.1151 raeburn 960: $isredirect = 1;
1.1116 raeburn 961: }
962: } else {
963: ($login_host, $lowest_load) =
964: &compare_server_load($lonhost, $login_host, $lowest_load);
965: if ($login_host eq $lonhost) {
966: $portal_path = '';
1.1151 raeburn 967: $isredirect = '';
1.1116 raeburn 968: }
969: }
970: } else {
1.1076 raeburn 971: ($login_host, $lowest_load) =
1.1116 raeburn 972: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 973: }
974: }
975: if ($login_host ne '') {
1.1116 raeburn 976: $hostname = &hostname($login_host);
1.1076 raeburn 977: }
1.1151 raeburn 978: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 979: }
980:
1.202 matthew 981: # --------------------------------------------- Try to change a user's password
982:
983: sub changepass {
1.799 raeburn 984: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 985: $currentpass = &escape($currentpass);
986: $newpass = &escape($newpass);
1.1030 raeburn 987: my $lonhost = $perlvar{'lonHostID'};
988: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 989: $server);
990: if (! $answer) {
991: &logthis("No reply on password change request to $server ".
992: "by $uname in domain $udom.");
993: } elsif ($answer =~ "^ok") {
994: &logthis("$uname in $udom successfully changed their password ".
995: "on $server.");
996: } elsif ($answer =~ "^pwchange_failure") {
997: &logthis("$uname in $udom was unable to change their password ".
998: "on $server. The action was blocked by either lcpasswd ".
999: "or pwchange");
1000: } elsif ($answer =~ "^non_authorized") {
1001: &logthis("$uname in $udom did not get their password correct when ".
1002: "attempting to change it on $server.");
1003: } elsif ($answer =~ "^auth_mode_error") {
1004: &logthis("$uname in $udom attempted to change their password despite ".
1005: "not being locally or internally authenticated on $server.");
1006: } elsif ($answer =~ "^unknown_user") {
1007: &logthis("$uname in $udom attempted to change their password ".
1008: "on $server but were unable to because $server is not ".
1009: "their home server.");
1010: } elsif ($answer =~ "^refused") {
1011: &logthis("$server refused to change $uname in $udom password because ".
1012: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1013: } elsif ($answer =~ "invalid_client") {
1014: &logthis("$server refused to change $uname in $udom password because ".
1015: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1016: }
1017: return $answer;
1.1 albertel 1018: }
1019:
1.169 harris41 1020: # ----------------------- Try to determine user's current authentication scheme
1021:
1022: sub queryauthenticate {
1023: my ($uname,$udom)=@_;
1.456 albertel 1024: my $uhome=&homeserver($uname,$udom);
1025: if (!$uhome) {
1026: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1027: return 'no_host';
1028: }
1029: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1030: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1031: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1032: }
1.456 albertel 1033: return $answer;
1.169 harris41 1034: }
1035:
1.1 albertel 1036: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1037:
1.1 albertel 1038: sub authenticate {
1.1073 raeburn 1039: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1040: $upass=&escape($upass);
1041: $uname= &LONCAPA::clean_username($uname);
1.836 www 1042: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1043: my $newhome;
1.836 www 1044: if ((!$uhome) || ($uhome eq 'no_host')) {
1045: # Maybe the machine was offline and only re-appeared again recently?
1046: &reconlonc();
1047: # One more
1.952 raeburn 1048: $uhome=&homeserver($uname,$udom,1);
1049: if (($uhome eq 'no_host') && $checkdefauth) {
1050: if (defined(&domain($udom,'primary'))) {
1051: $newhome=&domain($udom,'primary');
1052: }
1053: if ($newhome ne '') {
1054: $uhome = $newhome;
1055: }
1056: }
1.836 www 1057: if ((!$uhome) || ($uhome eq 'no_host')) {
1058: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1059: return 'no_host';
1060: }
1.1 albertel 1061: }
1.1073 raeburn 1062: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1063: if ($answer eq 'authorized') {
1.952 raeburn 1064: if ($newhome) {
1065: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1066: return 'no_account_on_host';
1067: } else {
1068: &logthis("User $uname at $udom authorized by $uhome");
1069: return $uhome;
1070: }
1.471 albertel 1071: }
1072: if ($answer eq 'non_authorized') {
1073: &logthis("User $uname at $udom rejected by $uhome");
1074: return 'no_host';
1.9 www 1075: }
1.471 albertel 1076: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1077: return 'no_host';
1078: }
1079:
1.1073 raeburn 1080: sub can_host_session {
1.1074 raeburn 1081: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1082: my $canhost = 1;
1.1074 raeburn 1083: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1084: if (ref($remotesessions) eq 'HASH') {
1085: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1086: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1087: $canhost = 0;
1088: } else {
1089: $canhost = 1;
1090: }
1091: }
1092: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1093: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1094: $canhost = 1;
1095: } else {
1096: $canhost = 0;
1097: }
1098: }
1099: if ($canhost) {
1100: if ($remotesessions->{'version'} ne '') {
1101: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1102: if ($reqmajor ne '' && $reqminor ne '') {
1103: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1104: my $major = $1;
1105: my $minor = $2;
1106: if (($major < $reqmajor ) ||
1107: (($major == $reqmajor) && ($minor < $reqminor))) {
1108: $canhost = 0;
1109: }
1110: } else {
1111: $canhost = 0;
1112: }
1113: }
1114: }
1115: }
1116: }
1117: if ($canhost) {
1118: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1119: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1120: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1121: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1122: if (($uint_dom ne '') &&
1123: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1124: $canhost = 0;
1125: } else {
1126: $canhost = 1;
1127: }
1128: }
1129: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1130: if (($uint_dom ne '') &&
1131: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1132: $canhost = 1;
1133: } else {
1134: $canhost = 0;
1135: }
1136: }
1137: }
1138: }
1139: return $canhost;
1140: }
1141:
1.1083 raeburn 1142: sub spare_can_host {
1143: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1144: my $canhost=1;
1145: my @intdoms;
1146: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1147: if (ref($internet_names) eq 'ARRAY') {
1148: @intdoms = @{$internet_names};
1149: }
1150: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1151: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1152: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1153: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1154: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1155: $canhost = &can_host_session($udom,$try_server,$remoterev,
1156: $remotesessions,
1157: $defdomdefaults{'hostedsessions'});
1158: }
1159: return $canhost;
1160: }
1161:
1.1123 raeburn 1162: sub this_host_spares {
1163: my ($dom) = @_;
1.1126 raeburn 1164: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1165: my @hosts = ¤t_machine_ids();
1166: foreach my $lonhost (@hosts) {
1167: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1168: $dom_in_use = $dom;
1169: $lonhost_in_use = $lonhost;
1.1123 raeburn 1170: last;
1171: }
1172: }
1.1126 raeburn 1173: if ($dom_in_use ne '') {
1174: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1175: }
1176: if (ref($result) ne 'HASH') {
1177: $lonhost_in_use = $perlvar{'lonHostID'};
1178: $dom_in_use = &host_domain($lonhost_in_use);
1179: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1180: if (ref($result) ne 'HASH') {
1181: $result = \%spareid;
1182: }
1183: }
1184: return $result;
1185: }
1186:
1187: sub spares_for_offload {
1188: my ($dom_in_use,$lonhost_in_use) = @_;
1189: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1190: if (defined($cached)) {
1191: return $result;
1192: } else {
1.1126 raeburn 1193: my $cachetime = 60*60*24;
1194: my %domconfig =
1195: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1196: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1197: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1198: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1199: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1200: }
1201: }
1202: }
1203: }
1.1126 raeburn 1204: return;
1.1123 raeburn 1205: }
1206:
1.1129 raeburn 1207: sub get_lonbalancer_config {
1208: my ($servers) = @_;
1209: my ($currbalancer,$currtargets);
1210: if (ref($servers) eq 'HASH') {
1211: foreach my $server (keys(%{$servers})) {
1212: my %what = (
1213: spareid => 1,
1214: perlvar => 1,
1215: );
1216: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1217: if ($result eq 'ok') {
1218: if (ref($returnhash) eq 'HASH') {
1219: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1220: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1221: $currbalancer = $server;
1222: $currtargets = {};
1223: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1224: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1225: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1226: }
1227: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1228: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1229: }
1230: }
1231: last;
1232: }
1233: }
1234: }
1235: }
1236: }
1237: }
1238: return ($currbalancer,$currtargets);
1239: }
1240:
1241: sub check_loadbalancing {
1242: my ($uname,$udom) = @_;
1243: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1244: $offloadto,$otherserver);
1245: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1246: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1247: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1248: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1249: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1250: my $serverhomedom = &host_domain($lonhost);
1251:
1252: my $cachetime = 60*60*24;
1253:
1254: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1255: $dom_in_use = $udom;
1256: $homeintdom = 1;
1257: } else {
1258: $dom_in_use = $serverhomedom;
1259: }
1260: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1261: unless (defined($cached)) {
1262: my %domconfig =
1263: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1264: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1265: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1266: }
1267: }
1268: if (ref($result) eq 'HASH') {
1269: my $currbalancer = $result->{'lonhost'};
1270: my $currtargets = $result->{'targets'};
1271: my $currrules = $result->{'rules'};
1272: if ($currbalancer ne '') {
1273: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1274: $is_balancer = 1;
1275: }
1276: }
1277: if ($is_balancer) {
1278: if (ref($currrules) eq 'HASH') {
1279: if ($homeintdom) {
1280: if ($uname ne '') {
1281: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1282: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1283: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1284: $rule_in_effect = $currrules->{'_LC_author'};
1285: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1286: $rule_in_effect = $currrules->{'_LC_adv'}
1287: }
1288: }
1289: if ($rule_in_effect eq '') {
1290: my %userenv = &userenvironment($udom,$uname,'inststatus');
1291: if ($userenv{'inststatus'} ne '') {
1292: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1293: my ($othertitle,$usertypes,$types) =
1294: &Apache::loncommon::sorted_inst_types($udom);
1295: if (ref($types) eq 'ARRAY') {
1296: foreach my $type (@{$types}) {
1297: if (grep(/^\Q$type\E$/,@statuses)) {
1298: if (exists($currrules->{$type})) {
1299: $rule_in_effect = $currrules->{$type};
1300: }
1301: }
1302: }
1303: }
1304: } else {
1305: if (exists($currrules->{'default'})) {
1306: $rule_in_effect = $currrules->{'default'};
1307: }
1308: }
1309: }
1310: } else {
1311: if (exists($currrules->{'default'})) {
1312: $rule_in_effect = $currrules->{'default'};
1313: }
1314: }
1315: } else {
1316: if ($currrules->{'_LC_external'} ne '') {
1317: $rule_in_effect = $currrules->{'_LC_external'};
1318: }
1319: }
1320: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1321: $uname,$udom);
1322: }
1323: }
1324: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1325: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1326: unless (defined($cached)) {
1327: my %domconfig =
1328: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1329: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1330: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1331: }
1332: }
1333: if (ref($result) eq 'HASH') {
1334: my $currbalancer = $result->{'lonhost'};
1335: my $currtargets = $result->{'targets'};
1336: my $currrules = $result->{'rules'};
1337:
1338: if ($currbalancer eq $lonhost) {
1339: $is_balancer = 1;
1340: if (ref($currrules) eq 'HASH') {
1341: if ($currrules->{'_LC_internetdom'} ne '') {
1342: $rule_in_effect = $currrules->{'_LC_internetdom'};
1343: }
1344: }
1345: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1346: $uname,$udom);
1347: }
1348: } else {
1349: if ($perlvar{'lonBalancer'} eq 'yes') {
1350: $is_balancer = 1;
1351: $offloadto = &this_host_spares($dom_in_use);
1352: }
1353: }
1354: } else {
1355: if ($perlvar{'lonBalancer'} eq 'yes') {
1356: $is_balancer = 1;
1357: $offloadto = &this_host_spares($dom_in_use);
1358: }
1359: }
1.1176 raeburn 1360: if ($is_balancer) {
1361: my $lowest_load = 30000;
1362: if (ref($offloadto) eq 'HASH') {
1363: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1364: foreach my $try_server (@{$offloadto->{'primary'}}) {
1365: ($otherserver,$lowest_load) =
1366: &compare_server_load($try_server,$otherserver,$lowest_load);
1367: }
1.1129 raeburn 1368: }
1.1176 raeburn 1369: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1370:
1.1176 raeburn 1371: if (!$found_server) {
1372: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1373: foreach my $try_server (@{$offloadto->{'default'}}) {
1374: ($otherserver,$lowest_load) =
1375: &compare_server_load($try_server,$otherserver,$lowest_load);
1376: }
1377: }
1378: }
1379: } elsif (ref($offloadto) eq 'ARRAY') {
1380: if (@{$offloadto} == 1) {
1381: $otherserver = $offloadto->[0];
1382: } elsif (@{$offloadto} > 1) {
1383: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1384: ($otherserver,$lowest_load) =
1385: &compare_server_load($try_server,$otherserver,$lowest_load);
1386: }
1387: }
1388: }
1.1176 raeburn 1389: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1390: $is_balancer = 0;
1391: if ($uname ne '' && $udom ne '') {
1392: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1393:
1394: &appenv({'user.loadbalexempt' => $lonhost,
1395: 'user.loadbalcheck.time' => time});
1396: }
1.1129 raeburn 1397: }
1398: }
1399: }
1400: return ($is_balancer,$otherserver);
1401: }
1402:
1403: sub get_loadbalancer_targets {
1404: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1405: my $offloadto;
1.1175 raeburn 1406: if ($rule_in_effect eq 'none') {
1407: return [$perlvar{'lonHostID'}];
1408: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1409: $offloadto = $currtargets;
1410: } else {
1411: if ($rule_in_effect eq 'homeserver') {
1412: my $homeserver = &homeserver($uname,$udom);
1413: if ($homeserver ne 'no_host') {
1414: $offloadto = [$homeserver];
1415: }
1416: } elsif ($rule_in_effect eq 'externalbalancer') {
1417: my %domconfig =
1418: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1419: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1420: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1421: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1422: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1423: }
1424: }
1425: } else {
1.1178 raeburn 1426: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1427: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1428: if (&hostname($remotebalancer) ne '') {
1429: $offloadto = [$remotebalancer];
1430: }
1431: }
1432: } elsif (&hostname($rule_in_effect) ne '') {
1433: $offloadto = [$rule_in_effect];
1434: }
1435: }
1436: return $offloadto;
1437: }
1438:
1.1127 raeburn 1439: sub internet_dom_servers {
1440: my ($dom) = @_;
1441: my (%uniqservers,%servers);
1442: my $primaryserver = &hostname(&domain($dom,'primary'));
1443: my @machinedoms = &machine_domains($primaryserver);
1444: foreach my $mdom (@machinedoms) {
1445: my %currservers = %servers;
1446: my %server = &get_servers($mdom);
1447: %servers = (%currservers,%server);
1448: }
1449: my %by_hostname;
1450: foreach my $id (keys(%servers)) {
1451: push(@{$by_hostname{$servers{$id}}},$id);
1452: }
1453: foreach my $hostname (sort(keys(%by_hostname))) {
1454: if (@{$by_hostname{$hostname}} > 1) {
1455: my $match = 0;
1456: foreach my $id (@{$by_hostname{$hostname}}) {
1457: if (&host_domain($id) eq $dom) {
1458: $uniqservers{$id} = $hostname;
1459: $match = 1;
1460: }
1461: }
1462: unless ($match) {
1463: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1464: }
1465: } else {
1466: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1467: }
1468: }
1469: return %uniqservers;
1470: }
1471:
1.1 albertel 1472: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1473:
1.599 albertel 1474: my %homecache;
1.1 albertel 1475: sub homeserver {
1.230 stredwic 1476: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1477: my $index="$uname:$udom";
1.426 albertel 1478:
1.599 albertel 1479: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1480:
1481: my %servers = &get_servers($udom,'library');
1482: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1483: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1484: exists($badServerCache{$tryserver}));
1.841 albertel 1485:
1486: my $answer=reply("home:$udom:$uname",$tryserver);
1487: if ($answer eq 'found') {
1488: delete($badServerCache{$tryserver});
1489: return $homecache{$index}=$tryserver;
1490: } elsif ($answer eq 'no_host') {
1491: $badServerCache{$tryserver}=1;
1492: }
1.1 albertel 1493: }
1494: return 'no_host';
1.70 www 1495: }
1496:
1497: # ------------------------------------- Find the usernames behind a list of IDs
1498:
1499: sub idget {
1500: my ($udom,@ids)=@_;
1501: my %returnhash=();
1502:
1.841 albertel 1503: my %servers = &get_servers($udom,'library');
1504: foreach my $tryserver (keys(%servers)) {
1505: my $idlist=join('&',@ids);
1506: $idlist=~tr/A-Z/a-z/;
1507: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1508: my @answer=();
1509: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1510: @answer=split(/\&/,$reply);
1511: } ;
1512: my $i;
1513: for ($i=0;$i<=$#ids;$i++) {
1514: if ($answer[$i]) {
1515: $returnhash{$ids[$i]}=$answer[$i];
1516: }
1517: }
1518: }
1.70 www 1519: return %returnhash;
1520: }
1521:
1522: # ------------------------------------- Find the IDs behind a list of usernames
1523:
1524: sub idrget {
1525: my ($udom,@unames)=@_;
1526: my %returnhash=();
1.800 albertel 1527: foreach my $uname (@unames) {
1528: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1529: }
1.70 www 1530: return %returnhash;
1531: }
1532:
1533: # ------------------------------- Store away a list of names and associated IDs
1534:
1535: sub idput {
1536: my ($udom,%ids)=@_;
1537: my %servers=();
1.800 albertel 1538: foreach my $uname (keys(%ids)) {
1539: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1540: my $uhom=&homeserver($uname,$udom);
1.70 www 1541: if ($uhom ne 'no_host') {
1.800 albertel 1542: my $id=&escape($ids{$uname});
1.70 www 1543: $id=~tr/A-Z/a-z/;
1.800 albertel 1544: my $esc_unam=&escape($uname);
1.70 www 1545: if ($servers{$uhom}) {
1.800 albertel 1546: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1547: } else {
1.800 albertel 1548: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1549: }
1550: }
1.191 harris41 1551: }
1.800 albertel 1552: foreach my $server (keys(%servers)) {
1553: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1554: }
1.344 www 1555: }
1556:
1.1023 raeburn 1557: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1558: sub dump_dom {
1.1165 droeschl 1559: my ($namespace, $udom, $regexp) = @_;
1560:
1561: $udom ||= $env{'user.domain'};
1562:
1563: return () unless $udom;
1564:
1565: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1566: }
1567:
1.1023 raeburn 1568: # ------------------------------------------ get items from domain db files
1.806 raeburn 1569:
1570: sub get_dom {
1.860 raeburn 1571: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1572: my $items='';
1573: foreach my $item (@$storearr) {
1574: $items.=&escape($item).'&';
1575: }
1576: $items=~s/\&$//;
1.860 raeburn 1577: if (!$udom) {
1578: $udom=$env{'user.domain'};
1579: if (defined(&domain($udom,'primary'))) {
1580: $uhome=&domain($udom,'primary');
1581: } else {
1.874 albertel 1582: undef($uhome);
1.860 raeburn 1583: }
1584: } else {
1585: if (!$uhome) {
1586: if (defined(&domain($udom,'primary'))) {
1587: $uhome=&domain($udom,'primary');
1588: }
1589: }
1590: }
1591: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1592: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1593: my %returnhash;
1.875 albertel 1594: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1595: return %returnhash;
1596: }
1.806 raeburn 1597: my @pairs=split(/\&/,$rep);
1598: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1599: return @pairs;
1600: }
1601: my $i=0;
1602: foreach my $item (@$storearr) {
1603: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1604: $i++;
1605: }
1606: return %returnhash;
1607: } else {
1.880 banghart 1608: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1609: }
1610: }
1611:
1612: # -------------------------------------------- put items in domain db files
1613:
1614: sub put_dom {
1.860 raeburn 1615: my ($namespace,$storehash,$udom,$uhome)=@_;
1616: if (!$udom) {
1617: $udom=$env{'user.domain'};
1618: if (defined(&domain($udom,'primary'))) {
1619: $uhome=&domain($udom,'primary');
1620: } else {
1.874 albertel 1621: undef($uhome);
1.860 raeburn 1622: }
1623: } else {
1624: if (!$uhome) {
1625: if (defined(&domain($udom,'primary'))) {
1626: $uhome=&domain($udom,'primary');
1627: }
1628: }
1629: }
1630: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1631: my $items='';
1632: foreach my $item (keys(%$storehash)) {
1633: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1634: }
1635: $items=~s/\&$//;
1636: return &reply("putdom:$udom:$namespace:$items",$uhome);
1637: } else {
1.860 raeburn 1638: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1639: }
1640: }
1641:
1.1023 raeburn 1642: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1643: sub newput_dom {
1.1023 raeburn 1644: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1645: my $result;
1646: if (!$udom) {
1647: $udom=$env{'user.domain'};
1648: }
1.1023 raeburn 1649: if ($udom) {
1650: my $uname = &get_domainconfiguser($udom);
1651: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1652: }
1653: return $result;
1654: }
1655:
1.1023 raeburn 1656: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1657: sub del_dom {
1.1023 raeburn 1658: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1659: if (ref($storearr) eq 'ARRAY') {
1660: if (!$udom) {
1661: $udom=$env{'user.domain'};
1662: }
1.1023 raeburn 1663: if ($udom) {
1664: my $uname = &get_domainconfiguser($udom);
1665: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1666: }
1667: }
1668: }
1669:
1.1023 raeburn 1670: # ----------------------------------construct domainconfig user for a domain
1671: sub get_domainconfiguser {
1672: my ($udom) = @_;
1673: return $udom.'-domainconfig';
1674: }
1675:
1.837 raeburn 1676: sub retrieve_inst_usertypes {
1677: my ($udom) = @_;
1678: my (%returnhash,@order);
1.989 raeburn 1679: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1680: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1681: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1682: %returnhash = %{$domdefs{'inststatustypes'}};
1683: @order = @{$domdefs{'inststatusorder'}};
1684: } else {
1685: if (defined(&domain($udom,'primary'))) {
1686: my $uhome=&domain($udom,'primary');
1687: my $rep=&reply("inst_usertypes:$udom",$uhome);
1688: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1689: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1690: return (\%returnhash,\@order);
1691: }
1692: my ($hashitems,$orderitems) = split(/:/,$rep);
1693: my @pairs=split(/\&/,$hashitems);
1694: foreach my $item (@pairs) {
1695: my ($key,$value)=split(/=/,$item,2);
1696: $key = &unescape($key);
1697: next if ($key =~ /^error: 2 /);
1698: $returnhash{$key}=&thaw_unescape($value);
1699: }
1700: my @esc_order = split(/\&/,$orderitems);
1701: foreach my $item (@esc_order) {
1702: push(@order,&unescape($item));
1703: }
1704: } else {
1705: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1706: }
1707: }
1708: return (\%returnhash,\@order);
1709: }
1710:
1.868 raeburn 1711: sub is_domainimage {
1712: my ($url) = @_;
1713: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1714: if (&domain($1) ne '') {
1715: return '1';
1716: }
1717: }
1718: return;
1719: }
1720:
1.899 raeburn 1721: sub inst_directory_query {
1722: my ($srch) = @_;
1723: my $udom = $srch->{'srchdomain'};
1724: my %results;
1725: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1726: my $outcome;
1.899 raeburn 1727: if ($homeserver ne '') {
1.904 albertel 1728: my $queryid=&reply("querysend:instdirsearch:".
1729: &escape($srch->{'srchby'}).':'.
1730: &escape($srch->{'srchterm'}).':'.
1731: &escape($srch->{'srchtype'}),$homeserver);
1732: my $host=&hostname($homeserver);
1733: if ($queryid !~/^\Q$host\E\_/) {
1734: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1735: return;
1736: }
1737: my $response = &get_query_reply($queryid);
1738: my $maxtries = 5;
1739: my $tries = 1;
1740: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1741: $response = &get_query_reply($queryid);
1742: $tries ++;
1743: }
1744:
1745: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1746: if ($response eq 'unavailable') {
1747: $outcome = $response;
1748: } else {
1749: $outcome = 'ok';
1750: my @matches = split(/\n/,$response);
1751: foreach my $match (@matches) {
1752: my ($key,$value) = split(/=/,$match);
1753: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1754: }
1.899 raeburn 1755: }
1756: }
1757: }
1.909 raeburn 1758: return ($outcome,%results);
1.899 raeburn 1759: }
1760:
1761: sub usersearch {
1762: my ($srch) = @_;
1763: my $dom = $srch->{'srchdomain'};
1764: my %results;
1765: my %libserv = &all_library();
1766: my $query = 'usersearch';
1767: foreach my $tryserver (keys(%libserv)) {
1768: if (&host_domain($tryserver) eq $dom) {
1769: my $host=&hostname($tryserver);
1770: my $queryid=
1.911 raeburn 1771: &reply("querysend:".&escape($query).':'.
1772: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1773: &escape($srch->{'srchtype'}).':'.
1774: &escape($srch->{'srchterm'}),$tryserver);
1775: if ($queryid !~/^\Q$host\E\_/) {
1776: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1777: next;
1.899 raeburn 1778: }
1779: my $reply = &get_query_reply($queryid);
1780: my $maxtries = 1;
1781: my $tries = 1;
1782: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1783: $reply = &get_query_reply($queryid);
1784: $tries ++;
1785: }
1786: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1787: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1788: } else {
1.911 raeburn 1789: my @matches;
1790: if ($reply =~ /\n/) {
1791: @matches = split(/\n/,$reply);
1792: } else {
1793: @matches = split(/\&/,$reply);
1794: }
1.899 raeburn 1795: foreach my $match (@matches) {
1796: my ($uname,$udom,%userhash);
1.911 raeburn 1797: foreach my $entry (split(/:/,$match)) {
1798: my ($key,$value) =
1799: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1800: $userhash{$key} = $value;
1801: if ($key eq 'username') {
1802: $uname = $value;
1803: } elsif ($key eq 'domain') {
1804: $udom = $value;
1.911 raeburn 1805: }
1.899 raeburn 1806: }
1807: $results{$uname.':'.$udom} = \%userhash;
1808: }
1809: }
1810: }
1811: }
1812: return %results;
1813: }
1814:
1.912 raeburn 1815: sub get_instuser {
1816: my ($udom,$uname,$id) = @_;
1817: my $homeserver = &domain($udom,'primary');
1818: my ($outcome,%results);
1819: if ($homeserver ne '') {
1820: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1821: &escape($id).':'.&escape($udom),$homeserver);
1822: my $host=&hostname($homeserver);
1823: if ($queryid !~/^\Q$host\E\_/) {
1824: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1825: return;
1826: }
1827: my $response = &get_query_reply($queryid);
1828: my $maxtries = 5;
1829: my $tries = 1;
1830: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1831: $response = &get_query_reply($queryid);
1832: $tries ++;
1833: }
1834: if (!&error($response) && $response ne 'refused') {
1835: if ($response eq 'unavailable') {
1836: $outcome = $response;
1837: } else {
1838: $outcome = 'ok';
1839: my @matches = split(/\n/,$response);
1840: foreach my $match (@matches) {
1841: my ($key,$value) = split(/=/,$match);
1842: $results{&unescape($key)} = &thaw_unescape($value);
1843: }
1844: }
1845: }
1846: }
1847: my %userinfo;
1848: if (ref($results{$uname}) eq 'HASH') {
1849: %userinfo = %{$results{$uname}};
1850: }
1851: return ($outcome,%userinfo);
1852: }
1853:
1854: sub inst_rulecheck {
1.923 raeburn 1855: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1856: my %returnhash;
1857: if ($udom ne '') {
1858: if (ref($rules) eq 'ARRAY') {
1859: @{$rules} = map {&escape($_);} (@{$rules});
1860: my $rulestr = join(':',@{$rules});
1861: my $homeserver=&domain($udom,'primary');
1862: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1863: my $response;
1864: if ($item eq 'username') {
1865: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1866: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1867: $homeserver));
1.923 raeburn 1868: } elsif ($item eq 'id') {
1869: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1870: ':'.&escape($id).':'.$rulestr,
1871: $homeserver));
1.945 raeburn 1872: } elsif ($item eq 'selfcreate') {
1873: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1874: &escape($udom).':'.&escape($uname).
1875: ':'.$rulestr,$homeserver));
1.923 raeburn 1876: }
1.912 raeburn 1877: if ($response ne 'refused') {
1878: my @pairs=split(/\&/,$response);
1879: foreach my $item (@pairs) {
1880: my ($key,$value)=split(/=/,$item,2);
1881: $key = &unescape($key);
1882: next if ($key =~ /^error: 2 /);
1883: $returnhash{$key}=&thaw_unescape($value);
1884: }
1885: }
1886: }
1887: }
1888: }
1889: return %returnhash;
1890: }
1891:
1892: sub inst_userrules {
1.923 raeburn 1893: my ($udom,$check) = @_;
1.912 raeburn 1894: my (%ruleshash,@ruleorder);
1895: if ($udom ne '') {
1896: my $homeserver=&domain($udom,'primary');
1897: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1898: my $response;
1899: if ($check eq 'id') {
1900: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1901: $homeserver);
1.943 raeburn 1902: } elsif ($check eq 'email') {
1903: $response=&reply('instemailrules:'.&escape($udom),
1904: $homeserver);
1.923 raeburn 1905: } else {
1906: $response=&reply('instuserrules:'.&escape($udom),
1907: $homeserver);
1908: }
1.912 raeburn 1909: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1910: ($response ne 'unknown_cmd') &&
1.912 raeburn 1911: ($response ne 'no_such_host')) {
1912: my ($hashitems,$orderitems) = split(/:/,$response);
1913: my @pairs=split(/\&/,$hashitems);
1914: foreach my $item (@pairs) {
1915: my ($key,$value)=split(/=/,$item,2);
1916: $key = &unescape($key);
1917: next if ($key =~ /^error: 2 /);
1918: $ruleshash{$key}=&thaw_unescape($value);
1919: }
1920: my @esc_order = split(/\&/,$orderitems);
1921: foreach my $item (@esc_order) {
1922: push(@ruleorder,&unescape($item));
1923: }
1924: }
1925: }
1926: }
1927: return (\%ruleshash,\@ruleorder);
1928: }
1929:
1.976 raeburn 1930: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1931:
1932: sub get_domain_defaults {
1933: my ($domain) = @_;
1934: my $cachetime = 60*60*24;
1935: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1936: if (defined($cached)) {
1937: if (ref($result) eq 'HASH') {
1938: return %{$result};
1939: }
1940: }
1941: my %domdefaults;
1942: my %domconfig =
1.989 raeburn 1943: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1944: 'requestcourses','inststatus',
1.1183 raeburn 1945: 'coursedefaults','usersessions',
1946: 'requestauthor'],$domain);
1.943 raeburn 1947: if (ref($domconfig{'defaults'}) eq 'HASH') {
1948: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1949: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1950: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1951: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1952: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1953: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1954: } else {
1955: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1956: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1957: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1958: }
1.976 raeburn 1959: if (ref($domconfig{'quotas'}) eq 'HASH') {
1960: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1961: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1962: } else {
1963: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1964: }
1.1177 raeburn 1965: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 1966: foreach my $item (@usertools) {
1967: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1968: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1969: }
1970: }
1971: }
1.985 raeburn 1972: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1973: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1974: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1975: }
1976: }
1.1183 raeburn 1977: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
1978: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
1979: }
1.989 raeburn 1980: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1981: foreach my $item ('inststatustypes','inststatusorder') {
1982: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1983: }
1984: }
1.1047 raeburn 1985: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1986: foreach my $item ('canuse_pdfforms') {
1987: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1988: }
1989: }
1.1073 raeburn 1990: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1991: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1992: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1993: }
1994: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1995: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1996: }
1997: }
1.943 raeburn 1998: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1999: $cachetime);
2000: return %domdefaults;
2001: }
2002:
1.344 www 2003: # --------------------------------------------------- Assign a key to a student
2004:
2005: sub assign_access_key {
1.364 www 2006: #
2007: # a valid key looks like uname:udom#comments
2008: # comments are being appended
2009: #
1.498 www 2010: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2011: $kdom=
1.620 albertel 2012: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2013: $knum=
1.620 albertel 2014: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2015: $cdom=
1.620 albertel 2016: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2017: $cnum=
1.620 albertel 2018: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2019: $udom=$env{'user.name'} unless (defined($udom));
2020: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2021: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2022: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2023: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2024: # assigned to this person
2025: # - this should not happen,
1.345 www 2026: # unless something went wrong
2027: # the first time around
2028: # ready to assign
1.364 www 2029: $logentry=$1.'; '.$logentry;
1.496 www 2030: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2031: $kdom,$knum) eq 'ok') {
1.345 www 2032: # key now belongs to user
1.346 www 2033: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2034: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2035: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2036: return 'ok';
2037: } else {
2038: return
2039: 'error: Count not permanently assign key, will need to be re-entered later.';
2040: }
2041: } else {
2042: return 'error: Could not assign key, try again later.';
2043: }
1.364 www 2044: } elsif (!$existing{$ckey}) {
1.345 www 2045: # the key does not exist
2046: return 'error: The key does not exist';
2047: } else {
2048: # the key is somebody else's
2049: return 'error: The key is already in use';
2050: }
1.344 www 2051: }
2052:
1.364 www 2053: # ------------------------------------------ put an additional comment on a key
2054:
2055: sub comment_access_key {
2056: #
2057: # a valid key looks like uname:udom#comments
2058: # comments are being appended
2059: #
2060: my ($ckey,$cdom,$cnum,$logentry)=@_;
2061: $cdom=
1.620 albertel 2062: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2063: $cnum=
1.620 albertel 2064: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2065: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2066: if ($existing{$ckey}) {
2067: $existing{$ckey}.='; '.$logentry;
2068: # ready to assign
1.367 www 2069: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2070: $cdom,$cnum) eq 'ok') {
2071: return 'ok';
2072: } else {
2073: return 'error: Count not store comment.';
2074: }
2075: } else {
2076: # the key does not exist
2077: return 'error: The key does not exist';
2078: }
2079: }
2080:
1.344 www 2081: # ------------------------------------------------------ Generate a set of keys
2082:
2083: sub generate_access_keys {
1.364 www 2084: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2085: $cdom=
1.620 albertel 2086: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2087: $cnum=
1.620 albertel 2088: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2089: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2090: unless (($cdom) && ($cnum)) { return 0; }
2091: if ($number>10000) { return 0; }
2092: sleep(2); # make sure don't get same seed twice
2093: srand(time()^($$+($$<<15))); # from "Programming Perl"
2094: my $total=0;
2095: for (my $i=1;$i<=$number;$i++) {
2096: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2097: sprintf("%lx",int(100000*rand)).'-'.
2098: sprintf("%lx",int(100000*rand));
2099: $newkey=~s/1/g/g; # folks mix up 1 and l
2100: $newkey=~s/0/h/g; # and also 0 and O
2101: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2102: if ($existing{$newkey}) {
2103: $i--;
2104: } else {
1.364 www 2105: if (&put('accesskeys',
2106: { $newkey => '# generated '.localtime().
1.620 albertel 2107: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2108: '; '.$logentry },
2109: $cdom,$cnum) eq 'ok') {
1.344 www 2110: $total++;
2111: }
2112: }
2113: }
1.620 albertel 2114: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2115: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2116: return $total;
2117: }
2118:
2119: # ------------------------------------------------------- Validate an accesskey
2120:
2121: sub validate_access_key {
2122: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2123: $cdom=
1.620 albertel 2124: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2125: $cnum=
1.620 albertel 2126: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2127: $udom=$env{'user.domain'} unless (defined($udom));
2128: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2129: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2130: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2131: }
2132:
2133: # ------------------------------------- Find the section of student in a course
1.652 albertel 2134: sub devalidate_getsection_cache {
2135: my ($udom,$unam,$courseid)=@_;
2136: my $hashid="$udom:$unam:$courseid";
2137: &devalidate_cache_new('getsection',$hashid);
2138: }
1.298 matthew 2139:
1.815 albertel 2140: sub courseid_to_courseurl {
2141: my ($courseid) = @_;
2142: #already url style courseid
2143: return $courseid if ($courseid =~ m{^/});
2144:
2145: if (exists($env{'course.'.$courseid.'.num'})) {
2146: my $cnum = $env{'course.'.$courseid.'.num'};
2147: my $cdom = $env{'course.'.$courseid.'.domain'};
2148: return "/$cdom/$cnum";
2149: }
2150:
2151: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2152: if (exists($courseinfo{'num'})) {
2153: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2154: }
2155:
2156: return undef;
2157: }
2158:
1.298 matthew 2159: sub getsection {
2160: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2161: my $cachetime=1800;
1.551 albertel 2162:
2163: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2164: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2165: if (defined($cached)) { return $result; }
2166:
1.298 matthew 2167: my %Pending;
2168: my %Expired;
2169: #
2170: # Each role can either have not started yet (pending), be active,
2171: # or have expired.
2172: #
2173: # If there is an active role, we are done.
2174: #
2175: # If there is more than one role which has not started yet,
2176: # choose the one which will start sooner
2177: # If there is one role which has not started yet, return it.
2178: #
2179: # If there is more than one expired role, choose the one which ended last.
2180: # If there is a role which has expired, return it.
2181: #
1.815 albertel 2182: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2183: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2184: foreach my $key (keys(%roleshash)) {
1.479 albertel 2185: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2186: my $section=$1;
2187: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2188: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2189: my $now=time;
1.548 albertel 2190: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2191: $Expired{$end}=$section;
2192: next;
2193: }
1.548 albertel 2194: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2195: $Pending{$start}=$section;
2196: next;
2197: }
1.599 albertel 2198: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2199: }
2200: #
2201: # Presumedly there will be few matching roles from the above
2202: # loop and the sorting time will be negligible.
2203: if (scalar(keys(%Pending))) {
2204: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2205: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2206: }
2207: if (scalar(keys(%Expired))) {
2208: my @sorted = sort {$a <=> $b} keys(%Expired);
2209: my $time = pop(@sorted);
1.599 albertel 2210: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2211: }
1.599 albertel 2212: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2213: }
1.70 www 2214:
1.599 albertel 2215: sub save_cache {
2216: &purge_remembered();
1.722 albertel 2217: #&Apache::loncommon::validate_page();
1.620 albertel 2218: undef(%env);
1.780 albertel 2219: undef($env_loaded);
1.599 albertel 2220: }
1.452 albertel 2221:
1.599 albertel 2222: my $to_remember=-1;
2223: my %remembered;
2224: my %accessed;
2225: my $kicks=0;
2226: my $hits=0;
1.849 albertel 2227: sub make_key {
2228: my ($name,$id) = @_;
1.872 albertel 2229: if (length($id) > 65
2230: && length(&escape($id)) > 200) {
2231: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2232: }
1.849 albertel 2233: return &escape($name.':'.$id);
2234: }
2235:
1.599 albertel 2236: sub devalidate_cache_new {
2237: my ($name,$id,$debug) = @_;
2238: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2239: $id=&make_key($name,$id);
1.599 albertel 2240: $memcache->delete($id);
2241: delete($remembered{$id});
2242: delete($accessed{$id});
2243: }
2244:
2245: sub is_cached_new {
2246: my ($name,$id,$debug) = @_;
1.849 albertel 2247: $id=&make_key($name,$id);
1.599 albertel 2248: if (exists($remembered{$id})) {
1.1133 foxr 2249: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2250: $accessed{$id}=[&gettimeofday()];
2251: $hits++;
2252: return ($remembered{$id},1);
2253: }
2254: my $value = $memcache->get($id);
2255: if (!(defined($value))) {
2256: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2257: return (undef,undef);
1.416 albertel 2258: }
1.599 albertel 2259: if ($value eq '__undef__') {
2260: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2261: $value=undef;
2262: }
2263: &make_room($id,$value,$debug);
2264: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2265: return ($value,1);
2266: }
2267:
2268: sub do_cache_new {
2269: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2270: $id=&make_key($name,$id);
1.599 albertel 2271: my $setvalue=$value;
2272: if (!defined($setvalue)) {
2273: $setvalue='__undef__';
2274: }
1.623 albertel 2275: if (!defined($time) ) {
2276: $time=600;
2277: }
1.599 albertel 2278: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2279: my $result = $memcache->set($id,$setvalue,$time);
2280: if (! $result) {
1.872 albertel 2281: &logthis("caching of id -> $id failed");
1.910 albertel 2282: $memcache->disconnect_all();
1.872 albertel 2283: }
1.600 albertel 2284: # need to make a copy of $value
1.919 albertel 2285: &make_room($id,$value,$debug);
1.599 albertel 2286: return $value;
2287: }
2288:
2289: sub make_room {
2290: my ($id,$value,$debug)=@_;
1.919 albertel 2291:
2292: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2293: : $value;
1.599 albertel 2294: if ($to_remember<0) { return; }
2295: $accessed{$id}=[&gettimeofday()];
2296: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2297: my $to_kick;
2298: my $max_time=0;
2299: foreach my $other (keys(%accessed)) {
2300: if (&tv_interval($accessed{$other}) > $max_time) {
2301: $to_kick=$other;
2302: $max_time=&tv_interval($accessed{$other});
2303: }
2304: }
2305: delete($remembered{$to_kick});
2306: delete($accessed{$to_kick});
2307: $kicks++;
2308: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2309: return;
2310: }
2311:
1.599 albertel 2312: sub purge_remembered {
1.604 albertel 2313: #&logthis("Tossing ".scalar(keys(%remembered)));
2314: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2315: undef(%remembered);
2316: undef(%accessed);
1.428 albertel 2317: }
1.70 www 2318: # ------------------------------------- Read an entry from a user's environment
2319:
2320: sub userenvironment {
2321: my ($udom,$unam,@what)=@_;
1.976 raeburn 2322: my $items;
2323: foreach my $item (@what) {
2324: $items.=&escape($item).'&';
2325: }
2326: $items=~s/\&$//;
1.70 www 2327: my %returnhash=();
1.1009 raeburn 2328: my $uhome = &homeserver($unam,$udom);
2329: unless ($uhome eq 'no_host') {
2330: my @answer=split(/\&/,
2331: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2332: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2333: return %returnhash;
2334: }
1.1009 raeburn 2335: my $i;
2336: for ($i=0;$i<=$#what;$i++) {
2337: $returnhash{$what[$i]}=&unescape($answer[$i]);
2338: }
1.70 www 2339: }
2340: return %returnhash;
1.1 albertel 2341: }
2342:
1.617 albertel 2343: # ---------------------------------------------------------- Get a studentphoto
2344: sub studentphoto {
2345: my ($udom,$unam,$ext) = @_;
2346: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2347: if (defined($env{'request.course.id'})) {
1.708 raeburn 2348: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2349: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2350: return(&retrievestudentphoto($udom,$unam,$ext));
2351: } else {
2352: my ($result,$perm_reqd)=
1.707 albertel 2353: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2354: if ($result eq 'ok') {
2355: if (!($perm_reqd eq 'yes')) {
2356: return(&retrievestudentphoto($udom,$unam,$ext));
2357: }
2358: }
2359: }
2360: }
2361: } else {
2362: my ($result,$perm_reqd) =
1.707 albertel 2363: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2364: if ($result eq 'ok') {
2365: if (!($perm_reqd eq 'yes')) {
2366: return(&retrievestudentphoto($udom,$unam,$ext));
2367: }
2368: }
2369: }
2370: return '/adm/lonKaputt/lonlogo_broken.gif';
2371: }
2372:
2373: sub retrievestudentphoto {
2374: my ($udom,$unam,$ext,$type) = @_;
2375: my $home=&Apache::lonnet::homeserver($unam,$udom);
2376: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2377: if ($ret eq 'ok') {
2378: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2379: if ($type eq 'thumbnail') {
2380: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2381: }
2382: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2383: return $tokenurl;
2384: } else {
2385: if ($type eq 'thumbnail') {
2386: return '/adm/lonKaputt/genericstudent_tn.gif';
2387: } else {
2388: return '/adm/lonKaputt/lonlogo_broken.gif';
2389: }
1.617 albertel 2390: }
2391: }
2392:
1.263 www 2393: # -------------------------------------------------------------------- New chat
2394:
2395: sub chatsend {
1.724 raeburn 2396: my ($newentry,$anon,$group)=@_;
1.620 albertel 2397: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2398: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2399: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2400: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2401: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2402: &escape($newentry)).':'.$group,$chome);
1.292 www 2403: }
2404:
2405: # ------------------------------------------ Find current version of a resource
2406:
2407: sub getversion {
2408: my $fname=&clutter(shift);
2409: unless ($fname=~/^\/res\//) { return -1; }
2410: return ¤tversion(&filelocation('',$fname));
2411: }
2412:
2413: sub currentversion {
2414: my $fname=shift;
2415: my $author=$fname;
2416: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2417: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2418: my $home=&homeserver($uname,$udom);
1.292 www 2419: if ($home eq 'no_host') {
2420: return -1;
2421: }
1.1112 www 2422: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2423: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2424: return -1;
2425: }
1.1112 www 2426: return $answer;
1.263 www 2427: }
2428:
1.1111 www 2429: #
2430: # Return special version number of resource if set by override, empty otherwise
2431: #
2432: sub usedversion {
2433: my $fname=shift;
2434: unless ($fname) { $fname=$env{'request.uri'}; }
2435: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2436: if ($urlversion) { return $urlversion; }
2437: return '';
2438: }
2439:
1.1 albertel 2440: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2441:
1.1 albertel 2442: sub subscribe {
2443: my $fname=shift;
1.761 raeburn 2444: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2445: $fname=~s/[\n\r]//g;
1.1 albertel 2446: my $author=$fname;
2447: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2448: my ($udom,$uname)=split(/\//,$author);
2449: my $home=homeserver($uname,$udom);
1.335 albertel 2450: if ($home eq 'no_host') {
2451: return 'not_found';
1.1 albertel 2452: }
2453: my $answer=reply("sub:$fname",$home);
1.64 www 2454: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2455: $answer.=' by '.$home;
2456: }
1.1 albertel 2457: return $answer;
2458: }
2459:
1.8 www 2460: # -------------------------------------------------------------- Replicate file
2461:
2462: sub repcopy {
2463: my $filename=shift;
1.23 www 2464: $filename=~s/\/+/\//g;
1.1142 raeburn 2465: my $londocroot = $perlvar{'lonDocRoot'};
2466: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2467: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2468: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2469: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2470: return &repcopy_userfile($filename);
2471: }
1.532 albertel 2472: $filename=~s/[\n\r]//g;
1.8 www 2473: my $transname="$filename.in.transfer";
1.828 www 2474: # FIXME: this should flock
1.607 raeburn 2475: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2476: my $remoteurl=subscribe($filename);
1.64 www 2477: if ($remoteurl =~ /^con_lost by/) {
2478: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2479: return 'unavailable';
1.8 www 2480: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2481: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2482: return 'not_found';
1.64 www 2483: } elsif ($remoteurl =~ /^rejected by/) {
2484: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2485: return 'forbidden';
1.20 www 2486: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2487: return 'ok';
1.8 www 2488: } else {
1.290 www 2489: my $author=$filename;
2490: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2491: my ($udom,$uname)=split(/\//,$author);
2492: my $home=homeserver($uname,$udom);
2493: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2494: my @parts=split(/\//,$filename);
2495: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2496: if ($path ne "$londocroot/res") {
1.8 www 2497: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2498: return 'bad_request';
1.8 www 2499: }
2500: my $count;
2501: for ($count=5;$count<$#parts;$count++) {
2502: $path.="/$parts[$count]";
2503: if ((-e $path)!=1) {
2504: mkdir($path,0777);
2505: }
2506: }
2507: my $ua=new LWP::UserAgent;
2508: my $request=new HTTP::Request('GET',"$remoteurl");
2509: my $response=$ua->request($request,$transname);
2510: if ($response->is_error()) {
2511: unlink($transname);
2512: my $message=$response->status_line;
1.672 albertel 2513: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2514: ." LWP get: $message: $filename</font>");
1.607 raeburn 2515: return 'unavailable';
1.8 www 2516: } else {
1.16 www 2517: if ($remoteurl!~/\.meta$/) {
2518: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2519: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2520: if ($mresponse->is_error()) {
2521: unlink($filename.'.meta');
2522: &logthis(
1.672 albertel 2523: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2524: }
2525: }
1.8 www 2526: rename($transname,$filename);
1.607 raeburn 2527: return 'ok';
1.8 www 2528: }
1.290 www 2529: }
1.8 www 2530: }
1.330 www 2531: }
2532:
2533: # ------------------------------------------------ Get server side include body
2534: sub ssi_body {
1.381 albertel 2535: my ($filelink,%form)=@_;
1.606 matthew 2536: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2537: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2538: }
1.953 www 2539: my $output='';
2540: my $response;
1.980 raeburn 2541: if ($filelink=~/^https?\:/) {
1.954 raeburn 2542: ($output,$response)=&externalssi($filelink);
1.953 www 2543: } else {
1.1004 droeschl 2544: $filelink .= $filelink=~/\?/ ? '&' : '?';
2545: $filelink .= 'inhibitmenu=yes';
1.953 www 2546: ($output,$response)=&ssi($filelink,%form);
2547: }
1.778 albertel 2548: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2549: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2550: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2551: if (wantarray) {
2552: return ($output, $response);
2553: } else {
2554: return $output;
2555: }
1.8 www 2556: }
2557:
1.15 www 2558: # --------------------------------------------------------- Server Side Include
2559:
1.782 albertel 2560: sub absolute_url {
2561: my ($host_name) = @_;
2562: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2563: if ($host_name eq '') {
2564: $host_name = $ENV{'SERVER_NAME'};
2565: }
2566: return $protocol.$host_name;
2567: }
2568:
1.942 foxr 2569: #
2570: # Server side include.
2571: # Parameters:
2572: # fn Possibly encrypted resource name/id.
2573: # form Hash that describes how the rendering should be done
2574: # and other things.
1.944 foxr 2575: # Returns:
1.950 raeburn 2576: # Scalar context: The content of the response.
2577: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2578: #
1.15 www 2579: sub ssi {
2580:
1.944 foxr 2581: my ($fn,%form)=@_;
1.15 www 2582: my $ua=new LWP::UserAgent;
1.23 www 2583: my $request;
1.711 albertel 2584:
2585: $form{'no_update_last_known'}=1;
1.895 albertel 2586: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2587: if (%form) {
1.782 albertel 2588: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2589: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2590: } else {
1.782 albertel 2591: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2592: }
2593:
1.15 www 2594: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2595: my $response= $ua->request($request);
1.1182 foxr 2596: my $content = $response->content;
2597:
2598:
1.944 foxr 2599: if (wantarray) {
1.1173 foxr 2600: return ($content, $response);
1.944 foxr 2601: } else {
1.1173 foxr 2602: return $content;
1.942 foxr 2603: }
1.324 www 2604: }
2605:
2606: sub externalssi {
2607: my ($url)=@_;
2608: my $ua=new LWP::UserAgent;
2609: my $request=new HTTP::Request('GET',$url);
2610: my $response=$ua->request($request);
1.954 raeburn 2611: if (wantarray) {
2612: return ($response->content, $response);
2613: } else {
2614: return $response->content;
2615: }
1.15 www 2616: }
1.254 www 2617:
1.492 albertel 2618: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2619:
2620: sub allowuploaded {
2621: my ($srcurl,$url)=@_;
2622: $url=&clutter(&declutter($url));
2623: my $dir=$url;
2624: $dir=~s/\/[^\/]+$//;
2625: my %httpref=();
2626: my $httpurl=&hreflocation('',$url);
2627: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2628: &Apache::lonnet::appenv(\%httpref);
1.254 www 2629: }
1.477 raeburn 2630:
1.478 albertel 2631: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2632: # input: action, courseID, current domain, intended
1.637 raeburn 2633: # path to file, source of file, instruction to parse file for objects,
2634: # ref to hash for embedded objects,
2635: # ref to hash for codebase of java objects.
1.1095 raeburn 2636: # reference to scalar to accommodate mime type determined
2637: # from File::MMagic if $parser = parse.
1.637 raeburn 2638: #
1.485 raeburn 2639: # output: url to file (if action was uploaddoc),
2640: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2641: #
1.478 albertel 2642: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2643: # course.
1.477 raeburn 2644: #
1.478 albertel 2645: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2646: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2647: # course's home server.
1.477 raeburn 2648: #
1.478 albertel 2649: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2650: # be copied from $source (current location) to
2651: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2652: # and will then be copied to
2653: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2654: # course's home server.
1.485 raeburn 2655: #
1.481 raeburn 2656: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2657: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2658: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2659: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2660: # in course's home server.
1.637 raeburn 2661: #
1.477 raeburn 2662:
2663: sub process_coursefile {
1.1095 raeburn 2664: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2665: $mimetype)=@_;
1.477 raeburn 2666: my $fetchresult;
1.638 albertel 2667: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2668: if ($action eq 'propagate') {
1.638 albertel 2669: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2670: $home);
1.481 raeburn 2671: } else {
1.477 raeburn 2672: my $fpath = '';
2673: my $fname = $file;
1.478 albertel 2674: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2675: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2676: my $filepath = &build_filepath($fpath);
1.481 raeburn 2677: if ($action eq 'copy') {
2678: if ($source eq '') {
2679: $fetchresult = 'no source file';
2680: return $fetchresult;
2681: } else {
2682: my $destination = $filepath.'/'.$fname;
2683: rename($source,$destination);
2684: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2685: $home);
1.481 raeburn 2686: }
2687: } elsif ($action eq 'uploaddoc') {
2688: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2689: print $fh $env{'form.'.$source};
1.481 raeburn 2690: close($fh);
1.637 raeburn 2691: if ($parser eq 'parse') {
1.1024 raeburn 2692: my $mm = new File::MMagic;
1.1095 raeburn 2693: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2694: if ($type eq 'text/html') {
1.1024 raeburn 2695: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2696: unless ($parse_result eq 'ok') {
2697: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2698: }
1.637 raeburn 2699: }
1.1095 raeburn 2700: if (ref($mimetype)) {
2701: $$mimetype = $type;
2702: }
1.637 raeburn 2703: }
1.477 raeburn 2704: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2705: $home);
1.481 raeburn 2706: if ($fetchresult eq 'ok') {
2707: return '/uploaded/'.$fpath.'/'.$fname;
2708: } else {
2709: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2710: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2711: return '/adm/notfound.html';
2712: }
1.477 raeburn 2713: }
2714: }
1.485 raeburn 2715: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2716: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2717: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2718: }
2719: return $fetchresult;
2720: }
2721:
1.637 raeburn 2722: sub build_filepath {
2723: my ($fpath) = @_;
2724: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2725: unless ($fpath eq '') {
2726: my @parts=split('/',$fpath);
2727: foreach my $part (@parts) {
2728: $filepath.= '/'.$part;
2729: if ((-e $filepath)!=1) {
2730: mkdir($filepath,0777);
2731: }
2732: }
2733: }
2734: return $filepath;
2735: }
2736:
2737: sub store_edited_file {
1.638 albertel 2738: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2739: my $file = $primary_url;
2740: $file =~ s#^/uploaded/$docudom/$docuname/##;
2741: my $fpath = '';
2742: my $fname = $file;
2743: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2744: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2745: my $filepath = &build_filepath($fpath);
2746: open(my $fh,'>'.$filepath.'/'.$fname);
2747: print $fh $content;
2748: close($fh);
1.638 albertel 2749: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2750: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2751: $home);
1.637 raeburn 2752: if ($$fetchresult eq 'ok') {
2753: return '/uploaded/'.$fpath.'/'.$fname;
2754: } else {
1.638 albertel 2755: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2756: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2757: return '/adm/notfound.html';
2758: }
2759: }
2760:
1.531 albertel 2761: sub clean_filename {
1.831 albertel 2762: my ($fname,$args)=@_;
1.315 www 2763: # Replace Windows backslashes by forward slashes
1.257 www 2764: $fname=~s/\\/\//g;
1.831 albertel 2765: if (!$args->{'keep_path'}) {
2766: # Get rid of everything but the actual filename
2767: $fname=~s/^.*\/([^\/]+)$/$1/;
2768: }
1.315 www 2769: # Replace spaces by underscores
2770: $fname=~s/\s+/\_/g;
2771: # Replace all other weird characters by nothing
1.831 albertel 2772: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2773: # Replace all .\d. sequences with _\d. so they no longer look like version
2774: # numbers
2775: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2776: return $fname;
2777: }
1.1051 raeburn 2778: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2779: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2780: # image with the same aspect ratio as the original, but with dimensions which do
2781: # not exceed $resizewidth and $resizeheight.
2782:
1.984 neumanie 2783: sub resizeImage {
1.1051 raeburn 2784: my ($img_path,$resizewidth,$resizeheight) = @_;
2785: my $ima = Image::Magick->new;
2786: my $resized;
2787: if (-e $img_path) {
2788: $ima->Read($img_path);
2789: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2790: my $width = $ima->Get('width');
2791: my $height = $ima->Get('height');
2792: if ($width > $resizewidth) {
2793: my $factor = $width/$resizewidth;
2794: my $newheight = $height/$factor;
2795: $ima->Scale(width=>$resizewidth,height=>$newheight);
2796: $resized = 1;
2797: }
2798: }
2799: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2800: my $width = $ima->Get('width');
2801: my $height = $ima->Get('height');
2802: if ($height > $resizeheight) {
2803: my $factor = $height/$resizeheight;
2804: my $newwidth = $width/$factor;
2805: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2806: $resized = 1;
2807: }
2808: }
2809: if ($resized) {
2810: $ima->Write($img_path);
2811: }
2812: }
2813: return;
1.977 amueller 2814: }
2815:
1.608 albertel 2816: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2817: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2818: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2819: # $context - possible values: coursedoc, existingfile, overwrite,
2820: # canceloverwrite, or ''.
2821: # if 'coursedoc': upload to the current course
2822: # if 'existingfile': write file to tmp/overwrites directory
2823: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2824: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2825: # $subdir - directory in userfile to store the file into
1.858 raeburn 2826: # $parser - instruction to parse file for objects ($parser = parse)
2827: # $allfiles - reference to hash for embedded objects
2828: # $codebase - reference to hash for codebase of java objects
2829: # $desuname - username for permanent storage of uploaded file
2830: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2831: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2832: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2833: # $resizewidth - width (pixels) to which to resize uploaded image
2834: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2835: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 2836: # from File::MMagic.
1.858 raeburn 2837: #
1.686 albertel 2838: # output: url of file in userspace, or error: <message>
2839: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2840:
1.531 albertel 2841: sub userfileupload {
1.1090 raeburn 2842: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2843: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2844: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2845: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2846: $fname=&clean_filename($fname);
1.1090 raeburn 2847: # See if there is anything left
1.257 www 2848: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2849: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2850: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2851: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2852: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2853: my $now = time;
1.1090 raeburn 2854: my $filepath;
1.1095 raeburn 2855: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2856: $filepath = 'tmp/helprequests/'.$now;
2857: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2858: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2859: '_'.$env{'user.domain'}.'/pending';
2860: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2861: my ($docuname,$docudom);
2862: if ($destudom) {
2863: $docudom = $destudom;
2864: } else {
2865: $docudom = $env{'user.domain'};
2866: }
2867: if ($destuname) {
2868: $docuname = $destuname;
2869: } else {
2870: $docuname = $env{'user.name'};
2871: }
2872: if (exists($env{'form.group'})) {
2873: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2874: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2875: }
2876: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2877: if ($context eq 'canceloverwrite') {
2878: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2879: if (-e $tempfile) {
2880: my @info = stat($tempfile);
2881: if ($info[9] eq $env{'form.timestamp'}) {
2882: unlink($tempfile);
2883: }
2884: }
2885: return;
1.523 raeburn 2886: }
2887: }
1.1090 raeburn 2888: # Create the directory if not present
1.741 raeburn 2889: my @parts=split(/\//,$filepath);
2890: my $fullpath = $perlvar{'lonDaemons'};
2891: for (my $i=0;$i<@parts;$i++) {
2892: $fullpath .= '/'.$parts[$i];
2893: if ((-e $fullpath)!=1) {
2894: mkdir($fullpath,0777);
2895: }
2896: }
2897: open(my $fh,'>'.$fullpath.'/'.$fname);
2898: print $fh $env{'form.'.$formname};
2899: close($fh);
1.1090 raeburn 2900: if ($context eq 'existingfile') {
2901: my @info = stat($fullpath.'/'.$fname);
2902: return ($fullpath.'/'.$fname,$info[9]);
2903: } else {
2904: return $fullpath.'/'.$fname;
2905: }
1.523 raeburn 2906: }
1.995 raeburn 2907: if ($subdir eq 'scantron') {
2908: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2909: } else {
1.995 raeburn 2910: $fname="$subdir/$fname";
2911: }
1.1090 raeburn 2912: if ($context eq 'coursedoc') {
1.638 albertel 2913: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2914: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2915: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2916: return &finishuserfileupload($docuname,$docudom,
2917: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2918: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2919: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2920: } else {
1.620 albertel 2921: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2922: return &process_coursefile('uploaddoc',$docuname,$docudom,
2923: $fname,$formname,$parser,
1.1095 raeburn 2924: $allfiles,$codebase,$mimetype);
1.481 raeburn 2925: }
1.719 banghart 2926: } elsif (defined($destuname)) {
2927: my $docuname=$destuname;
2928: my $docudom=$destudom;
1.860 raeburn 2929: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2930: $parser,$allfiles,$codebase,
1.1051 raeburn 2931: $thumbwidth,$thumbheight,
1.1095 raeburn 2932: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2933: } else {
1.638 albertel 2934: my $docuname=$env{'user.name'};
2935: my $docudom=$env{'user.domain'};
1.714 raeburn 2936: if (exists($env{'form.group'})) {
2937: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2938: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2939: }
1.860 raeburn 2940: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2941: $parser,$allfiles,$codebase,
1.1051 raeburn 2942: $thumbwidth,$thumbheight,
1.1095 raeburn 2943: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2944: }
1.271 www 2945: }
2946:
2947: sub finishuserfileupload {
1.860 raeburn 2948: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2949: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2950: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2951: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2952:
1.860 raeburn 2953: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2954: $file=$fname;
2955: if ($fname=~m|/|) {
2956: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2957: $path.=$fnamepath.'/';
2958: }
1.259 www 2959: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2960: my $count;
2961: for ($count=4;$count<=$#parts;$count++) {
2962: $filepath.="/$parts[$count]";
2963: if ((-e $filepath)!=1) {
2964: mkdir($filepath,0777);
2965: }
2966: }
1.984 neumanie 2967:
1.258 www 2968: # Save the file
2969: {
1.701 albertel 2970: if (!open(FH,'>'.$filepath.'/'.$file)) {
2971: &logthis('Failed to create '.$filepath.'/'.$file);
2972: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2973: return '/adm/notfound.html';
2974: }
1.1090 raeburn 2975: if ($context eq 'overwrite') {
1.1117 foxr 2976: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2977: my $target = $filepath.'/'.$file;
2978: if (-e $source) {
2979: my @info = stat($source);
2980: if ($info[9] eq $env{'form.timestamp'}) {
2981: unless (&File::Copy::move($source,$target)) {
2982: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2983: return "Moving from $source failed";
2984: }
2985: } else {
2986: return "Temporary file: $source had unexpected date/time for last modification";
2987: }
2988: } else {
2989: return "Temporary file: $source missing";
2990: }
2991: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2992: &logthis('Failed to write to '.$filepath.'/'.$file);
2993: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2994: return '/adm/notfound.html';
2995: }
1.570 albertel 2996: close(FH);
1.1051 raeburn 2997: if ($resizewidth && $resizeheight) {
2998: my $mm = new File::MMagic;
2999: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3000: if ($mime_type =~ m{^image/}) {
3001: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3002: }
1.977 amueller 3003: }
1.258 www 3004: }
1.1152 raeburn 3005: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3006: if (ref($mimetype)) {
3007: if ($$mimetype eq '') {
3008: my $mm = new File::MMagic;
3009: my $type = $mm->checktype_filename($filepath.'/'.$file);
3010: $$mimetype = $type;
3011: }
3012: }
3013: }
1.637 raeburn 3014: if ($parser eq 'parse') {
1.1152 raeburn 3015: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3016: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3017: $allfiles,$codebase);
3018: unless ($parse_result eq 'ok') {
3019: &logthis('Failed to parse '.$filepath.$file.
3020: ' for embedded media: '.$parse_result);
3021: }
1.637 raeburn 3022: }
3023: }
1.860 raeburn 3024: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3025: my $input = $filepath.'/'.$file;
3026: my $output = $filepath.'/'.'tn-'.$file;
3027: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3028: system("convert -sample $thumbsize $input $output");
3029: if (-e $filepath.'/'.'tn-'.$file) {
3030: $fetchthumb = 1;
3031: }
3032: }
1.858 raeburn 3033:
1.259 www 3034: # Notify homeserver to grep it
3035: #
1.984 neumanie 3036: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3037: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3038: if ($fetchresult eq 'ok') {
1.860 raeburn 3039: if ($fetchthumb) {
3040: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3041: if ($thumbresult ne 'ok') {
3042: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3043: $docuhome.': '.$thumbresult);
3044: }
3045: }
1.259 www 3046: #
1.258 www 3047: # Return the URL to it
1.494 albertel 3048: return '/uploaded/'.$path.$file;
1.263 www 3049: } else {
1.494 albertel 3050: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3051: ': '.$fetchresult);
1.263 www 3052: return '/adm/notfound.html';
1.858 raeburn 3053: }
1.493 albertel 3054: }
3055:
1.637 raeburn 3056: sub extract_embedded_items {
1.961 raeburn 3057: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3058: my @state = ();
1.1164 raeburn 3059: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3060: my %javafiles = (
3061: codebase => '',
3062: code => '',
3063: archive => ''
3064: );
3065: my %mediafiles = (
3066: src => '',
3067: movie => '',
3068: );
1.648 raeburn 3069: my $p;
3070: if ($content) {
3071: $p = HTML::LCParser->new($content);
3072: } else {
1.961 raeburn 3073: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3074: }
1.641 albertel 3075: while (my $t=$p->get_token()) {
1.640 albertel 3076: if ($t->[0] eq 'S') {
3077: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3078: push(@state, $tagname);
1.648 raeburn 3079: if (lc($tagname) eq 'allow') {
3080: &add_filetype($allfiles,$attr->{'src'},'src');
3081: }
1.640 albertel 3082: if (lc($tagname) eq 'img') {
3083: &add_filetype($allfiles,$attr->{'src'},'src');
3084: }
1.886 albertel 3085: if (lc($tagname) eq 'a') {
3086: &add_filetype($allfiles,$attr->{'href'},'href');
3087: }
1.645 raeburn 3088: if (lc($tagname) eq 'script') {
1.1164 raeburn 3089: my $src;
1.645 raeburn 3090: if ($attr->{'archive'} =~ /\.jar$/i) {
3091: &add_filetype($allfiles,$attr->{'archive'},'archive');
3092: } else {
1.1164 raeburn 3093: if ($attr->{'src'} ne '') {
3094: $src = $attr->{'src'};
3095: &add_filetype($allfiles,$src,'src');
3096: }
3097: }
3098: my $text = $p->get_trimmed_text();
3099: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3100: my @swfargs = split(/,/,$1);
3101: foreach my $item (@swfargs) {
3102: $item =~ s/["']//g;
3103: $item =~ s/^\s+//;
3104: $item =~ s/\s+$//;
3105: }
3106: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3107: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3108: push(@{$related{$swfargs[0]}},$swfargs[2]);
3109: } else {
3110: $related{$swfargs[0]} = [$swfargs[2]];
3111: }
3112: }
1.645 raeburn 3113: }
3114: }
3115: if (lc($tagname) eq 'link') {
3116: if (lc($attr->{'rel'}) eq 'stylesheet') {
3117: &add_filetype($allfiles,$attr->{'href'},'href');
3118: }
3119: }
1.640 albertel 3120: if (lc($tagname) eq 'object' ||
3121: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3122: foreach my $item (keys(%javafiles)) {
3123: $javafiles{$item} = '';
3124: }
1.1164 raeburn 3125: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3126: $lastids{lc($tagname)} = $attr->{'id'};
3127: }
1.640 albertel 3128: }
3129: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3130: my $name = lc($attr->{'name'});
3131: foreach my $item (keys(%javafiles)) {
3132: if ($name eq $item) {
3133: $javafiles{$item} = $attr->{'value'};
3134: last;
3135: }
3136: }
1.1164 raeburn 3137: my $pathfrom;
1.640 albertel 3138: foreach my $item (keys(%mediafiles)) {
3139: if ($name eq $item) {
1.1164 raeburn 3140: $pathfrom = $attr->{'value'};
3141: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3142: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3143: last;
3144: }
3145: }
1.1164 raeburn 3146: if ($name eq 'flashvars') {
3147: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3148: }
3149: if ($pathfrom ne '') {
3150: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3151: $pathfrom);
3152: }
1.640 albertel 3153: }
3154: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3155: foreach my $item (keys(%javafiles)) {
3156: if ($attr->{$item}) {
3157: $javafiles{$item} = $attr->{$item};
3158: last;
3159: }
3160: }
3161: foreach my $item (keys(%mediafiles)) {
3162: if ($attr->{$item}) {
3163: &add_filetype($allfiles,$attr->{$item},$item);
3164: last;
3165: }
3166: }
1.1164 raeburn 3167: if (lc($tagname) eq 'embed') {
3168: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3169: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3170: $attr->{'src'});
3171: }
3172: }
1.640 albertel 3173: }
1.1164 raeburn 3174: if ($t->[4] =~ m{/>$}) {
3175: pop(@state);
3176: }
1.640 albertel 3177: } elsif ($t->[0] eq 'E') {
3178: my ($tagname) = ($t->[1]);
3179: if ($javafiles{'codebase'} ne '') {
3180: $javafiles{'codebase'} .= '/';
3181: }
3182: if (lc($tagname) eq 'applet' ||
3183: lc($tagname) eq 'object' ||
3184: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3185: ) {
3186: foreach my $item (keys(%javafiles)) {
3187: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3188: my $file=$javafiles{'codebase'}.$javafiles{$item};
3189: &add_filetype($allfiles,$file,$item);
3190: }
3191: }
3192: }
3193: pop @state;
3194: }
3195: }
1.1164 raeburn 3196: foreach my $id (sort(keys(%flashvars))) {
3197: if ($shockwave{$id} ne '') {
3198: my @pairs = split(/\&/,$flashvars{$id});
3199: foreach my $pair (@pairs) {
3200: my ($key,$value) = split(/\=/,$pair);
3201: if ($key eq 'thumb') {
3202: &add_filetype($allfiles,$value,$key);
3203: } elsif ($key eq 'content') {
3204: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3205: my ($ext) = ($value =~ /\.([^.]+)$/);
3206: if ($ext ne '') {
3207: &add_filetype($allfiles,$path.$value,$ext);
3208: }
3209: }
3210: }
3211: }
3212: }
1.637 raeburn 3213: return 'ok';
3214: }
3215:
1.639 albertel 3216: sub add_filetype {
3217: my ($allfiles,$file,$type)=@_;
3218: if (exists($allfiles->{$file})) {
3219: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3220: push(@{$allfiles->{$file}}, &escape($type));
3221: }
3222: } else {
3223: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3224: }
3225: }
3226:
1.1164 raeburn 3227: sub embedded_dependency {
3228: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3229: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3230: if (($identifier ne '') &&
3231: (ref($related->{$identifier}) eq 'ARRAY') &&
3232: ($pathfrom ne '')) {
3233: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3234: foreach my $dep (@{$related->{$identifier}}) {
3235: &add_filetype($allfiles,$path.$dep,'object');
3236: }
3237: }
3238: }
3239: return;
3240: }
3241:
1.493 albertel 3242: sub removeuploadedurl {
1.984 neumanie 3243: my ($url)=@_;
3244: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3245: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3246: }
3247:
3248: sub removeuserfile {
3249: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3250: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3251: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3252: if ($result eq 'ok') {
1.798 raeburn 3253: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3254: my $metafile = $fname.'.meta';
3255: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3256: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3257: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3258: my $sqlresult =
1.823 albertel 3259: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3260: 'portfolio_metadata',$group,
3261: 'delete');
1.798 raeburn 3262: }
3263: }
3264: return $result;
1.257 www 3265: }
1.15 www 3266:
1.530 albertel 3267: sub mkdiruserfile {
3268: my ($docuname,$docudom,$dir)=@_;
3269: my $home=&homeserver($docuname,$docudom);
3270: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3271: }
3272:
1.531 albertel 3273: sub renameuserfile {
3274: my ($docuname,$docudom,$old,$new)=@_;
3275: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3276: my $result = &reply("renameuserfile:$docudom:$docuname:".
3277: &escape("$old").':'.&escape("$new"),$home);
3278: if ($result eq 'ok') {
3279: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3280: my $oldmeta = $old.'.meta';
3281: my $newmeta = $new.'.meta';
3282: my $metaresult =
3283: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3284: my $url = "/uploaded/$docudom/$docuname/$old";
3285: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3286: my $sqlresult =
1.823 albertel 3287: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3288: 'portfolio_metadata',$group,
3289: 'delete');
1.798 raeburn 3290: }
3291: }
3292: return $result;
1.531 albertel 3293: }
3294:
1.14 www 3295: # ------------------------------------------------------------------------- Log
3296:
3297: sub log {
3298: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3299: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3300: }
3301:
3302: # ------------------------------------------------------------------ Course Log
1.352 www 3303: #
3304: # This routine flushes several buffers of non-mission-critical nature
3305: #
1.157 www 3306:
3307: sub flushcourselogs {
1.352 www 3308: &logthis('Flushing log buffers');
3309: #
3310: # course logs
3311: # This is a log of all transactions in a course, which can be used
3312: # for data mining purposes
3313: #
3314: # It also collects the courseid database, which lists last transaction
3315: # times and course titles for all courseids
3316: #
3317: my %courseidbuffer=();
1.921 raeburn 3318: foreach my $crsid (keys(%courselogs)) {
1.352 www 3319: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3320: &escape($courselogs{$crsid}),
3321: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3322: delete $courselogs{$crsid};
3323: } else {
3324: &logthis('Failed to flush log buffer for '.$crsid);
3325: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3326: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3327: " exceeded maximum size, deleting.</font>");
3328: delete $courselogs{$crsid};
3329: }
1.352 www 3330: }
1.920 raeburn 3331: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3332: 'description' => $coursedescrbuf{$crsid},
3333: 'inst_code' => $courseinstcodebuf{$crsid},
3334: 'type' => $coursetypebuf{$crsid},
3335: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3336: };
1.191 harris41 3337: }
1.352 www 3338: #
3339: # Write course id database (reverse lookup) to homeserver of courses
3340: # Is used in pickcourse
3341: #
1.840 albertel 3342: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3343: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3344: $courseidbuffer{$crs_home},
3345: $crs_home,'timeonly');
1.352 www 3346: }
3347: #
3348: # File accesses
3349: # Writes to the dynamic metadata of resources to get hit counts, etc.
3350: #
1.449 matthew 3351: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3352: if ($entry =~ /___count$/) {
3353: my ($dom,$name);
1.807 albertel 3354: ($dom,$name,undef)=
1.811 albertel 3355: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3356: if (! defined($dom) || $dom eq '' ||
3357: ! defined($name) || $name eq '') {
1.620 albertel 3358: my $cid = $env{'request.course.id'};
3359: $dom = $env{'request.'.$cid.'.domain'};
3360: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3361: }
1.450 matthew 3362: my $value = $accesshash{$entry};
3363: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3364: my %temphash=($url => $value);
1.449 matthew 3365: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3366: if ($result eq 'ok') {
3367: delete $accesshash{$entry};
3368: }
3369: } else {
1.811 albertel 3370: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3371: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3372: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3373: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3374: delete $accesshash{$entry};
3375: }
1.185 www 3376: }
1.191 harris41 3377: }
1.352 www 3378: #
3379: # Roles
3380: # Reverse lookup of user roles for course faculty/staff and co-authorship
3381: #
1.800 albertel 3382: foreach my $entry (keys(%userrolehash)) {
1.351 www 3383: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3384: split(/\:/,$entry);
3385: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3386: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3387: $rudom,$runame) eq 'ok') {
3388: delete $userrolehash{$entry};
3389: }
3390: }
1.662 raeburn 3391: #
3392: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3393: #
3394: my %domrolebuffer = ();
1.1000 raeburn 3395: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3396: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3397: if ($domrolebuffer{$rudom}) {
3398: $domrolebuffer{$rudom}.='&'.&escape($entry).
3399: '='.&escape($domainrolehash{$entry});
3400: } else {
3401: $domrolebuffer{$rudom}.=&escape($entry).
3402: '='.&escape($domainrolehash{$entry});
3403: }
3404: delete $domainrolehash{$entry};
3405: }
3406: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3407: my %servers = &get_servers($dom,'library');
3408: foreach my $tryserver (keys(%servers)) {
3409: unless (&reply('domroleput:'.$dom.':'.
3410: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3411: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3412: }
1.662 raeburn 3413: }
3414: }
1.186 www 3415: $dumpcount++;
1.157 www 3416: }
3417:
3418: sub courselog {
3419: my $what=shift;
1.158 www 3420: $what=time.':'.$what;
1.620 albertel 3421: unless ($env{'request.course.id'}) { return ''; }
3422: $coursedombuf{$env{'request.course.id'}}=
3423: $env{'course.'.$env{'request.course.id'}.'.domain'};
3424: $coursenumbuf{$env{'request.course.id'}}=
3425: $env{'course.'.$env{'request.course.id'}.'.num'};
3426: $coursehombuf{$env{'request.course.id'}}=
3427: $env{'course.'.$env{'request.course.id'}.'.home'};
3428: $coursedescrbuf{$env{'request.course.id'}}=
3429: $env{'course.'.$env{'request.course.id'}.'.description'};
3430: $courseinstcodebuf{$env{'request.course.id'}}=
3431: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3432: $courseownerbuf{$env{'request.course.id'}}=
3433: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3434: $coursetypebuf{$env{'request.course.id'}}=
3435: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3436: if (defined $courselogs{$env{'request.course.id'}}) {
3437: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3438: } else {
1.620 albertel 3439: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3440: }
1.620 albertel 3441: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3442: &flushcourselogs();
3443: }
1.158 www 3444: }
3445:
3446: sub courseacclog {
3447: my $fnsymb=shift;
1.620 albertel 3448: unless ($env{'request.course.id'}) { return ''; }
3449: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3450: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3451: $what.=':POST';
1.583 matthew 3452: # FIXME: Probably ought to escape things....
1.800 albertel 3453: foreach my $key (keys(%env)) {
3454: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3455: my $formitem = $1;
3456: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3457: $what.=':'.$formitem.'='.$env{$key};
3458: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3459: $what.=':'.$formitem.'='.$env{$key};
3460: }
1.158 www 3461: }
1.191 harris41 3462: }
1.583 matthew 3463: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3464: # FIXME: We should not be depending on a form parameter that someone
3465: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3466: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3467: $what.= ':POST';
3468: # FIXME: Probably ought to escape things....
3469: foreach my $element ('courseexp','crsfulltext','crsrelated',
3470: 'crsdiscuss') {
1.620 albertel 3471: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3472: }
3473: }
1.158 www 3474: }
3475: &courselog($what);
1.149 www 3476: }
3477:
1.185 www 3478: sub countacc {
3479: my $url=&declutter(shift);
1.458 matthew 3480: return if (! defined($url) || $url eq '');
1.620 albertel 3481: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3482: #
3483: # Mark that this url was used in this course
3484: #
1.620 albertel 3485: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3486: #
3487: # Increase the access count for this resource in this child process
3488: #
1.281 www 3489: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3490: $accesshash{$key}++;
1.185 www 3491: }
1.349 www 3492:
1.361 www 3493: sub linklog {
3494: my ($from,$to)=@_;
3495: $from=&declutter($from);
3496: $to=&declutter($to);
3497: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3498: $accesshash{$to.'___'.$from.'___goto'}=1;
3499: }
1.1160 www 3500:
3501: sub statslog {
3502: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3503: if ($users<2) { return; }
3504: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3505: 'course' => $env{'request.course.id'},
3506: 'sections' => '"all"',
3507: 'num_students' => $users,
3508: 'part' => $part,
3509: 'symb' => $symb,
3510: 'mean_tries' => $av_attempts,
3511: 'deg_of_diff' => $degdiff});
3512: foreach my $key (keys(%dynstore)) {
3513: $accesshash{$key}=$dynstore{$key};
3514: }
3515: }
1.361 www 3516:
1.349 www 3517: sub userrolelog {
3518: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3519: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3520: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3521: $userrolehash
3522: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3523: =$tend.':'.$tstart;
1.662 raeburn 3524: }
1.1169 droeschl 3525: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3526: $userrolehash
3527: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3528: =$tend.':'.$tstart;
3529: }
1.1169 droeschl 3530: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3531: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3532: $domainrolehash
3533: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3534: = $tend.':'.$tstart;
3535: }
1.351 www 3536: }
3537:
1.957 raeburn 3538: sub courserolelog {
3539: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 ! raeburn 3540: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
! 3541: my $cdom = $1;
! 3542: my $cnum = $2;
! 3543: my $sec = $3;
! 3544: my $namespace = 'rolelog';
! 3545: my %storehash = (
! 3546: role => $trole,
! 3547: start => $tstart,
! 3548: end => $tend,
! 3549: selfenroll => $selfenroll,
! 3550: context => $context,
! 3551: );
! 3552: if ($trole eq 'gr') {
! 3553: $namespace = 'groupslog';
! 3554: $storehash{'group'} = $sec;
! 3555: } else {
! 3556: $storehash{'section'} = $sec;
! 3557: }
! 3558: &write_rolelog('course',$namespace,\%storehash,$delflag,$domain,
! 3559: $username,$cdom,$cnum);
! 3560: if (($trole ne 'st') || ($sec ne '')) {
! 3561: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3562: }
3563: }
3564: return;
3565: }
3566:
1.1184 ! raeburn 3567: sub domainrolelog {
! 3568: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
! 3569: if ($area =~ m{^/($match_domain)/$}) {
! 3570: my $cdom = $1;
! 3571: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
! 3572: my $namespace = 'rolelog';
! 3573: my %storehash = (
! 3574: role => $trole,
! 3575: start => $tstart,
! 3576: end => $tend,
! 3577: context => $context,
! 3578: );
! 3579: &write_rolelog('domain',$namespace,\%storehash,$delflag,$domain,
! 3580: $username,$cdom,$domconfiguser);
! 3581: }
! 3582: return;
! 3583:
! 3584: }
! 3585:
! 3586: sub coauthorrolelog {
! 3587: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
! 3588: if ($area =~ m{^/($match_domain)/($match_username)$}) {
! 3589: my $audom = $1;
! 3590: my $auname = $2;
! 3591: my $namespace = 'rolelog';
! 3592: my %storehash = (
! 3593: role => $trole,
! 3594: start => $tstart,
! 3595: end => $tend,
! 3596: context => $context,
! 3597: );
! 3598: &write_rolelog('author',$namespace,\%storehash,$delflag,$domain,
! 3599: $username,$audom,$auname);
! 3600: }
! 3601: return;
! 3602: }
! 3603:
1.351 www 3604: sub get_course_adv_roles {
1.948 raeburn 3605: my ($cid,$codes) = @_;
1.620 albertel 3606: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3607: my %coursehash=&coursedescription($cid);
1.988 raeburn 3608: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3609: my %nothide=();
1.800 albertel 3610: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3611: if ($user !~ /:/) {
3612: $nothide{join(':',split(/[\@]/,$user))}=1;
3613: } else {
3614: $nothide{$user}=1;
3615: }
1.470 www 3616: }
1.351 www 3617: my %returnhash=();
3618: my %dumphash=
3619: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3620: my $now=time;
1.997 raeburn 3621: my %privileged;
1.1000 raeburn 3622: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3623: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3624: if (($tstart) && ($tstart<0)) { next; }
3625: if (($tend) && ($tend<$now)) { next; }
3626: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3627: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3628: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3629: unless (ref($privileged{$domain}) eq 'HASH') {
3630: my %dompersonnel =
1.998 raeburn 3631: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3632: $privileged{$domain} = {};
3633: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3634: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3635: foreach my $user (keys(%{$dompersonnel{$server}})) {
3636: my ($trole,$uname,$udom) = split(/:/,$user);
3637: $privileged{$udom}{$uname} = 1;
3638: }
3639: }
3640: }
3641: }
3642: if ((exists($privileged{$domain}{$username})) &&
3643: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3644: if ($role eq 'cr') { next; }
1.948 raeburn 3645: if ($codes) {
3646: if ($section) { $role .= ':'.$section; }
3647: if ($returnhash{$role}) {
3648: $returnhash{$role}.=','.$username.':'.$domain;
3649: } else {
3650: $returnhash{$role}=$username.':'.$domain;
3651: }
1.351 www 3652: } else {
1.988 raeburn 3653: my $key=&plaintext($role,$crstype);
1.973 bisitz 3654: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3655: if ($returnhash{$key}) {
3656: $returnhash{$key}.=','.$username.':'.$domain;
3657: } else {
3658: $returnhash{$key}=$username.':'.$domain;
3659: }
1.351 www 3660: }
1.948 raeburn 3661: }
1.400 www 3662: return %returnhash;
3663: }
3664:
3665: sub get_my_roles {
1.937 raeburn 3666: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3667: unless (defined($uname)) { $uname=$env{'user.name'}; }
3668: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3669: my (%dumphash,%nothide);
1.1086 raeburn 3670: if ($context eq 'userroles') {
1.1166 raeburn 3671: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3672: } else {
3673: %dumphash=
1.400 www 3674: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3675: if ($hidepriv) {
3676: my %coursehash=&coursedescription($udom.'_'.$uname);
3677: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3678: if ($user !~ /:/) {
3679: $nothide{join(':',split(/[\@]/,$user))} = 1;
3680: } else {
3681: $nothide{$user} = 1;
3682: }
3683: }
3684: }
1.858 raeburn 3685: }
1.400 www 3686: my %returnhash=();
3687: my $now=time;
1.999 raeburn 3688: my %privileged;
1.800 albertel 3689: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3690: my ($role,$tend,$tstart);
3691: if ($context eq 'userroles') {
1.1149 raeburn 3692: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3693: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3694: } else {
3695: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3696: }
1.400 www 3697: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3698: my $status = 'active';
1.939 raeburn 3699: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3700: $status = 'previous';
3701: }
3702: if (($tstart) && ($now<$tstart)) {
3703: $status = 'future';
3704: }
3705: if (ref($types) eq 'ARRAY') {
3706: if (!grep(/^\Q$status\E$/,@{$types})) {
3707: next;
3708: }
3709: } else {
3710: if ($status ne 'active') {
3711: next;
3712: }
3713: }
1.867 raeburn 3714: my ($rolecode,$username,$domain,$section,$area);
3715: if ($context eq 'userroles') {
3716: ($area,$rolecode) = split(/_/,$entry);
3717: (undef,$domain,$username,$section) = split(/\//,$area);
3718: } else {
3719: ($role,$username,$domain,$section) = split(/\:/,$entry);
3720: }
1.832 raeburn 3721: if (ref($roledoms) eq 'ARRAY') {
3722: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3723: next;
3724: }
3725: }
3726: if (ref($roles) eq 'ARRAY') {
3727: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3728: if ($role =~ /^cr\//) {
3729: if (!grep(/^cr$/,@{$roles})) {
3730: next;
3731: }
1.1104 raeburn 3732: } elsif ($role =~ /^gr\//) {
3733: if (!grep(/^gr$/,@{$roles})) {
3734: next;
3735: }
1.922 raeburn 3736: } else {
3737: next;
3738: }
1.832 raeburn 3739: }
1.867 raeburn 3740: }
1.937 raeburn 3741: if ($hidepriv) {
1.999 raeburn 3742: if ($context eq 'userroles') {
3743: if ((&privileged($username,$domain)) &&
3744: (!$nothide{$username.':'.$domain})) {
3745: next;
3746: }
3747: } else {
3748: unless (ref($privileged{$domain}) eq 'HASH') {
3749: my %dompersonnel =
3750: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3751: $privileged{$domain} = {};
3752: if (keys(%dompersonnel)) {
3753: foreach my $server (keys(%dompersonnel)) {
3754: if (ref($dompersonnel{$server}) eq 'HASH') {
3755: foreach my $user (keys(%{$dompersonnel{$server}})) {
3756: my ($trole,$uname,$udom) = split(/:/,$user);
3757: $privileged{$udom}{$uname} = $trole;
3758: }
3759: }
3760: }
3761: }
3762: }
3763: if (exists($privileged{$domain}{$username})) {
3764: if (!$nothide{$username.':'.$domain}) {
3765: next;
3766: }
3767: }
1.937 raeburn 3768: }
3769: }
1.933 raeburn 3770: if ($withsec) {
3771: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3772: $tstart.':'.$tend;
3773: } else {
3774: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3775: }
1.832 raeburn 3776: }
1.373 www 3777: return %returnhash;
1.399 www 3778: }
3779:
3780: # ----------------------------------------------------- Frontpage Announcements
3781: #
3782: #
3783:
3784: sub postannounce {
3785: my ($server,$text)=@_;
1.844 albertel 3786: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3787: unless ($text=~/\w/) { $text=''; }
3788: return &reply('setannounce:'.&escape($text),$server);
3789: }
3790:
3791: sub getannounce {
1.448 albertel 3792:
3793: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3794: my $announcement='';
1.800 albertel 3795: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3796: close($fh);
1.399 www 3797: if ($announcement=~/\w/) {
3798: return
3799: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3800: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3801: } else {
3802: return '';
3803: }
3804: } else {
3805: return '';
3806: }
1.351 www 3807: }
1.353 www 3808:
3809: # ---------------------------------------------------------- Course ID routines
3810: # Deal with domain's nohist_courseid.db files
3811: #
3812:
3813: sub courseidput {
1.921 raeburn 3814: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3815: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3816: my $outcome;
3817: if ($caller eq 'timeonly') {
3818: my $cids = '';
3819: foreach my $item (keys(%$storehash)) {
3820: $cids.=&escape($item).'&';
3821: }
3822: $cids=~s/\&$//;
3823: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3824: $coursehome);
3825: } else {
3826: my $items = '';
3827: foreach my $item (keys(%$storehash)) {
3828: $items.= &escape($item).'='.
3829: &freeze_escape($$storehash{$item}).'&';
3830: }
3831: $items=~s/\&$//;
3832: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3833: $coursehome);
1.918 raeburn 3834: }
3835: if ($outcome eq 'unknown_cmd') {
3836: my $what;
3837: foreach my $cid (keys(%$storehash)) {
3838: $what .= &escape($cid).'=';
1.921 raeburn 3839: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3840: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3841: }
3842: $what =~ s/\:$/&/;
3843: }
3844: $what =~ s/\&$//;
3845: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3846: } else {
3847: return $outcome;
3848: }
1.353 www 3849: }
3850:
3851: sub courseiddump {
1.921 raeburn 3852: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3853: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3854: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3855: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3856: my $as_hash = 1;
3857: my %returnhash;
3858: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3859: my %libserv = &all_library();
3860: foreach my $tryserver (keys(%libserv)) {
3861: if ( ( $hostidflag == 1
3862: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3863: || (!defined($hostidflag)) ) {
3864:
1.918 raeburn 3865: if (($domfilter eq '') ||
3866: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 3867: my $rep;
3868: if (grep { $_ eq $tryserver } current_machine_ids()) {
3869: $rep = LONCAPA::Lond::dump_course_id_handler(
3870: join(":", (&host_domain($tryserver), $sincefilter,
3871: &escape($descfilter), &escape($instcodefilter),
3872: &escape($ownerfilter), &escape($coursefilter),
3873: &escape($typefilter), &escape($regexp_ok),
3874: $as_hash, &escape($selfenrollonly),
3875: &escape($catfilter), $showhidden, $caller,
3876: &escape($cloner), &escape($cc_clone), $cloneonly,
3877: &escape($createdbefore), &escape($createdafter),
3878: &escape($creationcontext), $domcloner)));
3879: } else {
3880: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
3881: $sincefilter.':'.&escape($descfilter).':'.
3882: &escape($instcodefilter).':'.&escape($ownerfilter).
3883: ':'.&escape($coursefilter).':'.&escape($typefilter).
3884: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3885: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3886: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3887: &escape($cc_clone).':'.$cloneonly.':'.
3888: &escape($createdbefore).':'.&escape($createdafter).':'.
3889: &escape($creationcontext).':'.$domcloner,
3890: $tryserver);
3891: }
3892:
1.918 raeburn 3893: my @pairs=split(/\&/,$rep);
3894: foreach my $item (@pairs) {
3895: my ($key,$value)=split(/\=/,$item,2);
3896: $key = &unescape($key);
3897: next if ($key =~ /^error: 2 /);
3898: my $result = &thaw_unescape($value);
3899: if (ref($result) eq 'HASH') {
3900: $returnhash{$key}=$result;
3901: } else {
1.921 raeburn 3902: my @responses = split(/:/,$value);
3903: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3904: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3905: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3906: }
1.1008 raeburn 3907: }
1.353 www 3908: }
3909: }
3910: }
3911: }
3912: return %returnhash;
3913: }
3914:
1.1055 raeburn 3915: sub courselastaccess {
3916: my ($cdom,$cnum,$hostidref) = @_;
3917: my %returnhash;
3918: if ($cdom && $cnum) {
3919: my $chome = &homeserver($cnum,$cdom);
3920: if ($chome ne 'no_host') {
3921: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3922: &extract_lastaccess(\%returnhash,$rep);
3923: }
3924: } else {
3925: if (!$cdom) { $cdom=''; }
3926: my %libserv = &all_library();
3927: foreach my $tryserver (keys(%libserv)) {
3928: if (ref($hostidref) eq 'ARRAY') {
3929: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3930: }
3931: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3932: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3933: &extract_lastaccess(\%returnhash,$rep);
3934: }
3935: }
3936: }
3937: return %returnhash;
3938: }
3939:
3940: sub extract_lastaccess {
3941: my ($returnhash,$rep) = @_;
3942: if (ref($returnhash) eq 'HASH') {
3943: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3944: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3945: $rep eq '') {
3946: my @pairs=split(/\&/,$rep);
3947: foreach my $item (@pairs) {
3948: my ($key,$value)=split(/\=/,$item,2);
3949: $key = &unescape($key);
3950: next if ($key =~ /^error: 2 /);
3951: $returnhash->{$key} = &thaw_unescape($value);
3952: }
3953: }
3954: }
3955: return;
3956: }
3957:
1.658 raeburn 3958: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3959:
3960: sub dcmailput {
1.685 raeburn 3961: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3962: my $status = &Apache::lonnet::critical(
1.740 www 3963: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3964: &escape($message),$server);
1.662 raeburn 3965: return $status;
3966: }
3967:
1.658 raeburn 3968: sub dcmaildump {
3969: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3970: my %returnhash=();
1.846 albertel 3971:
3972: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3973: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3974: &escape($enddate).':';
3975: my @esc_senders=map { &escape($_)} @$senders;
3976: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3977: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3978: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3979: if (($key) && ($value)) {
3980: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3981: }
3982: }
3983: }
3984: return %returnhash;
3985: }
1.662 raeburn 3986: # ---------------------------------------------------------- Domain roles
3987:
3988: sub get_domain_roles {
3989: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3990: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3991: $startdate = '.';
3992: }
1.1018 raeburn 3993: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3994: $enddate = '.';
3995: }
1.922 raeburn 3996: my $rolelist;
3997: if (ref($roles) eq 'ARRAY') {
3998: $rolelist = join(':',@{$roles});
3999: }
1.662 raeburn 4000: my %personnel = ();
1.841 albertel 4001:
4002: my %servers = &get_servers($dom,'library');
4003: foreach my $tryserver (keys(%servers)) {
4004: %{$personnel{$tryserver}}=();
4005: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4006: &escape($startdate).':'.
4007: &escape($enddate).':'.
4008: &escape($rolelist), $tryserver))) {
4009: my ($key,$value) = split(/\=/,$line,2);
4010: if (($key) && ($value)) {
4011: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4012: }
4013: }
1.662 raeburn 4014: }
4015: return %personnel;
4016: }
1.658 raeburn 4017:
1.1057 www 4018: # ----------------------------------------------------------- Interval timing
1.149 www 4019:
1.1153 www 4020: {
4021: # Caches needed for speedup of navmaps
4022: # We don't want to cache this for very long at all (5 seconds at most)
4023: #
4024: # The user for whom we cache
4025: my $cachedkey='';
4026: # The cached times for this user
4027: my %cachedtimes=();
4028: # When this was last done
4029: my $cachedtime=();
4030:
4031: sub load_all_first_access {
1.1154 raeburn 4032: my ($uname,$udom)=@_;
1.1156 www 4033: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4034: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4035: return;
4036: }
4037: $cachedtime=time;
4038: $cachedkey=$uname.':'.$udom;
4039: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4040: }
4041:
1.504 albertel 4042: sub get_first_access {
1.1162 raeburn 4043: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4044: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4045: if ($argsymb) { $symb=$argsymb; }
4046: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4047: if ($argmap) { $map = $argmap; }
1.926 albertel 4048: if ($type eq 'course') {
4049: $res='course';
4050: } elsif ($type eq 'map') {
1.588 albertel 4051: $res=&symbread($map);
4052: } else {
4053: $res=$symb;
4054: }
1.1153 www 4055: &load_all_first_access($uname,$udom);
4056: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4057: }
4058:
4059: sub set_first_access {
1.1162 raeburn 4060: my ($type,$interval)=@_;
1.790 albertel 4061: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4062: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4063: if ($type eq 'course') {
4064: $res='course';
4065: } elsif ($type eq 'map') {
1.588 albertel 4066: $res=&symbread($map);
4067: } else {
4068: $res=$symb;
4069: }
1.1153 www 4070: $cachedkey='';
1.1162 raeburn 4071: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4072: if (!$firstaccess) {
1.1162 raeburn 4073: my $start = time;
4074: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4075: $udom,$uname);
4076: if ($putres eq 'ok') {
4077: &put('timerinterval',{"$courseid\0$res"=>$interval},
4078: $udom,$uname);
4079: &appenv(
4080: {
4081: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4082: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4083: }
4084: );
4085: }
4086: return $putres;
1.505 albertel 4087: }
4088: return 'already_set';
1.504 albertel 4089: }
1.1153 www 4090: }
1.110 www 4091: # --------------------------------------------- Set Expire Date for Spreadsheet
4092:
4093: sub expirespread {
4094: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4095: my $cid=$env{'request.course.id'};
1.110 www 4096: if ($cid) {
4097: my $now=time;
4098: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4099: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4100: $env{'course.'.$cid.'.num'}.
1.110 www 4101: ':nohist_expirationdates:'.
4102: &escape($key).'='.$now,
1.620 albertel 4103: $env{'course.'.$cid.'.home'})
1.110 www 4104: }
4105: return 'ok';
1.14 www 4106: }
4107:
1.109 www 4108: # ----------------------------------------------------- Devalidate Spreadsheets
4109:
4110: sub devalidate {
1.325 www 4111: my ($symb,$uname,$udom)=@_;
1.620 albertel 4112: my $cid=$env{'request.course.id'};
1.109 www 4113: if ($cid) {
1.391 matthew 4114: # delete the stored spreadsheets for
4115: # - the student level sheet of this user in course's homespace
4116: # - the assessment level sheet for this resource
4117: # for this user in user's homespace
1.553 albertel 4118: # - current conditional state info
1.325 www 4119: my $key=$uname.':'.$udom.':';
1.109 www 4120: my $status=
1.299 matthew 4121: &del('nohist_calculatedsheets',
1.391 matthew 4122: [$key.'studentcalc:'],
1.620 albertel 4123: $env{'course.'.$cid.'.domain'},
4124: $env{'course.'.$cid.'.num'})
1.133 albertel 4125: .' '.
4126: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4127: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4128: unless ($status eq 'ok ok') {
4129: &logthis('Could not devalidate spreadsheet '.
1.325 www 4130: $uname.' at '.$udom.' for '.
1.109 www 4131: $symb.': '.$status);
1.133 albertel 4132: }
1.553 albertel 4133: &delenv('user.state.'.$cid);
1.109 www 4134: }
4135: }
4136:
1.265 albertel 4137: sub get_scalar {
4138: my ($string,$end) = @_;
4139: my $value;
4140: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4141: $value = $1;
4142: } elsif ($$string =~ s/^([^&]*?)&//) {
4143: $value = $1;
4144: }
4145: return &unescape($value);
4146: }
4147:
4148: sub array2str {
4149: my (@array) = @_;
4150: my $result=&arrayref2str(\@array);
4151: $result=~s/^__ARRAY_REF__//;
4152: $result=~s/__END_ARRAY_REF__$//;
4153: return $result;
4154: }
4155:
1.204 albertel 4156: sub arrayref2str {
4157: my ($arrayref) = @_;
1.265 albertel 4158: my $result='__ARRAY_REF__';
1.204 albertel 4159: foreach my $elem (@$arrayref) {
1.265 albertel 4160: if(ref($elem) eq 'ARRAY') {
4161: $result.=&arrayref2str($elem).'&';
4162: } elsif(ref($elem) eq 'HASH') {
4163: $result.=&hashref2str($elem).'&';
4164: } elsif(ref($elem)) {
4165: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4166: } else {
4167: $result.=&escape($elem).'&';
4168: }
4169: }
4170: $result=~s/\&$//;
1.265 albertel 4171: $result .= '__END_ARRAY_REF__';
1.204 albertel 4172: return $result;
4173: }
4174:
1.168 albertel 4175: sub hash2str {
1.204 albertel 4176: my (%hash) = @_;
4177: my $result=&hashref2str(\%hash);
1.265 albertel 4178: $result=~s/^__HASH_REF__//;
4179: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4180: return $result;
4181: }
4182:
4183: sub hashref2str {
4184: my ($hashref)=@_;
1.265 albertel 4185: my $result='__HASH_REF__';
1.800 albertel 4186: foreach my $key (sort(keys(%$hashref))) {
4187: if (ref($key) eq 'ARRAY') {
4188: $result.=&arrayref2str($key).'=';
4189: } elsif (ref($key) eq 'HASH') {
4190: $result.=&hashref2str($key).'=';
4191: } elsif (ref($key)) {
1.265 albertel 4192: $result.='=';
1.800 albertel 4193: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4194: } else {
1.1132 raeburn 4195: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4196: }
4197:
1.800 albertel 4198: if(ref($hashref->{$key}) eq 'ARRAY') {
4199: $result.=&arrayref2str($hashref->{$key}).'&';
4200: } elsif(ref($hashref->{$key}) eq 'HASH') {
4201: $result.=&hashref2str($hashref->{$key}).'&';
4202: } elsif(ref($hashref->{$key})) {
1.265 albertel 4203: $result.='&';
1.800 albertel 4204: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4205: } else {
1.800 albertel 4206: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4207: }
4208: }
1.168 albertel 4209: $result=~s/\&$//;
1.265 albertel 4210: $result .= '__END_HASH_REF__';
1.168 albertel 4211: return $result;
4212: }
4213:
4214: sub str2hash {
1.265 albertel 4215: my ($string)=@_;
4216: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4217: return %$hash;
4218: }
4219:
4220: sub str2hashref {
1.168 albertel 4221: my ($string) = @_;
1.265 albertel 4222:
4223: my %hash;
4224:
4225: if($string !~ /^__HASH_REF__/) {
4226: if (! ($string eq '' || !defined($string))) {
4227: $hash{'error'}='Not hash reference';
4228: }
4229: return (\%hash, $string);
4230: }
4231:
4232: $string =~ s/^__HASH_REF__//;
4233:
4234: while($string !~ /^__END_HASH_REF__/) {
4235: #key
4236: my $key='';
4237: if($string =~ /^__HASH_REF__/) {
4238: ($key, $string)=&str2hashref($string);
4239: if(defined($key->{'error'})) {
4240: $hash{'error'}='Bad data';
4241: return (\%hash, $string);
4242: }
4243: } elsif($string =~ /^__ARRAY_REF__/) {
4244: ($key, $string)=&str2arrayref($string);
4245: if($key->[0] eq 'Array reference error') {
4246: $hash{'error'}='Bad data';
4247: return (\%hash, $string);
4248: }
4249: } else {
4250: $string =~ s/^(.*?)=//;
1.267 albertel 4251: $key=&unescape($1);
1.265 albertel 4252: }
4253: $string =~ s/^=//;
4254:
4255: #value
4256: my $value='';
4257: if($string =~ /^__HASH_REF__/) {
4258: ($value, $string)=&str2hashref($string);
4259: if(defined($value->{'error'})) {
4260: $hash{'error'}='Bad data';
4261: return (\%hash, $string);
4262: }
4263: } elsif($string =~ /^__ARRAY_REF__/) {
4264: ($value, $string)=&str2arrayref($string);
4265: if($value->[0] eq 'Array reference error') {
4266: $hash{'error'}='Bad data';
4267: return (\%hash, $string);
4268: }
4269: } else {
4270: $value=&get_scalar(\$string,'__END_HASH_REF__');
4271: }
4272: $string =~ s/^&//;
4273:
4274: $hash{$key}=$value;
1.204 albertel 4275: }
1.265 albertel 4276:
4277: $string =~ s/^__END_HASH_REF__//;
4278:
4279: return (\%hash, $string);
1.204 albertel 4280: }
4281:
4282: sub str2array {
1.265 albertel 4283: my ($string)=@_;
4284: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4285: return @$array;
4286: }
4287:
4288: sub str2arrayref {
1.204 albertel 4289: my ($string) = @_;
1.265 albertel 4290: my @array;
4291:
4292: if($string !~ /^__ARRAY_REF__/) {
4293: if (! ($string eq '' || !defined($string))) {
4294: $array[0]='Array reference error';
4295: }
4296: return (\@array, $string);
4297: }
4298:
4299: $string =~ s/^__ARRAY_REF__//;
4300:
4301: while($string !~ /^__END_ARRAY_REF__/) {
4302: my $value='';
4303: if($string =~ /^__HASH_REF__/) {
4304: ($value, $string)=&str2hashref($string);
4305: if(defined($value->{'error'})) {
4306: $array[0] ='Array reference error';
4307: return (\@array, $string);
4308: }
4309: } elsif($string =~ /^__ARRAY_REF__/) {
4310: ($value, $string)=&str2arrayref($string);
4311: if($value->[0] eq 'Array reference error') {
4312: $array[0] ='Array reference error';
4313: return (\@array, $string);
4314: }
4315: } else {
4316: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4317: }
4318: $string =~ s/^&//;
4319:
4320: push(@array, $value);
1.191 harris41 4321: }
1.265 albertel 4322:
4323: $string =~ s/^__END_ARRAY_REF__//;
4324:
4325: return (\@array, $string);
1.168 albertel 4326: }
4327:
1.167 albertel 4328: # -------------------------------------------------------------------Temp Store
4329:
1.168 albertel 4330: sub tmpreset {
4331: my ($symb,$namespace,$domain,$stuname) = @_;
4332: if (!$symb) {
4333: $symb=&symbread();
1.620 albertel 4334: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4335: }
4336: $symb=escape($symb);
4337:
1.620 albertel 4338: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4339: $namespace=~s/\//\_/g;
4340: $namespace=~s/\W//g;
4341:
1.620 albertel 4342: if (!$domain) { $domain=$env{'user.domain'}; }
4343: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4344: if ($domain eq 'public' && $stuname eq 'public') {
4345: $stuname=$ENV{'REMOTE_ADDR'};
4346: }
1.1117 foxr 4347: my $path=LONCAPA::tempdir();
1.168 albertel 4348: my %hash;
4349: if (tie(%hash,'GDBM_File',
4350: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4351: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4352: foreach my $key (keys(%hash)) {
1.180 albertel 4353: if ($key=~ /:$symb/) {
1.168 albertel 4354: delete($hash{$key});
4355: }
4356: }
4357: }
4358: }
4359:
1.167 albertel 4360: sub tmpstore {
1.168 albertel 4361: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4362:
4363: if (!$symb) {
4364: $symb=&symbread();
1.620 albertel 4365: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4366: }
4367: $symb=escape($symb);
4368:
4369: if (!$namespace) {
4370: # I don't think we would ever want to store this for a course.
4371: # it seems this will only be used if we don't have a course.
1.620 albertel 4372: #$namespace=$env{'request.course.id'};
1.168 albertel 4373: #if (!$namespace) {
1.620 albertel 4374: $namespace=$env{'request.state'};
1.168 albertel 4375: #}
4376: }
4377: $namespace=~s/\//\_/g;
4378: $namespace=~s/\W//g;
1.620 albertel 4379: if (!$domain) { $domain=$env{'user.domain'}; }
4380: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4381: if ($domain eq 'public' && $stuname eq 'public') {
4382: $stuname=$ENV{'REMOTE_ADDR'};
4383: }
1.168 albertel 4384: my $now=time;
4385: my %hash;
1.1117 foxr 4386: my $path=LONCAPA::tempdir();
1.168 albertel 4387: if (tie(%hash,'GDBM_File',
4388: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4389: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4390: $hash{"version:$symb"}++;
4391: my $version=$hash{"version:$symb"};
4392: my $allkeys='';
4393: foreach my $key (keys(%$storehash)) {
4394: $allkeys.=$key.':';
1.591 albertel 4395: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4396: }
4397: $hash{"$version:$symb:timestamp"}=$now;
4398: $allkeys.='timestamp';
4399: $hash{"$version:keys:$symb"}=$allkeys;
4400: if (untie(%hash)) {
4401: return 'ok';
4402: } else {
4403: return "error:$!";
4404: }
4405: } else {
4406: return "error:$!";
4407: }
4408: }
1.167 albertel 4409:
1.168 albertel 4410: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4411:
1.168 albertel 4412: sub tmprestore {
4413: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4414:
1.168 albertel 4415: if (!$symb) {
4416: $symb=&symbread();
1.620 albertel 4417: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4418: }
4419: $symb=escape($symb);
4420:
1.620 albertel 4421: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4422:
1.620 albertel 4423: if (!$domain) { $domain=$env{'user.domain'}; }
4424: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4425: if ($domain eq 'public' && $stuname eq 'public') {
4426: $stuname=$ENV{'REMOTE_ADDR'};
4427: }
1.168 albertel 4428: my %returnhash;
4429: $namespace=~s/\//\_/g;
4430: $namespace=~s/\W//g;
4431: my %hash;
1.1117 foxr 4432: my $path=LONCAPA::tempdir();
1.168 albertel 4433: if (tie(%hash,'GDBM_File',
4434: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4435: &GDBM_READER(),0640)) {
1.168 albertel 4436: my $version=$hash{"version:$symb"};
4437: $returnhash{'version'}=$version;
4438: my $scope;
4439: for ($scope=1;$scope<=$version;$scope++) {
4440: my $vkeys=$hash{"$scope:keys:$symb"};
4441: my @keys=split(/:/,$vkeys);
4442: my $key;
4443: $returnhash{"$scope:keys"}=$vkeys;
4444: foreach $key (@keys) {
1.591 albertel 4445: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4446: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4447: }
4448: }
1.168 albertel 4449: if (!(untie(%hash))) {
4450: return "error:$!";
4451: }
4452: } else {
4453: return "error:$!";
4454: }
4455: return %returnhash;
1.167 albertel 4456: }
4457:
1.9 www 4458: # ----------------------------------------------------------------------- Store
4459:
4460: sub store {
1.124 www 4461: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4462: my $home='';
4463:
1.168 albertel 4464: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4465:
1.213 www 4466: $symb=&symbclean($symb);
1.122 albertel 4467: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4468:
1.620 albertel 4469: if (!$domain) { $domain=$env{'user.domain'}; }
4470: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4471:
4472: &devalidate($symb,$stuname,$domain);
1.109 www 4473:
4474: $symb=escape($symb);
1.187 www 4475: if (!$namespace) {
1.620 albertel 4476: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4477: return '';
4478: }
4479: }
1.620 albertel 4480: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4481:
4482: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4483: $$storehash{'host'}=$perlvar{'lonHostID'};
4484:
1.12 www 4485: my $namevalue='';
1.800 albertel 4486: foreach my $key (keys(%$storehash)) {
4487: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4488: }
1.12 www 4489: $namevalue=~s/\&$//;
1.187 www 4490: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4491: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4492: }
4493:
1.47 www 4494: # -------------------------------------------------------------- Critical Store
4495:
4496: sub cstore {
1.124 www 4497: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4498: my $home='';
4499:
1.168 albertel 4500: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4501:
1.213 www 4502: $symb=&symbclean($symb);
1.122 albertel 4503: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4504:
1.620 albertel 4505: if (!$domain) { $domain=$env{'user.domain'}; }
4506: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4507:
4508: &devalidate($symb,$stuname,$domain);
1.109 www 4509:
4510: $symb=escape($symb);
1.187 www 4511: if (!$namespace) {
1.620 albertel 4512: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4513: return '';
4514: }
4515: }
1.620 albertel 4516: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4517:
4518: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4519: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4520:
1.47 www 4521: my $namevalue='';
1.800 albertel 4522: foreach my $key (keys(%$storehash)) {
4523: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4524: }
1.47 www 4525: $namevalue=~s/\&$//;
1.187 www 4526: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4527: return critical
4528: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4529: }
4530:
1.9 www 4531: # --------------------------------------------------------------------- Restore
4532:
4533: sub restore {
1.124 www 4534: my ($symb,$namespace,$domain,$stuname) = @_;
4535: my $home='';
4536:
1.168 albertel 4537: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4538:
1.122 albertel 4539: if (!$symb) {
4540: unless ($symb=escape(&symbread())) { return ''; }
4541: } else {
1.213 www 4542: $symb=&escape(&symbclean($symb));
1.122 albertel 4543: }
1.188 www 4544: if (!$namespace) {
1.620 albertel 4545: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4546: return '';
4547: }
4548: }
1.620 albertel 4549: if (!$domain) { $domain=$env{'user.domain'}; }
4550: if (!$stuname) { $stuname=$env{'user.name'}; }
4551: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4552: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4553:
1.12 www 4554: my %returnhash=();
1.800 albertel 4555: foreach my $line (split(/\&/,$answer)) {
4556: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4557: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4558: }
1.75 www 4559: my $version;
4560: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4561: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4562: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4563: }
1.75 www 4564: }
1.13 www 4565: return %returnhash;
1.34 www 4566: }
4567:
4568: # ---------------------------------------------------------- Course Description
1.1118 foxr 4569: #
4570: #
1.34 www 4571:
4572: sub coursedescription {
1.731 albertel 4573: my ($courseid,$args)=@_;
1.34 www 4574: $courseid=~s/^\///;
1.49 www 4575: $courseid=~s/\_/\//g;
1.34 www 4576: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4577: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4578: my $normalid=$cdomain.'_'.$cnum;
4579: # need to always cache even if we get errors otherwise we keep
4580: # trying and trying and trying to get the course description.
4581: my %envhash=();
4582: my %returnhash=();
1.731 albertel 4583:
4584: my $expiretime=600;
4585: if ($env{'request.course.id'} eq $normalid) {
4586: $expiretime=120;
4587: }
4588:
4589: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4590: if (!$args->{'freshen_cache'}
4591: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4592: foreach my $key (keys(%env)) {
4593: next if ($key !~ /^\Q$prefix\E(.*)/);
4594: my ($setting) = $1;
4595: $returnhash{$setting} = $env{$key};
4596: }
4597: return %returnhash;
4598: }
4599:
1.1118 foxr 4600: # get the data again
4601:
1.731 albertel 4602: if (!$args->{'one_time'}) {
4603: $envhash{'course.'.$normalid.'.last_cache'}=time;
4604: }
1.811 albertel 4605:
1.34 www 4606: if ($chome ne 'no_host') {
1.302 albertel 4607: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4608: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4609: my $username = $env{'user.name'}; # Defult username
4610: if(defined $args->{'user'}) {
4611: $username = $args->{'user'};
4612: }
1.129 albertel 4613: $returnhash{'home'}= $chome;
4614: $returnhash{'domain'} = $cdomain;
4615: $returnhash{'num'} = $cnum;
1.741 raeburn 4616: if (!defined($returnhash{'type'})) {
4617: $returnhash{'type'} = 'Course';
4618: }
1.130 albertel 4619: while (my ($name,$value) = each %returnhash) {
1.53 www 4620: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4621: }
1.270 www 4622: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4623: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4624: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4625: $envhash{'course.'.$normalid.'.home'}=$chome;
4626: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4627: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4628: }
4629: }
1.731 albertel 4630: if (!$args->{'one_time'}) {
1.949 raeburn 4631: &appenv(\%envhash);
1.731 albertel 4632: }
1.302 albertel 4633: return %returnhash;
1.461 www 4634: }
4635:
1.1080 raeburn 4636: sub update_released_required {
4637: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4638: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4639: $cid = $env{'request.course.id'};
4640: $cdom = $env{'course.'.$cid.'.domain'};
4641: $cnum = $env{'course.'.$cid.'.num'};
4642: $chome = $env{'course.'.$cid.'.home'};
4643: }
4644: if ($needsrelease) {
4645: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4646: my $needsupdate;
4647: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4648: $needsupdate = 1;
4649: } else {
4650: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4651: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4652: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4653: $needsupdate = 1;
4654: }
4655: }
4656: if ($needsupdate) {
4657: my %needshash = (
4658: 'internal.releaserequired' => $needsrelease,
4659: );
4660: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4661: if ($putresult eq 'ok') {
4662: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4663: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4664: if (ref($crsinfo{$cid}) eq 'HASH') {
4665: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4666: &courseidput($cdom,\%crsinfo,$chome,'notime');
4667: }
4668: }
4669: }
4670: }
4671: return;
4672: }
4673:
1.461 www 4674: # -------------------------------------------------See if a user is privileged
4675:
4676: sub privileged {
4677: my ($username,$domain)=@_;
1.1170 droeschl 4678:
4679: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4680: my $now = time;
4681:
4682: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4683: my ($trole, $tend, $tstart) = split(/_/, $role);
4684: if (($trole eq 'dc') || ($trole eq 'su')) {
4685: return 1 unless ($tend && $tend < $now)
4686: or ($tstart && $tstart > $now);
4687: }
1.461 www 4688: }
1.1170 droeschl 4689:
1.461 www 4690: return 0;
1.9 www 4691: }
1.1 albertel 4692:
1.103 harris41 4693: # -------------------------------------------------------- Get user privileges
1.11 www 4694:
4695: sub rolesinit {
1.1169 droeschl 4696: my ($domain, $username) = @_;
4697: my %userroles = ('user.login.time' => time);
4698: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4699:
4700: # firstaccess and timerinterval are related to timed maps/resources.
4701: # also, blocking can be triggered by an activating timer
4702: # it's saved in the user's %env.
4703: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4704: my %timerinterval = &dump('timerinterval', $domain, $username);
4705: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4706: %timerintchk, %timerintenv);
4707:
1.1162 raeburn 4708: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 4709: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 4710: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4711: }
1.1169 droeschl 4712:
1.1162 raeburn 4713: foreach my $key (keys(%timerinterval)) {
4714: my ($cid,$rest) = split(/\0/,$key);
4715: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4716: }
1.1169 droeschl 4717:
1.11 www 4718: my %allroles=();
1.1162 raeburn 4719: my %allgroups=();
1.11 www 4720:
1.1169 droeschl 4721: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4722: my $role = $rolesdump{$area};
4723: $area =~ s/\_\w\w$//;
4724:
4725: my ($trole, $tend, $tstart, $group_privs);
4726:
4727: if ($role =~ /^cr/) {
4728: # Custom role, defined by a user
4729: # e.g., user.role.cr/msu/smith/mynewrole
4730: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4731: $trole = $1;
4732: ($tend, $tstart) = split('_', $2);
4733: } else {
4734: $trole = $role;
4735: }
4736: } elsif ($role =~ m|^gr/|) {
4737: # Role of member in a group, defined within a course/community
4738: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
4739: ($trole, $tend, $tstart) = split(/_/, $role);
4740: next if $tstart eq '-1';
4741: ($trole, $group_privs) = split(/\//, $trole);
4742: $group_privs = &unescape($group_privs);
4743: } else {
4744: # Just a normal role, defined in roles.tab
4745: ($trole, $tend, $tstart) = split(/_/,$role);
4746: }
4747:
4748: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4749: $username);
4750: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4751:
4752: # role expired or not available yet?
4753: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
4754: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
4755:
4756: next if $area eq '' or $trole eq '';
4757:
4758: my $spec = "$trole.$area";
4759: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
4760:
4761: if ($trole =~ /^cr\//) {
4762: # Custom role, defined by a user
4763: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4764: } elsif ($trole eq 'gr') {
4765: # Role of a member in a group, defined within a course/community
4766: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4767: next;
4768: } else {
4769: # Normal role, defined in roles.tab
4770: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4771: }
4772:
4773: my $cid = $tdomain.'_'.$trest;
4774: unless ($firstaccchk{$cid}) {
4775: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4776: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4777: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4778: $coursetimerstarts{$cid}{$item};
4779: }
4780: }
4781: $firstaccchk{$cid} = 1;
4782: }
4783: unless ($timerintchk{$cid}) {
4784: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4785: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4786: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4787: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 4788: }
1.12 www 4789: }
1.1169 droeschl 4790: $timerintchk{$cid} = 1;
1.191 harris41 4791: }
1.11 www 4792: }
1.1169 droeschl 4793:
4794: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
4795: \%allroles, \%allgroups);
4796: $env{'user.adv'} = $userroles{'user.adv'};
4797:
1.1162 raeburn 4798: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4799: }
4800:
1.567 raeburn 4801: sub set_arearole {
4802: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4803: # log the associated role with the area
4804: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4805: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4806: }
4807:
4808: sub custom_roleprivs {
4809: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4810: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4811: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4812: if (&hostname($homsvr) ne '') {
1.567 raeburn 4813: my ($rdummy,$roledef)=
4814: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4815: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4816: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4817: if (defined($syspriv)) {
1.1043 raeburn 4818: if ($trest =~ /^$match_community$/) {
4819: $syspriv =~ s/bre\&S//;
4820: }
1.567 raeburn 4821: $$allroles{'cm./'}.=':'.$syspriv;
4822: $$allroles{$spec.'./'}.=':'.$syspriv;
4823: }
4824: if ($tdomain ne '') {
4825: if (defined($dompriv)) {
4826: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4827: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4828: }
4829: if (($trest ne '') && (defined($coursepriv))) {
4830: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4831: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4832: }
4833: }
4834: }
4835: }
4836: }
4837:
1.678 raeburn 4838: sub group_roleprivs {
4839: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4840: my $access = 1;
4841: my $now = time;
4842: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4843: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4844: if ($access) {
1.811 albertel 4845: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4846: $$allgroups{$course}{$group} .=':'.$group_privs;
4847: }
4848: }
1.567 raeburn 4849:
4850: sub standard_roleprivs {
4851: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4852: if (defined($pr{$trole.':s'})) {
4853: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4854: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4855: }
4856: if ($tdomain ne '') {
4857: if (defined($pr{$trole.':d'})) {
4858: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4859: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4860: }
4861: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4862: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4863: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4864: }
4865: }
4866: }
4867:
4868: sub set_userprivs {
1.1064 raeburn 4869: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4870: my $author=0;
4871: my $adv=0;
1.678 raeburn 4872: my %grouproles = ();
4873: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4874: my @groupkeys;
1.1000 raeburn 4875: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4876: push(@groupkeys,$role);
4877: }
4878: if (ref($groups_roles) eq 'HASH') {
4879: foreach my $key (keys(%{$groups_roles})) {
4880: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4881: push(@groupkeys,$key);
4882: }
4883: }
4884: }
4885: if (@groupkeys > 0) {
4886: foreach my $role (@groupkeys) {
4887: my ($trole,$area,$sec,$extendedarea);
4888: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4889: $trole = $1;
4890: $area = $2;
4891: $sec = $3;
4892: $extendedarea = $area.$sec;
4893: if (exists($$allgroups{$area})) {
4894: foreach my $group (keys(%{$$allgroups{$area}})) {
4895: my $spec = $trole.'.'.$extendedarea;
4896: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4897: $$allgroups{$area}{$group};
1.1064 raeburn 4898: }
1.678 raeburn 4899: }
4900: }
4901: }
4902: }
4903: }
1.800 albertel 4904: foreach my $group (keys(%grouproles)) {
4905: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4906: }
1.800 albertel 4907: foreach my $role (keys(%{$allroles})) {
4908: my %thesepriv;
1.941 raeburn 4909: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4910: foreach my $item (split(/:/,$$allroles{$role})) {
4911: if ($item ne '') {
4912: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4913: if ($restrictions eq '') {
4914: $thesepriv{$privilege}='F';
4915: } elsif ($thesepriv{$privilege} ne 'F') {
4916: $thesepriv{$privilege}.=$restrictions;
4917: }
4918: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4919: }
4920: }
4921: my $thesestr='';
1.1104 raeburn 4922: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4923: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4924: }
4925: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4926: }
4927: return ($author,$adv);
4928: }
4929:
1.994 raeburn 4930: sub role_status {
1.1104 raeburn 4931: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4932: my @pwhere = ();
4933: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4934: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4935: unless (!defined($$role) || $$role eq '') {
4936: $$where=join('.',@pwhere);
4937: $$trolecode=$$role.'.'.$$where;
4938: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4939: $$tstatus='is';
1.1104 raeburn 4940: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4941: $$tstatus='future';
1.1034 raeburn 4942: if ($$tstart<$now) {
4943: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4944: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4945: my (%allroles,%allgroups,$group_privs,
4946: %groups_roles,@rolecodes);
1.1002 raeburn 4947: my %userroles = (
4948: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4949: );
1.1064 raeburn 4950: @rolecodes = ('cm');
1.1002 raeburn 4951: my $spec=$$role.'.'.$$where;
4952: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4953: if ($$role =~ /^cr\//) {
4954: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4955: push(@rolecodes,'cr');
1.1002 raeburn 4956: } elsif ($$role eq 'gr') {
1.1064 raeburn 4957: push(@rolecodes,$$role);
1.1002 raeburn 4958: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4959: $env{'user.name'});
1.1064 raeburn 4960: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4961: (undef,my $group_privs) = split(/\//,$trole);
4962: $group_privs = &unescape($group_privs);
4963: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4964: 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 4965: &get_groups_roles($tdomain,$trest,
4966: \%course_roles,\@rolecodes,
4967: \%groups_roles);
1.1002 raeburn 4968: } else {
1.1064 raeburn 4969: push(@rolecodes,$$role);
1.1002 raeburn 4970: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4971: }
1.1064 raeburn 4972: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4973: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4974: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4975: }
4976: }
1.1034 raeburn 4977: $$tstatus = 'is';
1.1002 raeburn 4978: }
1.994 raeburn 4979: }
4980: if ($$tend) {
1.1104 raeburn 4981: if ($$tend<$update) {
1.994 raeburn 4982: $$tstatus='expired';
4983: } elsif ($$tend<$now) {
4984: $$tstatus='will_not';
4985: }
4986: }
4987: }
4988: }
4989: }
4990:
1.1104 raeburn 4991: sub get_groups_roles {
4992: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4993: return unless((ref($cdom_courseroles) eq 'HASH') &&
4994: (ref($rolecodes) eq 'ARRAY') &&
4995: (ref($groups_roles) eq 'HASH'));
4996: if (keys(%{$cdom_courseroles}) > 0) {
4997: my ($cnum) = ($rest =~ /^($match_courseid)/);
4998: if ($cdom ne '' && $cnum ne '') {
4999: foreach my $key (keys(%{$cdom_courseroles})) {
5000: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5001: my $crsrole = $1;
5002: my $crssec = $2;
5003: if ($crsrole =~ /^cr/) {
5004: unless (grep(/^cr$/,@{$rolecodes})) {
5005: push(@{$rolecodes},'cr');
5006: }
5007: } else {
5008: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5009: push(@{$rolecodes},$crsrole);
5010: }
5011: }
5012: my $rolekey = "$crsrole./$cdom/$cnum";
5013: if ($crssec ne '') {
5014: $rolekey .= "/$crssec";
5015: }
5016: $rolekey .= './';
5017: $groups_roles->{$rolekey} = $rolecodes;
5018: }
5019: }
5020: }
5021: }
5022: return;
5023: }
5024:
5025: sub delete_env_groupprivs {
5026: my ($where,$courseroles,$possroles) = @_;
5027: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5028: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5029: unless (ref($courseroles->{$udom}) eq 'HASH') {
5030: %{$courseroles->{$udom}} =
5031: &get_my_roles('','','userroles',['active'],
5032: $possroles,[$udom],1);
5033: }
5034: if (ref($courseroles->{$udom}) eq 'HASH') {
5035: foreach my $item (keys(%{$courseroles->{$udom}})) {
5036: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5037: my $area = '/'.$cdom.'/'.$cnum;
5038: my $privkey = "user.priv.$crsrole.$area";
5039: if ($crssec ne '') {
5040: $privkey .= '/'.$crssec;
5041: }
5042: $privkey .= ".$area/$group";
5043: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5044: }
5045: }
5046: return;
5047: }
5048:
1.994 raeburn 5049: sub check_adhoc_privs {
1.1104 raeburn 5050: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5051: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
5052: if ($env{$cckey}) {
5053: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5054: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5055: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5056: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 5057: }
5058: } else {
1.1088 raeburn 5059: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 5060: }
5061: }
5062:
5063: sub set_adhoc_privileges {
5064: # role can be cc or ca
1.1088 raeburn 5065: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5066: my $area = '/'.$dcdom.'/'.$pickedcourse;
5067: my $spec = $role.'.'.$area;
5068: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5069: $env{'user.name'});
5070: my %ccrole = ();
5071: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5072: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5073: &appenv(\%userroles,[$role,'cm']);
5074: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5075: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5076: &appenv( {'request.role' => $spec,
5077: 'request.role.domain' => $dcdom,
5078: 'request.course.sec' => ''
5079: }
5080: );
5081: my $tadv=0;
5082: if (&allowed('adv') eq 'F') { $tadv=1; }
5083: &appenv({'request.role.adv' => $tadv});
5084: }
1.994 raeburn 5085: }
5086:
1.12 www 5087: # --------------------------------------------------------------- get interface
5088:
5089: sub get {
1.131 albertel 5090: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5091: my $items='';
1.800 albertel 5092: foreach my $item (@$storearr) {
5093: $items.=&escape($item).'&';
1.191 harris41 5094: }
1.12 www 5095: $items=~s/\&$//;
1.620 albertel 5096: if (!$udomain) { $udomain=$env{'user.domain'}; }
5097: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5098: my $uhome=&homeserver($uname,$udomain);
5099:
1.133 albertel 5100: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5101: my @pairs=split(/\&/,$rep);
1.273 albertel 5102: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5103: return @pairs;
5104: }
1.15 www 5105: my %returnhash=();
1.42 www 5106: my $i=0;
1.800 albertel 5107: foreach my $item (@$storearr) {
5108: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5109: $i++;
1.191 harris41 5110: }
1.15 www 5111: return %returnhash;
1.27 www 5112: }
5113:
5114: # --------------------------------------------------------------- del interface
5115:
5116: sub del {
1.133 albertel 5117: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5118: my $items='';
1.800 albertel 5119: foreach my $item (@$storearr) {
5120: $items.=&escape($item).'&';
1.191 harris41 5121: }
1.984 neumanie 5122:
1.27 www 5123: $items=~s/\&$//;
1.620 albertel 5124: if (!$udomain) { $udomain=$env{'user.domain'}; }
5125: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5126: my $uhome=&homeserver($uname,$udomain);
5127: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5128: }
5129:
5130: # -------------------------------------------------------------- dump interface
5131:
1.1180 droeschl 5132: sub unserialize {
5133: my ($rep, $escapedkeys) = @_;
5134:
5135: return {} if $rep =~ /^error/;
5136:
5137: my %returnhash=();
5138: foreach my $item (split /\&/, $rep) {
5139: my ($key, $value) = split(/=/, $item, 2);
5140: $key = unescape($key) unless $escapedkeys;
5141: next if $key =~ /^error: 2 /;
5142: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5143: }
5144: #return %returnhash;
5145: return \%returnhash;
5146: }
5147:
5148: # see Lond::dump_with_regexp
5149: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5150: sub dump {
1.1180 droeschl 5151: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5152: if (!$udomain) { $udomain=$env{'user.domain'}; }
5153: if (!$uname) { $uname=$env{'user.name'}; }
5154: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5155:
1.1180 droeschl 5156: my $reply;
5157: if (grep { $_ eq $uhome } current_machine_ids()) {
5158: # user is hosted on this machine
5159: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
5160: $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
5161: return %{unserialize($reply, $escapedkeys)};
5162: }
1.755 albertel 5163: if ($regexp) {
5164: $regexp=&escape($regexp);
5165: } else {
5166: $regexp='.';
5167: }
1.1166 raeburn 5168: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5169: my @pairs=split(/\&/,$rep);
5170: my %returnhash=();
1.1098 foxr 5171: if (!($rep =~ /^error/ )) {
5172: foreach my $item (@pairs) {
5173: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5174: $key = unescape($key) unless $escapedkeys;
5175: #$key = &unescape($key);
1.1098 foxr 5176: next if ($key =~ /^error: 2 /);
5177: $returnhash{$key}=&thaw_unescape($value);
5178: }
1.755 albertel 5179: }
5180: return %returnhash;
1.407 www 5181: }
5182:
1.1098 foxr 5183:
1.717 albertel 5184: # --------------------------------------------------------- dumpstore interface
5185:
5186: sub dumpstore {
5187: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5188: # same as dump but keys must be escaped. They may contain colon separated
5189: # lists of values that may themself contain colons (e.g. symbs).
5190: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5191: }
5192:
1.407 www 5193: # -------------------------------------------------------------- keys interface
5194:
5195: sub getkeys {
5196: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5197: if (!$udomain) { $udomain=$env{'user.domain'}; }
5198: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5199: my $uhome=&homeserver($uname,$udomain);
5200: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5201: my @keyarray=();
1.800 albertel 5202: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5203: next if ($key =~ /^error: 2 /);
1.800 albertel 5204: push(@keyarray,&unescape($key));
1.407 www 5205: }
5206: return @keyarray;
1.318 matthew 5207: }
5208:
1.319 matthew 5209: # --------------------------------------------------------------- currentdump
5210: sub currentdump {
1.328 matthew 5211: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5212: $courseid = $env{'request.course.id'} if (! defined($courseid));
5213: $sdom = $env{'user.domain'} if (! defined($sdom));
5214: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5215: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5216: my $rep;
5217:
5218: if (grep { $_ eq $uhome } current_machine_ids()) {
5219: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5220: $courseid)));
5221: } else {
5222: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5223: }
5224:
1.318 matthew 5225: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5226: #
1.318 matthew 5227: my %returnhash=();
1.319 matthew 5228: #
5229: if ($rep eq "unknown_cmd") {
5230: # an old lond will not know currentdump
5231: # Do a dump and make it look like a currentdump
1.822 albertel 5232: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5233: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5234: my %hash = @tmp;
5235: @tmp=();
1.424 matthew 5236: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5237: } else {
5238: my @pairs=split(/\&/,$rep);
1.800 albertel 5239: foreach my $pair (@pairs) {
5240: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5241: my ($symb,$param) = split(/:/,$key);
5242: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5243: &thaw_unescape($value);
1.319 matthew 5244: }
1.191 harris41 5245: }
1.12 www 5246: return %returnhash;
1.424 matthew 5247: }
5248:
5249: sub convert_dump_to_currentdump{
5250: my %hash = %{shift()};
5251: my %returnhash;
5252: # Code ripped from lond, essentially. The only difference
5253: # here is the unescaping done by lonnet::dump(). Conceivably
5254: # we might run in to problems with parameter names =~ /^v\./
5255: while (my ($key,$value) = each(%hash)) {
5256: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5257: $symb = &unescape($symb);
5258: $param = &unescape($param);
1.424 matthew 5259: next if ($v eq 'version' || $symb eq 'keys');
5260: next if (exists($returnhash{$symb}) &&
5261: exists($returnhash{$symb}->{$param}) &&
5262: $returnhash{$symb}->{'v.'.$param} > $v);
5263: $returnhash{$symb}->{$param}=$value;
5264: $returnhash{$symb}->{'v.'.$param}=$v;
5265: }
5266: #
5267: # Remove all of the keys in the hashes which keep track of
5268: # the version of the parameter.
5269: while (my ($symb,$param_hash) = each(%returnhash)) {
5270: # use a foreach because we are going to delete from the hash.
5271: foreach my $key (keys(%$param_hash)) {
5272: delete($param_hash->{$key}) if ($key =~ /^v\./);
5273: }
5274: }
5275: return \%returnhash;
1.12 www 5276: }
5277:
1.627 albertel 5278: # ------------------------------------------------------ critical inc interface
5279:
5280: sub cinc {
5281: return &inc(@_,'critical');
5282: }
5283:
1.449 matthew 5284: # --------------------------------------------------------------- inc interface
5285:
5286: sub inc {
1.627 albertel 5287: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5288: if (!$udomain) { $udomain=$env{'user.domain'}; }
5289: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5290: my $uhome=&homeserver($uname,$udomain);
5291: my $items='';
5292: if (! ref($store)) {
5293: # got a single value, so use that instead
5294: $items = &escape($store).'=&';
5295: } elsif (ref($store) eq 'SCALAR') {
5296: $items = &escape($$store).'=&';
5297: } elsif (ref($store) eq 'ARRAY') {
5298: $items = join('=&',map {&escape($_);} @{$store});
5299: } elsif (ref($store) eq 'HASH') {
5300: while (my($key,$value) = each(%{$store})) {
5301: $items.= &escape($key).'='.&escape($value).'&';
5302: }
5303: }
5304: $items=~s/\&$//;
1.627 albertel 5305: if ($critical) {
5306: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5307: } else {
5308: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5309: }
1.449 matthew 5310: }
5311:
1.12 www 5312: # --------------------------------------------------------------- put interface
5313:
5314: sub put {
1.134 albertel 5315: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5316: if (!$udomain) { $udomain=$env{'user.domain'}; }
5317: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5318: my $uhome=&homeserver($uname,$udomain);
1.12 www 5319: my $items='';
1.800 albertel 5320: foreach my $item (keys(%$storehash)) {
5321: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5322: }
1.12 www 5323: $items=~s/\&$//;
1.134 albertel 5324: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5325: }
5326:
1.631 albertel 5327: # ------------------------------------------------------------ newput interface
5328:
5329: sub newput {
5330: my ($namespace,$storehash,$udomain,$uname)=@_;
5331: if (!$udomain) { $udomain=$env{'user.domain'}; }
5332: if (!$uname) { $uname=$env{'user.name'}; }
5333: my $uhome=&homeserver($uname,$udomain);
5334: my $items='';
5335: foreach my $key (keys(%$storehash)) {
5336: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5337: }
5338: $items=~s/\&$//;
5339: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5340: }
5341:
5342: # --------------------------------------------------------- putstore interface
5343:
1.524 raeburn 5344: sub putstore {
1.715 albertel 5345: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5346: if (!$udomain) { $udomain=$env{'user.domain'}; }
5347: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5348: my $uhome=&homeserver($uname,$udomain);
5349: my $items='';
1.715 albertel 5350: foreach my $key (keys(%$storehash)) {
5351: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5352: }
1.715 albertel 5353: $items=~s/\&$//;
1.716 albertel 5354: my $esc_symb=&escape($symb);
5355: my $esc_v=&escape($version);
1.715 albertel 5356: my $reply =
1.716 albertel 5357: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5358: $uhome);
5359: if ($reply eq 'unknown_cmd') {
1.716 albertel 5360: # gfall back to way things use to be done
1.715 albertel 5361: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5362: $uname);
1.524 raeburn 5363: }
1.715 albertel 5364: return $reply;
5365: }
5366:
5367: sub old_putstore {
1.716 albertel 5368: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5369: if (!$udomain) { $udomain=$env{'user.domain'}; }
5370: if (!$uname) { $uname=$env{'user.name'}; }
5371: my $uhome=&homeserver($uname,$udomain);
5372: my %newstorehash;
1.800 albertel 5373: foreach my $item (keys(%$storehash)) {
5374: my $key = $version.':'.&escape($symb).':'.$item;
5375: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5376: }
5377: my $items='';
5378: my %allitems = ();
1.800 albertel 5379: foreach my $item (keys(%newstorehash)) {
5380: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5381: my $key = $1.':keys:'.$2;
5382: $allitems{$key} .= $3.':';
5383: }
1.800 albertel 5384: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5385: }
1.800 albertel 5386: foreach my $item (keys(%allitems)) {
5387: $allitems{$item} =~ s/\:$//;
5388: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5389: }
5390: $items=~s/\&$//;
5391: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5392: }
5393:
1.47 www 5394: # ------------------------------------------------------ critical put interface
5395:
5396: sub cput {
1.134 albertel 5397: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5398: if (!$udomain) { $udomain=$env{'user.domain'}; }
5399: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5400: my $uhome=&homeserver($uname,$udomain);
1.47 www 5401: my $items='';
1.800 albertel 5402: foreach my $item (keys(%$storehash)) {
5403: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5404: }
1.47 www 5405: $items=~s/\&$//;
1.134 albertel 5406: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5407: }
5408:
5409: # -------------------------------------------------------------- eget interface
5410:
5411: sub eget {
1.133 albertel 5412: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5413: my $items='';
1.800 albertel 5414: foreach my $item (@$storearr) {
5415: $items.=&escape($item).'&';
1.191 harris41 5416: }
1.12 www 5417: $items=~s/\&$//;
1.620 albertel 5418: if (!$udomain) { $udomain=$env{'user.domain'}; }
5419: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5420: my $uhome=&homeserver($uname,$udomain);
5421: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5422: my @pairs=split(/\&/,$rep);
5423: my %returnhash=();
1.42 www 5424: my $i=0;
1.800 albertel 5425: foreach my $item (@$storearr) {
5426: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5427: $i++;
1.191 harris41 5428: }
1.12 www 5429: return %returnhash;
5430: }
5431:
1.667 albertel 5432: # ------------------------------------------------------------ tmpput interface
5433: sub tmpput {
1.802 raeburn 5434: my ($storehash,$server,$context)=@_;
1.667 albertel 5435: my $items='';
1.800 albertel 5436: foreach my $item (keys(%$storehash)) {
5437: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5438: }
5439: $items=~s/\&$//;
1.802 raeburn 5440: if (defined($context)) {
5441: $items .= ':'.&escape($context);
5442: }
1.667 albertel 5443: return &reply("tmpput:$items",$server);
5444: }
5445:
5446: # ------------------------------------------------------------ tmpget interface
5447: sub tmpget {
1.688 albertel 5448: my ($token,$server)=@_;
5449: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5450: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5451: my %returnhash;
5452: foreach my $item (split(/\&/,$rep)) {
5453: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5454: next if ($key =~ /^error: 2 /);
1.667 albertel 5455: $returnhash{&unescape($key)}=&thaw_unescape($value);
5456: }
5457: return %returnhash;
5458: }
5459:
1.1113 raeburn 5460: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5461: sub tmpdel {
5462: my ($token,$server)=@_;
5463: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5464: return &reply("tmpdel:$token",$server);
5465: }
5466:
1.765 albertel 5467: # -------------------------------------------------- portfolio access checking
5468:
5469: sub portfolio_access {
1.766 albertel 5470: my ($requrl) = @_;
1.765 albertel 5471: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5472: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5473: if ($result) {
5474: my %setters;
5475: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5476: my ($startblock,$endblock) =
5477: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5478: if ($startblock && $endblock) {
5479: return 'B';
5480: }
5481: } else {
5482: my ($startblock,$endblock) =
5483: &Apache::loncommon::blockcheck(\%setters,'port');
5484: if ($startblock && $endblock) {
5485: return 'B';
5486: }
5487: }
5488: }
1.765 albertel 5489: if ($result eq 'ok') {
1.766 albertel 5490: return 'F';
1.765 albertel 5491: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5492: return 'A';
1.765 albertel 5493: }
1.766 albertel 5494: return '';
1.765 albertel 5495: }
5496:
5497: sub get_portfolio_access {
1.767 albertel 5498: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5499:
5500: if (!ref($access_hash)) {
5501: my $current_perms = &get_portfile_permissions($udom,$unum);
5502: my %access_controls = &get_access_controls($current_perms,$group,
5503: $file_name);
5504: $access_hash = $access_controls{$file_name};
5505: }
5506:
1.765 albertel 5507: my ($public,$guest,@domains,@users,@courses,@groups);
5508: my $now = time;
5509: if (ref($access_hash) eq 'HASH') {
5510: foreach my $key (keys(%{$access_hash})) {
5511: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5512: if ($start > $now) {
5513: next;
5514: }
5515: if ($end && $end<$now) {
5516: next;
5517: }
5518: if ($scope eq 'public') {
5519: $public = $key;
5520: last;
5521: } elsif ($scope eq 'guest') {
5522: $guest = $key;
5523: } elsif ($scope eq 'domains') {
5524: push(@domains,$key);
5525: } elsif ($scope eq 'users') {
5526: push(@users,$key);
5527: } elsif ($scope eq 'course') {
5528: push(@courses,$key);
5529: } elsif ($scope eq 'group') {
5530: push(@groups,$key);
5531: }
5532: }
5533: if ($public) {
5534: return 'ok';
5535: }
5536: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5537: if ($guest) {
5538: return $guest;
5539: }
5540: } else {
5541: if (@domains > 0) {
5542: foreach my $domkey (@domains) {
5543: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5544: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5545: return 'ok';
5546: }
5547: }
5548: }
5549: }
5550: if (@users > 0) {
5551: foreach my $userkey (@users) {
1.865 raeburn 5552: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5553: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5554: if (ref($item) eq 'HASH') {
5555: if (($item->{'uname'} eq $env{'user.name'}) &&
5556: ($item->{'udom'} eq $env{'user.domain'})) {
5557: return 'ok';
5558: }
5559: }
5560: }
5561: }
1.765 albertel 5562: }
5563: }
5564: my %roleshash;
5565: my @courses_and_groups = @courses;
5566: push(@courses_and_groups,@groups);
5567: if (@courses_and_groups > 0) {
5568: my (%allgroups,%allroles);
5569: my ($start,$end,$role,$sec,$group);
5570: foreach my $envkey (%env) {
1.1060 raeburn 5571: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5572: my $cid = $2.'_'.$3;
5573: if ($1 eq 'gr') {
5574: $group = $4;
5575: $allgroups{$cid}{$group} = $env{$envkey};
5576: } else {
5577: if ($4 eq '') {
5578: $sec = 'none';
5579: } else {
5580: $sec = $4;
5581: }
5582: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5583: }
1.811 albertel 5584: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5585: my $cid = $2.'_'.$3;
5586: if ($4 eq '') {
5587: $sec = 'none';
5588: } else {
5589: $sec = $4;
5590: }
5591: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5592: }
5593: }
5594: if (keys(%allroles) == 0) {
5595: return;
5596: }
5597: foreach my $key (@courses_and_groups) {
5598: my %content = %{$$access_hash{$key}};
5599: my $cnum = $content{'number'};
5600: my $cdom = $content{'domain'};
5601: my $cid = $cdom.'_'.$cnum;
5602: if (!exists($allroles{$cid})) {
5603: next;
5604: }
5605: foreach my $role_id (keys(%{$content{'roles'}})) {
5606: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5607: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5608: my @status = @{$content{'roles'}{$role_id}{'access'}};
5609: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5610: foreach my $role (keys(%{$allroles{$cid}})) {
5611: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5612: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5613: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5614: if (grep/^all$/,@sections) {
5615: return 'ok';
5616: } else {
5617: if (grep/^$sec$/,@sections) {
5618: return 'ok';
5619: }
5620: }
5621: }
5622: }
5623: if (keys(%{$allgroups{$cid}}) == 0) {
5624: if (grep/^none$/,@groups) {
5625: return 'ok';
5626: }
5627: } else {
5628: if (grep/^all$/,@groups) {
5629: return 'ok';
5630: }
5631: foreach my $group (keys(%{$allgroups{$cid}})) {
5632: if (grep/^$group$/,@groups) {
5633: return 'ok';
5634: }
5635: }
5636: }
5637: }
5638: }
5639: }
5640: }
5641: }
5642: if ($guest) {
5643: return $guest;
5644: }
5645: }
5646: }
5647: return;
5648: }
5649:
5650: sub course_group_datechecker {
5651: my ($dates,$now,$status) = @_;
5652: my ($start,$end) = split(/\./,$dates);
5653: if (!$start && !$end) {
5654: return 'ok';
5655: }
5656: if (grep/^active$/,@{$status}) {
5657: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5658: return 'ok';
5659: }
5660: }
5661: if (grep/^previous$/,@{$status}) {
5662: if ($end > $now ) {
5663: return 'ok';
5664: }
5665: }
5666: if (grep/^future$/,@{$status}) {
5667: if ($start > $now) {
5668: return 'ok';
5669: }
5670: }
5671: return;
5672: }
5673:
5674: sub parse_portfolio_url {
5675: my ($url) = @_;
5676:
5677: my ($type,$udom,$unum,$group,$file_name);
5678:
1.823 albertel 5679: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5680: $type = 1;
5681: $udom = $1;
5682: $unum = $2;
5683: $file_name = $3;
1.823 albertel 5684: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5685: $type = 2;
5686: $udom = $1;
5687: $unum = $2;
5688: $group = $3;
5689: $file_name = $3.'/'.$4;
5690: }
5691: if (wantarray) {
5692: return ($type,$udom,$unum,$file_name,$group);
5693: }
5694: return $type;
5695: }
5696:
5697: sub is_portfolio_url {
5698: my ($url) = @_;
5699: return scalar(&parse_portfolio_url($url));
5700: }
5701:
1.798 raeburn 5702: sub is_portfolio_file {
5703: my ($file) = @_;
1.820 raeburn 5704: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5705: return 1;
5706: }
5707: return;
5708: }
5709:
1.976 raeburn 5710: sub usertools_access {
1.1084 raeburn 5711: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5712: my ($access,%tools);
5713: if ($context eq '') {
5714: $context = 'tools';
5715: }
5716: if ($context eq 'requestcourses') {
5717: %tools = (
5718: official => 1,
5719: unofficial => 1,
1.1006 raeburn 5720: community => 1,
1.985 raeburn 5721: );
1.1183 raeburn 5722: } elsif ($context eq 'requestauthor') {
5723: %tools = (
5724: requestauthor => 1,
5725: );
1.985 raeburn 5726: } else {
5727: %tools = (
5728: aboutme => 1,
5729: blog => 1,
1.1177 raeburn 5730: webdav => 1,
1.985 raeburn 5731: portfolio => 1,
5732: );
5733: }
1.976 raeburn 5734: return if (!defined($tools{$tool}));
5735:
5736: if ((!defined($udom)) || (!defined($uname))) {
5737: $udom = $env{'user.domain'};
5738: $uname = $env{'user.name'};
5739: }
5740:
1.978 raeburn 5741: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5742: if ($action ne 'reload') {
1.985 raeburn 5743: if ($context eq 'requestcourses') {
5744: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 5745: } elsif ($context eq 'requestauthor') {
5746: return $env{'environment.canrequest.author'};
1.985 raeburn 5747: } else {
5748: return $env{'environment.availabletools.'.$tool};
5749: }
5750: }
1.976 raeburn 5751: }
5752:
1.1183 raeburn 5753: my ($toolstatus,$inststatus,$envkey);
5754: if ($context eq 'requestauthor') {
5755: $envkey = $context;
5756: } else {
5757: $envkey = $context.'.'.$tool;
5758: }
1.976 raeburn 5759:
1.985 raeburn 5760: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5761: ($action ne 'reload')) {
1.1183 raeburn 5762: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 5763: $inststatus = $env{'environment.inststatus'};
5764: } else {
1.1084 raeburn 5765: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 5766: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 5767: $inststatus = $userenvref->{'inststatus'};
5768: } else {
1.1183 raeburn 5769: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
5770: $toolstatus = $userenv{$envkey};
1.1084 raeburn 5771: $inststatus = $userenv{'inststatus'};
5772: }
1.976 raeburn 5773: }
5774:
5775: if ($toolstatus ne '') {
5776: if ($toolstatus) {
5777: $access = 1;
5778: } else {
5779: $access = 0;
5780: }
5781: return $access;
5782: }
5783:
1.1084 raeburn 5784: my ($is_adv,%domdef);
5785: if (ref($is_advref) eq 'HASH') {
5786: $is_adv = $is_advref->{'is_adv'};
5787: } else {
5788: $is_adv = &is_advanced_user($udom,$uname);
5789: }
5790: if (ref($domdefref) eq 'HASH') {
5791: %domdef = %{$domdefref};
5792: } else {
5793: %domdef = &get_domain_defaults($udom);
5794: }
1.976 raeburn 5795: if (ref($domdef{$tool}) eq 'HASH') {
5796: if ($is_adv) {
5797: if ($domdef{$tool}{'_LC_adv'} ne '') {
5798: if ($domdef{$tool}{'_LC_adv'}) {
5799: $access = 1;
5800: } else {
5801: $access = 0;
5802: }
5803: return $access;
5804: }
5805: }
5806: if ($inststatus ne '') {
5807: my ($hasaccess,$hasnoaccess);
5808: foreach my $affiliation (split(/:/,$inststatus)) {
5809: if ($domdef{$tool}{$affiliation} ne '') {
5810: if ($domdef{$tool}{$affiliation}) {
5811: $hasaccess = 1;
5812: } else {
5813: $hasnoaccess = 1;
5814: }
5815: }
5816: }
5817: if ($hasaccess || $hasnoaccess) {
5818: if ($hasaccess) {
5819: $access = 1;
5820: } elsif ($hasnoaccess) {
5821: $access = 0;
5822: }
5823: return $access;
5824: }
5825: } else {
5826: if ($domdef{$tool}{'default'} ne '') {
5827: if ($domdef{$tool}{'default'}) {
5828: $access = 1;
5829: } elsif ($domdef{$tool}{'default'} == 0) {
5830: $access = 0;
5831: }
5832: return $access;
5833: }
5834: }
5835: } else {
1.1177 raeburn 5836: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 5837: $access = 1;
5838: } else {
5839: $access = 0;
5840: }
1.976 raeburn 5841: return $access;
5842: }
5843: }
5844:
1.1050 raeburn 5845: sub is_course_owner {
5846: my ($cdom,$cnum,$udom,$uname) = @_;
5847: if (($udom eq '') || ($uname eq '')) {
5848: $udom = $env{'user.domain'};
5849: $uname = $env{'user.name'};
5850: }
5851: unless (($udom eq '') || ($uname eq '')) {
5852: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5853: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5854: return 1;
5855: } else {
5856: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5857: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5858: return 1;
5859: }
5860: }
5861: }
5862: }
5863: return;
5864: }
5865:
1.976 raeburn 5866: sub is_advanced_user {
5867: my ($udom,$uname) = @_;
1.1085 raeburn 5868: if ($udom ne '' && $uname ne '') {
5869: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5870: if (wantarray) {
5871: return ($env{'user.adv'},$env{'user.author'});
5872: } else {
5873: return $env{'user.adv'};
5874: }
1.1085 raeburn 5875: }
5876: }
1.976 raeburn 5877: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5878: my %allroles;
1.1128 raeburn 5879: my ($is_adv,$is_author);
1.976 raeburn 5880: foreach my $role (keys(%roleshash)) {
5881: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5882: my $area = '/'.$tdomain.'/'.$trest;
5883: if ($sec ne '') {
5884: $area .= '/'.$sec;
5885: }
5886: if (($area ne '') && ($trole ne '')) {
5887: my $spec=$trole.'.'.$area;
5888: if ($trole =~ /^cr\//) {
5889: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5890: } elsif ($trole ne 'gr') {
5891: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5892: }
1.1128 raeburn 5893: if ($trole eq 'au') {
5894: $is_author = 1;
5895: }
1.976 raeburn 5896: }
5897: }
5898: foreach my $role (keys(%allroles)) {
5899: last if ($is_adv);
5900: foreach my $item (split(/:/,$allroles{$role})) {
5901: if ($item ne '') {
5902: my ($privilege,$restrictions)=split(/&/,$item);
5903: if ($privilege eq 'adv') {
5904: $is_adv = 1;
5905: last;
5906: }
5907: }
5908: }
5909: }
1.1128 raeburn 5910: if (wantarray) {
5911: return ($is_adv,$is_author);
5912: }
1.976 raeburn 5913: return $is_adv;
5914: }
1.798 raeburn 5915:
1.1035 raeburn 5916: sub check_can_request {
1.1036 raeburn 5917: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5918: my $canreq = 0;
5919: my ($types,$typename) = &Apache::loncommon::course_types();
5920: my @options = ('approval','validate','autolimit');
5921: my $optregex = join('|',@options);
5922: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5923: foreach my $type (@{$types}) {
5924: if (&usertools_access($env{'user.name'},
5925: $env{'user.domain'},
5926: $type,undef,'requestcourses')) {
5927: $canreq ++;
1.1036 raeburn 5928: if (ref($request_domains) eq 'HASH') {
5929: push(@{$request_domains->{$type}},$env{'user.domain'});
5930: }
1.1035 raeburn 5931: if ($dom eq $env{'user.domain'}) {
5932: $can_request->{$type} = 1;
5933: }
5934: }
5935: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5936: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5937: if (@curr > 0) {
1.1036 raeburn 5938: foreach my $item (@curr) {
5939: if (ref($request_domains) eq 'HASH') {
5940: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5941: if ($otherdom ne '') {
5942: if (ref($request_domains->{$type}) eq 'ARRAY') {
5943: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5944: push(@{$request_domains->{$type}},$otherdom);
5945: }
5946: } else {
5947: push(@{$request_domains->{$type}},$otherdom);
5948: }
5949: }
5950: }
5951: }
5952: unless($dom eq $env{'user.domain'}) {
5953: $canreq ++;
1.1035 raeburn 5954: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5955: $can_request->{$type} = 1;
5956: }
5957: }
5958: }
5959: }
5960: }
5961: }
5962: return $canreq;
5963: }
5964:
1.341 www 5965: # ---------------------------------------------- Custom access rule evaluation
5966:
5967: sub customaccess {
5968: my ($priv,$uri)=@_;
1.807 albertel 5969: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5970: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5971: $udom = &LONCAPA::clean_domain($udom);
5972: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5973: my $access=0;
1.800 albertel 5974: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5975: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5976: if ($type eq 'user') {
5977: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5978: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5979: if ($tdom) {
5980: if ($tdom ne $env{'user.domain'}) { next; }
5981: }
1.896 albertel 5982: if ($tuname) {
5983: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5984: }
5985: $access=($effect eq 'allow');
5986: last;
5987: }
5988: } else {
5989: if ($role) {
5990: if ($role ne $urole) { next; }
5991: }
5992: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5993: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5994: if ($tdom) {
5995: if ($tdom ne $udom) { next; }
5996: }
5997: if ($tcrs) {
5998: if ($tcrs ne $ucrs) { next; }
5999: }
6000: if ($tsec) {
6001: if ($tsec ne $usec) { next; }
6002: }
6003: $access=($effect eq 'allow');
6004: last;
6005: }
6006: if ($realm eq '' && $role eq '') {
6007: $access=($effect eq 'allow');
6008: }
1.402 bowersj2 6009: }
1.341 www 6010: }
6011: return $access;
6012: }
6013:
1.103 harris41 6014: # ------------------------------------------------- Check for a user privilege
1.12 www 6015:
6016: sub allowed {
1.810 raeburn 6017: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6018: my $ver_orguri=$uri;
1.439 www 6019: $uri=&deversion($uri);
1.152 www 6020: my $orguri=$uri;
1.52 www 6021: $uri=&declutter($uri);
1.809 raeburn 6022:
1.810 raeburn 6023: if ($priv eq 'evb') {
6024: # Evade communication block restrictions for specified role in a course
6025: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6026: return $1;
6027: } else {
6028: return;
6029: }
6030: }
6031:
1.620 albertel 6032: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6033: # Free bre access to adm and meta resources
1.775 albertel 6034: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6035: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6036: && ($priv eq 'bre')) {
1.14 www 6037: return 'F';
1.159 www 6038: }
6039:
1.545 banghart 6040: # Free bre access to user's own portfolio contents
1.714 raeburn 6041: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6042: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6043: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6044: my %setters;
6045: my ($startblock,$endblock) =
6046: &Apache::loncommon::blockcheck(\%setters,'port');
6047: if ($startblock && $endblock) {
6048: return 'B';
6049: } else {
6050: return 'F';
6051: }
1.545 banghart 6052: }
6053:
1.762 raeburn 6054: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6055: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6056: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6057: if (exists($env{'request.course.id'})) {
6058: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6059: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6060: if (($domain eq $cdom) && ($name eq $cnum)) {
6061: my $courseprivid=$env{'request.course.id'};
6062: $courseprivid=~s/\_/\//;
6063: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6064: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6065: return $1;
1.762 raeburn 6066: } else {
6067: if ($env{'request.course.sec'}) {
6068: $courseprivid.='/'.$env{'request.course.sec'};
6069: }
6070: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6071: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6072: return $2;
6073: }
1.714 raeburn 6074: }
6075: }
6076: }
6077: }
6078:
1.159 www 6079: # Free bre to public access
6080:
6081: if ($priv eq 'bre') {
1.238 www 6082: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6083: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6084: return 'F';
6085: }
1.238 www 6086: if ($copyright eq 'priv') {
6087: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6088: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6089: return '';
6090: }
6091: }
6092: if ($copyright eq 'domain') {
6093: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6094: unless (($env{'user.domain'} eq $1) ||
6095: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6096: return '';
6097: }
1.262 matthew 6098: }
1.620 albertel 6099: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6100: # Library role, so allow browsing of resources in this domain.
6101: return 'F';
1.238 www 6102: }
1.341 www 6103: if ($copyright eq 'custom') {
6104: unless (&customaccess($priv,$uri)) { return ''; }
6105: }
1.14 www 6106: }
1.264 matthew 6107: # Domain coordinator is trying to create a course
1.620 albertel 6108: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6109: # uri is the requested domain in this case.
6110: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6111: # a role of dc for the domain in question.
1.620 albertel 6112: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6113: }
1.29 www 6114:
1.52 www 6115: my $thisallowed='';
6116: my $statecond=0;
6117: my $courseprivid='';
6118:
1.1039 raeburn 6119: my $ownaccess;
1.1043 raeburn 6120: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6121: if (($priv eq 'bro') && ($env{'user.author'})) {
6122: if ($uri eq '') {
6123: $ownaccess = 1;
6124: } else {
6125: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6126: my $udom = $env{'user.domain'};
6127: my $uname = $env{'user.name'};
6128: if ($uri =~ m{^\Q$udom\E/?$}) {
6129: $ownaccess = 1;
1.1040 raeburn 6130: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6131: unless ($uri =~ m{\.\./}) {
6132: $ownaccess = 1;
6133: }
6134: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6135: my $now = time;
6136: if ($uri =~ m{^([^/]+)/?$}) {
6137: my $adom = $1;
6138: foreach my $key (keys(%env)) {
1.1042 raeburn 6139: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6140: my ($start,$end) = split('.',$env{$key});
6141: if (($now >= $start) && (!$end || $end < $now)) {
6142: $ownaccess = 1;
6143: last;
6144: }
6145: }
6146: }
6147: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6148: my $adom = $1;
6149: my $aname = $2;
1.1042 raeburn 6150: foreach my $role ('ca','aa') {
6151: if ($env{"user.role.$role./$adom/$aname"}) {
6152: my ($start,$end) =
6153: split('.',$env{"user.role.$role./$adom/$aname"});
6154: if (($now >= $start) && (!$end || $end < $now)) {
6155: $ownaccess = 1;
6156: last;
6157: }
1.1039 raeburn 6158: }
6159: }
6160: }
6161: }
6162: }
6163: }
6164: }
6165:
1.52 www 6166: # Course
6167:
1.620 albertel 6168: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6169: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6170: $thisallowed.=$1;
6171: }
1.52 www 6172: }
1.29 www 6173:
1.52 www 6174: # Domain
6175:
1.620 albertel 6176: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6177: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6178: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6179: $thisallowed.=$1;
6180: }
1.12 www 6181: }
1.52 www 6182:
1.1141 raeburn 6183: # User who is not author or co-author might still be able to edit
6184: # resource of an author in the domain (e.g., if Domain Coordinator).
6185: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6186: (&allowed('mdc',$env{'request.course.id'}))) {
6187: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6188: $thisallowed.=$1;
6189: }
6190: }
6191:
1.52 www 6192: # Course: uri itself is a course
1.66 www 6193: my $courseuri=$uri;
6194: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6195: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6196:
1.620 albertel 6197: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6198: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6199: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6200: $thisallowed.=$1;
6201: }
1.12 www 6202: }
1.29 www 6203:
1.665 albertel 6204: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6205: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6206: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6207: $thisallowed='';
1.671 raeburn 6208: my ($match)=&is_on_map($uri);
6209: if ($match) {
6210: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6211: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6212: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6213: if (@blockers > 0) {
6214: $thisallowed = 'B';
6215: } else {
6216: $thisallowed.=$1;
6217: }
1.671 raeburn 6218: }
6219: } else {
1.705 albertel 6220: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6221: if ($refuri) {
6222: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6223: $thisallowed='F';
1.671 raeburn 6224: } else {
6225: $refuri=&declutter($refuri);
6226: my ($match) = &is_on_map($refuri);
6227: if ($match) {
1.1162 raeburn 6228: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6229: if (@blockers > 0) {
6230: $thisallowed = 'B';
6231: } else {
6232: $thisallowed='F';
6233: }
1.671 raeburn 6234: }
1.669 raeburn 6235: }
1.671 raeburn 6236: }
6237: }
1.314 www 6238: }
1.492 albertel 6239:
1.766 albertel 6240: if ($priv eq 'bre'
6241: && $thisallowed ne 'F'
6242: && $thisallowed ne '2'
6243: && &is_portfolio_url($uri)) {
6244: $thisallowed = &portfolio_access($uri);
6245: }
6246:
1.52 www 6247: # Full access at system, domain or course-wide level? Exit.
1.29 www 6248: if ($thisallowed=~/F/) {
6249: return 'F';
6250: }
6251:
1.52 www 6252: # If this is generating or modifying users, exit with special codes
1.29 www 6253:
1.643 www 6254: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6255: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6256: my ($audom,$auname)=split('/',$uri);
1.643 www 6257: # no author name given, so this just checks on the general right to make a co-author in this domain
6258: unless ($auname) { return $thisallowed; }
6259: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6260: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6261: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6262: ($audom ne $env{'request.role.domain'}))) { return ''; }
6263: }
1.52 www 6264: return $thisallowed;
6265: }
6266: #
1.103 harris41 6267: # Gathered so far: system, domain and course wide privileges
1.52 www 6268: #
6269: # Course: See if uri or referer is an individual resource that is part of
6270: # the course
6271:
1.620 albertel 6272: if ($env{'request.course.id'}) {
1.232 www 6273:
1.620 albertel 6274: $courseprivid=$env{'request.course.id'};
6275: if ($env{'request.course.sec'}) {
6276: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6277: }
6278: $courseprivid=~s/\_/\//;
6279: my $checkreferer=1;
1.232 www 6280: my ($match,$cond)=&is_on_map($uri);
6281: if ($match) {
6282: $statecond=$cond;
1.620 albertel 6283: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6284: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6285: my $value = $1;
6286: if ($priv eq 'bre') {
6287: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6288: if (@blockers > 0) {
6289: $thisallowed = 'B';
6290: } else {
6291: $thisallowed.=$value;
6292: }
6293: } else {
6294: $thisallowed.=$value;
6295: }
1.52 www 6296: $checkreferer=0;
6297: }
1.29 www 6298: }
1.83 www 6299:
1.148 www 6300: if ($checkreferer) {
1.620 albertel 6301: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6302: unless ($refuri) {
1.800 albertel 6303: foreach my $key (keys(%env)) {
6304: if ($key=~/^httpref\..*\*/) {
6305: my $pattern=$key;
1.156 www 6306: $pattern=~s/^httpref\.\/res\///;
1.148 www 6307: $pattern=~s/\*/\[\^\/\]\+/g;
6308: $pattern=~s/\//\\\//g;
1.152 www 6309: if ($orguri=~/$pattern/) {
1.800 albertel 6310: $refuri=$env{$key};
1.148 www 6311: }
6312: }
1.191 harris41 6313: }
1.148 www 6314: }
1.232 www 6315:
1.148 www 6316: if ($refuri) {
1.152 www 6317: $refuri=&declutter($refuri);
1.232 www 6318: my ($match,$cond)=&is_on_map($refuri);
6319: if ($match) {
6320: my $refstatecond=$cond;
1.620 albertel 6321: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6322: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6323: my $value = $1;
6324: if ($priv eq 'bre') {
6325: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6326: if (@blockers > 0) {
6327: $thisallowed = 'B';
6328: } else {
6329: $thisallowed.=$value;
6330: }
6331: } else {
6332: $thisallowed.=$value;
6333: }
1.53 www 6334: $uri=$refuri;
6335: $statecond=$refstatecond;
1.52 www 6336: }
6337: }
1.148 www 6338: }
1.29 www 6339: }
1.52 www 6340: }
1.29 www 6341:
1.52 www 6342: #
1.103 harris41 6343: # Gathered now: all privileges that could apply, and condition number
1.52 www 6344: #
6345: #
6346: # Full or no access?
6347: #
1.29 www 6348:
1.52 www 6349: if ($thisallowed=~/F/) {
6350: return 'F';
6351: }
1.29 www 6352:
1.52 www 6353: unless ($thisallowed) {
6354: return '';
6355: }
1.29 www 6356:
1.52 www 6357: # Restrictions exist, deal with them
6358: #
6359: # C:according to course preferences
6360: # R:according to resource settings
6361: # L:unless locked
6362: # X:according to user session state
6363: #
6364:
6365: # Possibly locked functionality, check all courses
1.54 www 6366: # Locks might take effect only after 10 minutes cache expiration for other
6367: # courses, and 2 minutes for current course
1.52 www 6368:
6369: my $envkey;
6370: if ($thisallowed=~/L/) {
1.1000 raeburn 6371: foreach $envkey (keys(%env)) {
1.54 www 6372: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6373: my $courseid=$2;
6374: my $roleid=$1.'.'.$2;
1.92 www 6375: $courseid=~s/^\///;
1.54 www 6376: my $expiretime=600;
1.620 albertel 6377: if ($env{'request.role'} eq $roleid) {
1.54 www 6378: $expiretime=120;
6379: }
6380: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6381: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6382: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6383: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6384: }
1.620 albertel 6385: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6386: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6387: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6388: &log($env{'user.domain'},$env{'user.name'},
6389: $env{'user.home'},
1.57 www 6390: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6391: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6392: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6393: return '';
6394: }
6395: }
1.620 albertel 6396: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6397: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6398: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6399: &log($env{'user.domain'},$env{'user.name'},
6400: $env{'user.home'},
1.57 www 6401: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6402: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6403: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6404: return '';
6405: }
6406: }
6407: }
1.29 www 6408: }
1.52 www 6409: }
6410:
6411: #
6412: # Rest of the restrictions depend on selected course
6413: #
6414:
1.620 albertel 6415: unless ($env{'request.course.id'}) {
1.766 albertel 6416: if ($thisallowed eq 'A') {
6417: return 'A';
1.814 raeburn 6418: } elsif ($thisallowed eq 'B') {
6419: return 'B';
1.766 albertel 6420: } else {
6421: return '1';
6422: }
1.52 www 6423: }
1.29 www 6424:
1.52 www 6425: #
6426: # Now user is definitely in a course
6427: #
1.53 www 6428:
6429:
6430: # Course preferences
6431:
6432: if ($thisallowed=~/C/) {
1.620 albertel 6433: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6434: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6435: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6436: =~/\Q$rolecode\E/) {
1.1103 raeburn 6437: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6438: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6439: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6440: $env{'request.course.id'});
6441: }
1.237 www 6442: return '';
6443: }
6444:
1.620 albertel 6445: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6446: =~/\Q$unamedom\E/) {
1.1103 raeburn 6447: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6448: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6449: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6450: $env{'request.course.id'});
6451: }
1.54 www 6452: return '';
6453: }
1.53 www 6454: }
6455:
6456: # Resource preferences
6457:
6458: if ($thisallowed=~/R/) {
1.620 albertel 6459: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6460: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6461: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6462: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6463: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6464: }
6465: return '';
1.54 www 6466: }
1.53 www 6467: }
1.30 www 6468:
1.246 www 6469: # Restricted by state or randomout?
1.30 www 6470:
1.52 www 6471: if ($thisallowed=~/X/) {
1.620 albertel 6472: if ($env{'acc.randomout'}) {
1.579 albertel 6473: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6474: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6475: return '';
6476: }
1.247 www 6477: }
6478: if (&condval($statecond)) {
1.52 www 6479: return '2';
6480: } else {
6481: return '';
6482: }
6483: }
1.30 www 6484:
1.766 albertel 6485: if ($thisallowed eq 'A') {
6486: return 'A';
1.814 raeburn 6487: } elsif ($thisallowed eq 'B') {
6488: return 'B';
1.766 albertel 6489: }
1.52 www 6490: return 'F';
1.232 www 6491: }
1.1162 raeburn 6492:
6493: sub get_comm_blocks {
6494: my ($cdom,$cnum) = @_;
6495: if ($cdom eq '' || $cnum eq '') {
6496: return unless ($env{'request.course.id'});
6497: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6498: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6499: }
6500: my %commblocks;
6501: my $hashid=$cdom.'_'.$cnum;
6502: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6503: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6504: %commblocks = %{$blocksref};
6505: } else {
6506: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6507: my $cachetime = 600;
6508: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6509: }
6510: return %commblocks;
6511: }
6512:
6513: sub has_comm_blocking {
6514: my ($priv,$symb,$uri,$blocks) = @_;
6515: return unless ($env{'request.course.id'});
6516: return unless ($priv eq 'bre');
6517: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6518: my %commblocks;
6519: if (ref($blocks) eq 'HASH') {
6520: %commblocks = %{$blocks};
6521: } else {
6522: %commblocks = &get_comm_blocks();
6523: }
6524: return unless (keys(%commblocks) > 0);
6525: if (!$symb) { $symb=&symbread($uri,1); }
6526: my ($map,$resid,undef)=&decode_symb($symb);
6527: my %tocheck = (
6528: maps => $map,
6529: resources => $symb,
6530: );
6531: my @blockers;
6532: my $now = time;
1.1163 raeburn 6533: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 6534: foreach my $block (keys(%commblocks)) {
6535: if ($block =~ /^(\d+)____(\d+)$/) {
6536: my ($start,$end) = ($1,$2);
6537: if ($start <= $now && $end >= $now) {
6538: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6539: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6540: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6541: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6542: unless (grep(/^\Q$block\E$/,@blockers)) {
6543: push(@blockers,$block);
6544: }
6545: }
6546: }
6547: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6548: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6549: unless (grep(/^\Q$block\E$/,@blockers)) {
6550: push(@blockers,$block);
6551: }
6552: }
6553: }
6554: }
6555: }
6556: }
6557: } elsif ($block =~ /^firstaccess____(.+)$/) {
6558: my $item = $1;
1.1163 raeburn 6559: my @to_test;
1.1162 raeburn 6560: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6561: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6562: my $check_interval;
6563: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6564: my @interval;
6565: my $type = 'map';
6566: if ($item eq 'course') {
6567: $type = 'course';
6568: @interval=&EXT("resource.0.interval");
6569: } else {
6570: if ($item =~ /___\d+___/) {
6571: $type = 'resource';
6572: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 6573: if (ref($navmap)) {
6574: my $res = $navmap->getBySymb($item);
6575: push(@to_test,$res);
6576: }
1.1162 raeburn 6577: } else {
6578: my $mapsymb = &symbread($item,1);
6579: if ($mapsymb) {
6580: if (ref($navmap)) {
6581: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 6582: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6583: foreach my $res (@to_test) {
1.1162 raeburn 6584: my $symb = $res->symb();
6585: next if ($symb eq $mapsymb);
6586: if ($symb ne '') {
6587: @interval=&EXT("resource.0.interval",$symb);
6588: last;
6589: }
6590: }
6591: }
6592: }
6593: }
6594: }
6595: if ($interval[0] =~ /\d+/) {
6596: my $first_access;
6597: if ($type eq 'resource') {
6598: $first_access=&get_first_access($interval[1],$item);
6599: } elsif ($type eq 'map') {
6600: $first_access=&get_first_access($interval[1],undef,$item);
6601: } else {
6602: $first_access=&get_first_access($interval[1]);
6603: }
6604: if ($first_access) {
6605: my $timesup = $first_access+$interval[0];
6606: if ($timesup > $now) {
1.1163 raeburn 6607: foreach my $res (@to_test) {
6608: if ($res->is_problem()) {
6609: if ($res->completable()) {
6610: unless (grep(/^\Q$block\E$/,@blockers)) {
6611: push(@blockers,$block);
6612: }
6613: last;
6614: }
6615: }
1.1162 raeburn 6616: }
6617: }
6618: }
6619: }
6620: }
6621: }
6622: }
6623: }
6624: }
6625: return @blockers;
6626: }
6627:
6628: sub check_docs_block {
6629: my ($docsblock,$tocheck) =@_;
6630: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6631: return;
6632: }
6633: if (ref($docsblock->{'maps'}) eq 'HASH') {
6634: if ($tocheck->{'maps'}) {
6635: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6636: return 1;
6637: }
6638: }
6639: }
6640: if (ref($docsblock->{'resources'}) eq 'HASH') {
6641: if ($tocheck->{'resources'}) {
6642: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6643: return 1;
6644: }
6645: }
6646: }
6647: return;
6648: }
6649:
1.1133 foxr 6650: #
6651: # Removes the versino from a URI and
6652: # splits it in to its filename and path to the filename.
6653: # Seems like File::Basename could have done this more clearly.
6654: # Parameters:
6655: # $uri - input URI
6656: # Returns:
6657: # Two element list consisting of
6658: # $pathname - the URI up to and excluding the trailing /
6659: # $filename - The part of the URI following the last /
6660: # NOTE:
6661: # Another realization of this is simply:
6662: # use File::Basename;
6663: # ...
6664: # $uri = shift;
6665: # $filename = basename($uri);
6666: # $path = dirname($uri);
6667: # return ($filename, $path);
6668: #
6669: # The implementation below is probably faster however.
6670: #
1.710 albertel 6671: sub split_uri_for_cond {
6672: my $uri=&deversion(&declutter(shift));
6673: my @uriparts=split(/\//,$uri);
6674: my $filename=pop(@uriparts);
6675: my $pathname=join('/',@uriparts);
6676: return ($pathname,$filename);
6677: }
1.232 www 6678: # --------------------------------------------------- Is a resource on the map?
6679:
6680: sub is_on_map {
1.710 albertel 6681: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6682: #Trying to find the conditional for the file
1.620 albertel 6683: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6684: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6685: if ($match) {
1.289 bowersj2 6686: return (1,$1);
6687: } else {
1.434 www 6688: return (0,0);
1.289 bowersj2 6689: }
1.12 www 6690: }
6691:
1.427 www 6692: # --------------------------------------------------------- Get symb from alias
6693:
6694: sub get_symb_from_alias {
6695: my $symb=shift;
6696: my ($map,$resid,$url)=&decode_symb($symb);
6697: # Already is a symb
6698: if ($url) { return $symb; }
6699: # Must be an alias
6700: my $aliassymb='';
6701: my %bighash;
1.620 albertel 6702: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6703: &GDBM_READER(),0640)) {
6704: my $rid=$bighash{'mapalias_'.$symb};
6705: if ($rid) {
6706: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6707: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6708: $resid,$bighash{'src_'.$rid});
1.427 www 6709: }
6710: untie %bighash;
6711: }
6712: return $aliassymb;
6713: }
6714:
1.12 www 6715: # ----------------------------------------------------------------- Define Role
6716:
6717: sub definerole {
6718: if (allowed('mcr','/')) {
6719: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6720: foreach my $role (split(':',$sysrole)) {
6721: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6722: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6723: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6724: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6725: return "refused:s:$crole&$cqual";
6726: }
6727: }
1.191 harris41 6728: }
1.800 albertel 6729: foreach my $role (split(':',$domrole)) {
6730: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6731: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6732: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6733: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6734: return "refused:d:$crole&$cqual";
6735: }
6736: }
1.191 harris41 6737: }
1.800 albertel 6738: foreach my $role (split(':',$courole)) {
6739: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6740: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6741: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6742: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6743: return "refused:c:$crole&$cqual";
6744: }
6745: }
1.191 harris41 6746: }
1.620 albertel 6747: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6748: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6749: "rolesdef_$rolename=".
6750: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6751: return reply($command,$env{'user.home'});
1.12 www 6752: } else {
6753: return 'refused';
6754: }
1.105 harris41 6755: }
6756:
6757: # ---------------- Make a metadata query against the network of library servers
6758:
6759: sub metadata_query {
1.244 matthew 6760: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6761: my %rhash;
1.845 albertel 6762: my %libserv = &all_library();
1.244 matthew 6763: my @server_list = (defined($server_array) ? @$server_array
6764: : keys(%libserv) );
6765: for my $server (@server_list) {
1.118 harris41 6766: unless ($custom or $customshow) {
6767: my $reply=&reply("querysend:".&escape($query),$server);
6768: $rhash{$server}=$reply;
6769: }
6770: else {
6771: my $reply=&reply("querysend:".&escape($query).':'.
6772: &escape($custom).':'.&escape($customshow),
6773: $server);
6774: $rhash{$server}=$reply;
6775: }
1.112 harris41 6776: }
1.118 harris41 6777: return \%rhash;
1.240 www 6778: }
6779:
6780: # ----------------------------------------- Send log queries and wait for reply
6781:
6782: sub log_query {
6783: my ($uname,$udom,$query,%filters)=@_;
6784: my $uhome=&homeserver($uname,$udom);
6785: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6786: my $uhost=&hostname($uhome);
1.800 albertel 6787: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6788: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6789: $uhome);
1.479 albertel 6790: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6791: return get_query_reply($queryid);
6792: }
6793:
1.818 raeburn 6794: # -------------------------- Update MySQL table for portfolio file
6795:
6796: sub update_portfolio_table {
1.821 raeburn 6797: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6798: if ($group ne '') {
6799: $file_name =~s /^\Q$group\E//;
6800: }
1.818 raeburn 6801: my $homeserver = &homeserver($uname,$udom);
6802: my $queryid=
1.821 raeburn 6803: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6804: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6805: my $reply = &get_query_reply($queryid);
6806: return $reply;
6807: }
6808:
1.899 raeburn 6809: # -------------------------- Update MySQL allusers table
6810:
6811: sub update_allusers_table {
6812: my ($uname,$udom,$names) = @_;
6813: my $homeserver = &homeserver($uname,$udom);
6814: my $queryid=
6815: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6816: 'lastname='.&escape($names->{'lastname'}).'%%'.
6817: 'firstname='.&escape($names->{'firstname'}).'%%'.
6818: 'middlename='.&escape($names->{'middlename'}).'%%'.
6819: 'generation='.&escape($names->{'generation'}).'%%'.
6820: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6821: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6822: return;
1.899 raeburn 6823: }
6824:
1.508 raeburn 6825: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6826:
6827: sub fetch_enrollment_query {
1.511 raeburn 6828: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6829: my $homeserver;
1.547 raeburn 6830: my $maxtries = 1;
1.508 raeburn 6831: if ($context eq 'automated') {
6832: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6833: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6834: } else {
6835: $homeserver = &homeserver($cnum,$dom);
6836: }
1.838 albertel 6837: my $host=&hostname($homeserver);
1.506 raeburn 6838: my $cmd = '';
1.1000 raeburn 6839: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6840: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6841: }
6842: $cmd =~ s/%%$//;
6843: $cmd = &escape($cmd);
6844: my $query = 'fetchenrollment';
1.620 albertel 6845: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6846: unless ($queryid=~/^\Q$host\E\_/) {
6847: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6848: return 'error: '.$queryid;
6849: }
1.506 raeburn 6850: my $reply = &get_query_reply($queryid);
1.547 raeburn 6851: my $tries = 1;
6852: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6853: $reply = &get_query_reply($queryid);
6854: $tries ++;
6855: }
1.526 raeburn 6856: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6857: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6858: } else {
1.901 albertel 6859: my @responses = split(/:/,$reply);
1.515 raeburn 6860: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6861: foreach my $line (@responses) {
6862: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6863: $$replyref{$key} = $value;
6864: }
6865: } else {
1.1117 foxr 6866: my $pathname = LONCAPA::tempdir();
1.800 albertel 6867: foreach my $line (@responses) {
6868: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6869: $$replyref{$key} = $value;
6870: if ($value > 0) {
1.800 albertel 6871: foreach my $item (@{$$affiliatesref{$key}}) {
6872: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6873: my $destname = $pathname.'/'.$filename;
6874: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6875: if ($xml_classlist =~ /^error/) {
6876: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6877: } else {
1.506 raeburn 6878: if ( open(FILE,">$destname") ) {
6879: print FILE &unescape($xml_classlist);
6880: close(FILE);
1.526 raeburn 6881: } else {
6882: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6883: }
6884: }
6885: }
6886: }
6887: }
6888: }
6889: return 'ok';
6890: }
6891: return 'error';
6892: }
6893:
1.242 www 6894: sub get_query_reply {
6895: my $queryid=shift;
1.1117 foxr 6896: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6897: my $reply='';
6898: for (1..100) {
6899: sleep 2;
6900: if (-e $replyfile.'.end') {
1.448 albertel 6901: if (open(my $fh,$replyfile)) {
1.904 albertel 6902: $reply = join('',<$fh>);
6903: close($fh);
1.240 www 6904: } else { return 'error: reply_file_error'; }
1.242 www 6905: return &unescape($reply);
6906: }
1.240 www 6907: }
1.242 www 6908: return 'timeout:'.$queryid;
1.240 www 6909: }
6910:
6911: sub courselog_query {
1.241 www 6912: #
6913: # possible filters:
6914: # url: url or symb
6915: # username
6916: # domain
6917: # action: view, submit, grade
6918: # start: timestamp
6919: # end: timestamp
6920: #
1.240 www 6921: my (%filters)=@_;
1.620 albertel 6922: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6923: if ($filters{'url'}) {
6924: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6925: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6926: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6927: }
1.620 albertel 6928: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6929: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6930: return &log_query($cname,$cdom,'courselog',%filters);
6931: }
6932:
6933: sub userlog_query {
1.858 raeburn 6934: #
6935: # possible filters:
6936: # action: log check role
6937: # start: timestamp
6938: # end: timestamp
6939: #
1.240 www 6940: my ($uname,$udom,%filters)=@_;
6941: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6942: }
6943:
1.506 raeburn 6944: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6945:
6946: sub auto_run {
1.508 raeburn 6947: my ($cnum,$cdom) = @_;
1.876 raeburn 6948: my $response = 0;
6949: my $settings;
6950: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6951: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6952: $settings = $domconfig{'autoenroll'};
6953: if ($settings->{'run'} eq '1') {
6954: $response = 1;
6955: }
6956: } else {
1.934 raeburn 6957: my $homeserver;
6958: if (&is_course($cdom,$cnum)) {
6959: $homeserver = &homeserver($cnum,$cdom);
6960: } else {
6961: $homeserver = &domain($cdom,'primary');
6962: }
6963: if ($homeserver ne 'no_host') {
6964: $response = &reply('autorun:'.$cdom,$homeserver);
6965: }
1.876 raeburn 6966: }
1.506 raeburn 6967: return $response;
6968: }
1.776 albertel 6969:
1.506 raeburn 6970: sub auto_get_sections {
1.508 raeburn 6971: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6972: my $homeserver;
6973: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6974: $homeserver = &homeserver($cnum,$cdom);
6975: }
6976: if (!defined($homeserver)) {
6977: if ($cdom =~ /^$match_domain$/) {
6978: $homeserver = &domain($cdom,'primary');
6979: }
6980: }
6981: my @secs;
6982: if (defined($homeserver)) {
6983: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6984: unless ($response eq 'refused') {
6985: @secs = split(/:/,$response);
6986: }
1.506 raeburn 6987: }
6988: return @secs;
6989: }
1.776 albertel 6990:
1.506 raeburn 6991: sub auto_new_course {
1.1099 raeburn 6992: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6993: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6994: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6995: return $response;
6996: }
1.776 albertel 6997:
1.506 raeburn 6998: sub auto_validate_courseID {
1.508 raeburn 6999: my ($cnum,$cdom,$inst_course_id) = @_;
7000: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7001: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7002: return $response;
7003: }
1.776 albertel 7004:
1.1007 raeburn 7005: sub auto_validate_instcode {
1.1020 raeburn 7006: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7007: my ($homeserver,$response);
7008: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7009: $homeserver = &homeserver($cnum,$cdom);
7010: }
7011: if (!defined($homeserver)) {
7012: if ($cdom =~ /^$match_domain$/) {
7013: $homeserver = &domain($cdom,'primary');
7014: }
7015: }
1.1065 raeburn 7016: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7017: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 7018: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
7019: return ($outcome,$description);
1.1007 raeburn 7020: }
7021:
1.506 raeburn 7022: sub auto_create_password {
1.873 raeburn 7023: my ($cnum,$cdom,$authparam,$udom) = @_;
7024: my ($homeserver,$response);
1.506 raeburn 7025: my $create_passwd = 0;
7026: my $authchk = '';
1.873 raeburn 7027: if ($udom =~ /^$match_domain$/) {
7028: $homeserver = &domain($udom,'primary');
7029: }
7030: if ($homeserver eq '') {
7031: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7032: $homeserver = &homeserver($cnum,$cdom);
7033: }
7034: }
7035: if ($homeserver eq '') {
7036: $authchk = 'nodomain';
1.506 raeburn 7037: } else {
1.873 raeburn 7038: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7039: if ($response eq 'refused') {
7040: $authchk = 'refused';
7041: } else {
1.901 albertel 7042: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7043: }
1.506 raeburn 7044: }
7045: return ($authparam,$create_passwd,$authchk);
7046: }
7047:
1.706 raeburn 7048: sub auto_photo_permission {
7049: my ($cnum,$cdom,$students) = @_;
7050: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7051: my ($outcome,$perm_reqd,$conditions) =
7052: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7053: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7054: return (undef,undef);
7055: }
1.706 raeburn 7056: return ($outcome,$perm_reqd,$conditions);
7057: }
7058:
7059: sub auto_checkphotos {
7060: my ($uname,$udom,$pid) = @_;
7061: my $homeserver = &homeserver($uname,$udom);
7062: my ($result,$resulttype);
7063: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7064: &escape($uname).':'.&escape($pid),
7065: $homeserver));
1.709 albertel 7066: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7067: return (undef,undef);
7068: }
1.706 raeburn 7069: if ($outcome) {
7070: ($result,$resulttype) = split(/:/,$outcome);
7071: }
7072: return ($result,$resulttype);
7073: }
7074:
7075: sub auto_photochoice {
7076: my ($cnum,$cdom) = @_;
7077: my $homeserver = &homeserver($cnum,$cdom);
7078: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7079: &escape($cdom),
7080: $homeserver)));
1.709 albertel 7081: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7082: return (undef,undef);
7083: }
1.706 raeburn 7084: return ($update,$comment);
7085: }
7086:
7087: sub auto_photoupdate {
7088: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7089: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7090: my $host=&hostname($homeserver);
1.706 raeburn 7091: my $cmd = '';
7092: my $maxtries = 1;
1.800 albertel 7093: foreach my $affiliate (keys(%{$affiliatesref})) {
7094: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7095: }
7096: $cmd =~ s/%%$//;
7097: $cmd = &escape($cmd);
7098: my $query = 'institutionalphotos';
7099: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7100: unless ($queryid=~/^\Q$host\E\_/) {
7101: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7102: return 'error: '.$queryid;
7103: }
7104: my $reply = &get_query_reply($queryid);
7105: my $tries = 1;
7106: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7107: $reply = &get_query_reply($queryid);
7108: $tries ++;
7109: }
7110: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7111: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7112: } else {
7113: my @responses = split(/:/,$reply);
7114: my $outcome = shift(@responses);
7115: foreach my $item (@responses) {
7116: my ($key,$value) = split(/=/,$item);
7117: $$photo{$key} = $value;
7118: }
7119: return $outcome;
7120: }
7121: return 'error';
7122: }
7123:
1.521 raeburn 7124: sub auto_instcode_format {
1.793 albertel 7125: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7126: $cat_order) = @_;
1.521 raeburn 7127: my $courses = '';
1.772 raeburn 7128: my @homeservers;
1.521 raeburn 7129: if ($caller eq 'global') {
1.841 albertel 7130: my %servers = &get_servers($codedom,'library');
7131: foreach my $tryserver (keys(%servers)) {
7132: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7133: push(@homeservers,$tryserver);
7134: }
1.584 raeburn 7135: }
1.1022 raeburn 7136: } elsif ($caller eq 'requests') {
7137: if ($codedom =~ /^$match_domain$/) {
7138: my $chome = &domain($codedom,'primary');
7139: unless ($chome eq 'no_host') {
7140: push(@homeservers,$chome);
7141: }
7142: }
1.521 raeburn 7143: } else {
1.772 raeburn 7144: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7145: }
1.793 albertel 7146: foreach my $code (keys(%{$instcodes})) {
7147: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7148: }
7149: chop($courses);
1.772 raeburn 7150: my $ok_response = 0;
7151: my $response;
7152: while (@homeservers > 0 && $ok_response == 0) {
7153: my $server = shift(@homeservers);
7154: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7155: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7156: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7157: split(/:/,$response);
1.772 raeburn 7158: %{$codes} = (%{$codes},&str2hash($codes_str));
7159: push(@{$codetitles},&str2array($codetitles_str));
7160: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7161: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7162: $ok_response = 1;
7163: }
7164: }
7165: if ($ok_response) {
1.521 raeburn 7166: return 'ok';
1.772 raeburn 7167: } else {
7168: return $response;
1.521 raeburn 7169: }
7170: }
7171:
1.792 raeburn 7172: sub auto_instcode_defaults {
7173: my ($domain,$returnhash,$code_order) = @_;
7174: my @homeservers;
1.841 albertel 7175:
7176: my %servers = &get_servers($domain,'library');
7177: foreach my $tryserver (keys(%servers)) {
7178: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7179: push(@homeservers,$tryserver);
7180: }
1.792 raeburn 7181: }
1.841 albertel 7182:
1.792 raeburn 7183: my $response;
1.841 albertel 7184: foreach my $server (@homeservers) {
1.792 raeburn 7185: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7186: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7187:
7188: foreach my $pair (split(/\&/,$response)) {
7189: my ($name,$value)=split(/\=/,$pair);
7190: if ($name eq 'code_order') {
7191: @{$code_order} = split(/\&/,&unescape($value));
7192: } else {
7193: $returnhash->{&unescape($name)}=&unescape($value);
7194: }
7195: }
7196: return 'ok';
1.792 raeburn 7197: }
1.841 albertel 7198:
7199: return $response;
1.1003 raeburn 7200: }
7201:
7202: sub auto_possible_instcodes {
1.1007 raeburn 7203: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7204: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7205: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7206: return;
7207: }
1.1003 raeburn 7208: my (@homeservers,$uhome);
7209: if (defined(&domain($domain,'primary'))) {
7210: $uhome=&domain($domain,'primary');
7211: push(@homeservers,&domain($domain,'primary'));
7212: } else {
7213: my %servers = &get_servers($domain,'library');
7214: foreach my $tryserver (keys(%servers)) {
7215: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7216: push(@homeservers,$tryserver);
7217: }
7218: }
7219: }
7220: my $response;
7221: foreach my $server (@homeservers) {
7222: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7223: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7224: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7225: split(':',$response);
7226: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7227: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7228: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7229: my ($name,$value)=split('=',$item);
7230: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7231: }
7232: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7233: my ($name,$value)=split('=',$item);
7234: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7235: }
7236: return 'ok';
7237: }
7238: return $response;
7239: }
1.792 raeburn 7240:
1.1010 raeburn 7241: sub auto_courserequest_checks {
7242: my ($dom) = @_;
1.1020 raeburn 7243: my ($homeserver,%validations);
7244: if ($dom =~ /^$match_domain$/) {
7245: $homeserver = &domain($dom,'primary');
7246: }
7247: unless ($homeserver eq 'no_host') {
7248: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7249: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7250: my @items = split(/&/,$response);
7251: foreach my $item (@items) {
7252: my ($key,$value) = split('=',$item);
7253: $validations{&unescape($key)} = &thaw_unescape($value);
7254: }
7255: }
7256: }
1.1010 raeburn 7257: return %validations;
7258: }
7259:
1.1020 raeburn 7260: sub auto_courserequest_validation {
7261: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7262: my ($homeserver,$response);
7263: if ($dom =~ /^$match_domain$/) {
7264: $homeserver = &domain($dom,'primary');
7265: }
7266: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7267:
1.1020 raeburn 7268: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7269: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7270: ':'.&escape($instcode).':'.&escape($instseclist),
7271: $homeserver));
7272: }
7273: return $response;
7274: }
7275:
1.777 albertel 7276: sub auto_validate_class_sec {
1.918 raeburn 7277: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7278: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7279: my $ownerlist;
7280: if (ref($owners) eq 'ARRAY') {
7281: $ownerlist = join(',',@{$owners});
7282: } else {
7283: $ownerlist = $owners;
7284: }
1.773 raeburn 7285: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7286: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7287: return $response;
7288: }
7289:
1.679 raeburn 7290: # ------------------------------------------------------- Course Group routines
7291:
7292: sub get_coursegroups {
1.809 raeburn 7293: my ($cdom,$cnum,$group,$namespace) = @_;
7294: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7295: }
7296:
1.679 raeburn 7297: sub modify_coursegroup {
7298: my ($cdom,$cnum,$groupsettings) = @_;
7299: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7300: }
7301:
1.809 raeburn 7302: sub toggle_coursegroup_status {
7303: my ($cdom,$cnum,$group,$action) = @_;
7304: my ($from_namespace,$to_namespace);
7305: if ($action eq 'delete') {
7306: $from_namespace = 'coursegroups';
7307: $to_namespace = 'deleted_groups';
7308: } else {
7309: $from_namespace = 'deleted_groups';
7310: $to_namespace = 'coursegroups';
7311: }
7312: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7313: if (my $tmp = &error(%curr_group)) {
7314: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7315: return ('read error',$tmp);
7316: } else {
7317: my %savedsettings = %curr_group;
1.809 raeburn 7318: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7319: my $deloutcome;
7320: if ($result eq 'ok') {
1.809 raeburn 7321: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7322: } else {
7323: return ('write error',$result);
7324: }
7325: if ($deloutcome eq 'ok') {
7326: return 'ok';
7327: } else {
7328: return ('delete error',$deloutcome);
7329: }
7330: }
7331: }
7332:
1.679 raeburn 7333: sub modify_group_roles {
1.957 raeburn 7334: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7335: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7336: my $role = 'gr/'.&escape($userprivs);
7337: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7338: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7339: if ($result eq 'ok') {
7340: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7341: }
1.679 raeburn 7342: return $result;
7343: }
7344:
7345: sub modify_coursegroup_membership {
7346: my ($cdom,$cnum,$membership) = @_;
7347: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7348: return $result;
7349: }
7350:
1.682 raeburn 7351: sub get_active_groups {
7352: my ($udom,$uname,$cdom,$cnum) = @_;
7353: my $now = time;
7354: my %groups = ();
7355: foreach my $key (keys(%env)) {
1.811 albertel 7356: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7357: my ($start,$end) = split(/\./,$env{$key});
7358: if (($end!=0) && ($end<$now)) { next; }
7359: if (($start!=0) && ($start>$now)) { next; }
7360: if ($1 eq $cdom && $2 eq $cnum) {
7361: $groups{$3} = $env{$key} ;
7362: }
7363: }
7364: }
7365: return %groups;
7366: }
7367:
1.683 raeburn 7368: sub get_group_membership {
7369: my ($cdom,$cnum,$group) = @_;
7370: return(&dump('groupmembership',$cdom,$cnum,$group));
7371: }
7372:
7373: sub get_users_groups {
7374: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7375: my @usersgroups;
1.683 raeburn 7376: my $cachetime=1800;
7377:
7378: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7379: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7380: if (defined($cached)) {
1.734 albertel 7381: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7382: } else {
7383: $grouplist = '';
1.816 raeburn 7384: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7385: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7386: my $access_end = $env{'course.'.$courseid.
7387: '.default_enrollment_end_date'};
7388: my $now = time;
7389: foreach my $key (keys(%roleshash)) {
7390: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7391: my $group = $1;
7392: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7393: my $start = $2;
7394: my $end = $1;
7395: if ($start == -1) { next; } # deleted from group
7396: if (($start!=0) && ($start>$now)) { next; }
7397: if (($end!=0) && ($end<$now)) {
7398: if ($access_end && $access_end < $now) {
7399: if ($access_end - $end < 86400) {
7400: push(@usersgroups,$group);
1.733 raeburn 7401: }
7402: }
1.817 raeburn 7403: next;
1.733 raeburn 7404: }
1.817 raeburn 7405: push(@usersgroups,$group);
1.683 raeburn 7406: }
7407: }
7408: }
1.817 raeburn 7409: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7410: $grouplist = join(':',@usersgroups);
7411: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7412: }
1.733 raeburn 7413: return @usersgroups;
1.683 raeburn 7414: }
7415:
7416: sub devalidate_getgroups_cache {
7417: my ($udom,$uname,$cdom,$cnum)=@_;
7418: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7419:
1.683 raeburn 7420: my $hashid="$udom:$uname:$courseid";
7421: &devalidate_cache_new('getgroups',$hashid);
7422: }
7423:
1.12 www 7424: # ------------------------------------------------------------------ Plain Text
7425:
7426: sub plaintext {
1.988 raeburn 7427: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7428: if ($short =~ m{^cr/}) {
1.758 albertel 7429: return (split('/',$short))[-1];
7430: }
1.742 raeburn 7431: if (!defined($cid)) {
7432: $cid = $env{'request.course.id'};
7433: }
7434: my %rolenames = (
1.1008 raeburn 7435: Course => 'std',
7436: Community => 'alt1',
1.742 raeburn 7437: );
1.1037 raeburn 7438: if ($cid ne '') {
7439: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7440: unless ($forcedefault) {
7441: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7442: &Apache::lonlocal::mt_escape(\$roletext);
7443: return &Apache::lonlocal::mt($roletext);
7444: }
7445: }
7446: }
7447: if ((defined($type)) && (defined($rolenames{$type})) &&
7448: (defined($rolenames{$type})) &&
7449: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7450: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7451: } elsif ($cid ne '') {
7452: my $crstype = $env{'course.'.$cid.'.type'};
7453: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7454: (defined($prp{$short}{$rolenames{$crstype}}))) {
7455: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7456: }
1.742 raeburn 7457: }
1.1037 raeburn 7458: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7459: }
7460:
7461: # ----------------------------------------------------------------- Assign Role
7462:
7463: sub assignrole {
1.957 raeburn 7464: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7465: $context)=@_;
1.21 www 7466: my $mrole;
7467: if ($role =~ /^cr\//) {
1.393 www 7468: my $cwosec=$url;
1.811 albertel 7469: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7470: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7471: my $refused = 1;
7472: if ($context eq 'requestcourses') {
7473: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7474: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7475: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7476: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7477: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7478: if ($crsenv{'internal.courseowner'} eq
7479: $env{'user.name'}.':'.$env{'user.domain'}) {
7480: $refused = '';
7481: }
7482: }
7483: }
7484: }
7485: }
7486: if ($refused) {
7487: &logthis('Refused custom assignrole: '.
7488: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7489: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7490: return 'refused';
7491: }
1.104 www 7492: }
1.21 www 7493: $mrole='cr';
1.678 raeburn 7494: } elsif ($role =~ /^gr\//) {
7495: my $cwogrp=$url;
1.811 albertel 7496: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7497: unless (&allowed('mdg',$cwogrp)) {
7498: &logthis('Refused group assignrole: '.
7499: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7500: $env{'user.name'}.' at '.$env{'user.domain'});
7501: return 'refused';
7502: }
7503: $mrole='gr';
1.21 www 7504: } else {
1.82 www 7505: my $cwosec=$url;
1.811 albertel 7506: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7507: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7508: my $refused;
7509: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7510: if (!(&allowed('c'.$role,$url))) {
7511: $refused = 1;
7512: }
7513: } else {
7514: $refused = 1;
7515: }
1.947 raeburn 7516: if ($refused) {
1.1045 raeburn 7517: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7518: if (!$selfenroll && $context eq 'course') {
7519: my %crsenv;
7520: if ($role eq 'cc' || $role eq 'co') {
7521: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7522: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7523: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7524: if ($crsenv{'internal.courseowner'} eq
7525: $env{'user.name'}.':'.$env{'user.domain'}) {
7526: $refused = '';
7527: }
7528: }
7529: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7530: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7531: if ($crsenv{'internal.courseowner'} eq
7532: $env{'user.name'}.':'.$env{'user.domain'}) {
7533: $refused = '';
7534: }
7535: }
7536: }
7537: }
7538: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7539: $refused = '';
1.1017 raeburn 7540: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7541: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7542: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7543: my $wrongcc;
7544: if ($cnum =~ /^$match_community$/) {
7545: $wrongcc = 1 if ($role eq 'cc');
7546: } else {
7547: $wrongcc = 1 if ($role eq 'co');
7548: }
7549: unless ($wrongcc) {
7550: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7551: if ($crsenv{'internal.courseowner'} eq
7552: $env{'user.name'}.':'.$env{'user.domain'}) {
7553: $refused = '';
7554: }
1.1017 raeburn 7555: }
7556: }
1.1183 raeburn 7557: } elsif ($context eq 'requestauthor') {
7558: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7559: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
7560: if ($env{'environment.requestauthor'} eq 'automatic') {
7561: $refused = '';
7562: } else {
7563: my %domdefaults = &get_domain_defaults($udom);
7564: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
7565: my $checkbystatus;
7566: if ($env{'user.adv'}) {
7567: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
7568: if ($disposition eq 'automatic') {
7569: $refused = '';
7570: } elsif ($disposition eq '') {
7571: $checkbystatus = 1;
7572: }
7573: } else {
7574: $checkbystatus = 1;
7575: }
7576: if ($checkbystatus) {
7577: if ($env{'environment.inststatus'}) {
7578: my @inststatuses = split(/,/,$env{'environment.inststatus'});
7579: foreach my $type (@inststatuses) {
7580: if (($type ne '') &&
7581: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
7582: $refused = '';
7583: }
7584: }
7585: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
7586: $refused = '';
7587: }
7588: }
7589: }
7590: }
7591: }
1.1017 raeburn 7592: }
7593: if ($refused) {
1.947 raeburn 7594: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7595: ' '.$role.' '.$end.' '.$start.' by '.
7596: $env{'user.name'}.' at '.$env{'user.domain'});
7597: return 'refused';
7598: }
1.932 raeburn 7599: }
1.1131 raeburn 7600: } elsif ($role eq 'au') {
7601: if ($url ne '/'.$udom.'/') {
7602: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7603: ' to assign author role for '.$uname.':'.$udom.
7604: ' in domain: '.$url.' refused (wrong domain).');
7605: return 'refused';
7606: }
1.104 www 7607: }
1.21 www 7608: $mrole=$role;
7609: }
1.620 albertel 7610: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7611: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7612: if ($end) { $command.='_'.$end; }
1.21 www 7613: if ($start) {
7614: if ($end) {
1.81 www 7615: $command.='_'.$start;
1.21 www 7616: } else {
1.81 www 7617: $command.='_0_'.$start;
1.21 www 7618: }
7619: }
1.739 raeburn 7620: my $origstart = $start;
7621: my $origend = $end;
1.957 raeburn 7622: my $delflag;
1.357 www 7623: # actually delete
7624: if ($deleteflag) {
1.373 www 7625: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7626: # modify command to delete the role
1.620 albertel 7627: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7628: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7629: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7630: # set start and finish to negative values for userrolelog
7631: $start=-1;
7632: $end=-1;
1.957 raeburn 7633: $delflag = 1;
1.357 www 7634: }
7635: }
7636: # send command
1.349 www 7637: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7638: # log new user role if status is ok
1.349 www 7639: if ($answer eq 'ok') {
1.663 raeburn 7640: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7641: # for course roles, perform group memberships changes triggered by role change.
7642: unless ($role =~ /^gr/) {
7643: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7644: $origstart,$selfenroll,$context);
1.739 raeburn 7645: }
1.1184 ! raeburn 7646: if (($role eq 'cc') || ($role eq 'in') ||
! 7647: ($role eq 'ep') || ($role eq 'ad') ||
! 7648: ($role eq 'ta') || ($role eq 'st') ||
! 7649: ($role=~/^cr/) || ($role eq 'gr') ||
! 7650: ($role eq 'co')) {
! 7651: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
! 7652: $selfenroll,$context);
! 7653: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
! 7654: ($role eq 'au') || ($role eq 'dc')) {
! 7655: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
! 7656: $context);
! 7657: } elsif (($role eq 'ca') || ($role eq 'aa')) {
! 7658: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
! 7659: $context);
! 7660: }
1.1053 raeburn 7661: if ($role eq 'cc') {
7662: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7663: }
1.349 www 7664: }
7665: return $answer;
1.169 harris41 7666: }
7667:
1.1053 raeburn 7668: sub autoupdate_coowners {
7669: my ($url,$end,$start,$uname,$udom) = @_;
7670: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7671: if (($cdom ne '') && ($cnum ne '')) {
7672: my $now = time;
7673: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7674: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7675: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7676: my $instcode = $coursehash{'internal.coursecode'};
7677: if ($instcode ne '') {
1.1056 raeburn 7678: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7679: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7680: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7681: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7682: if ($result eq 'valid') {
7683: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7684: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7685: push(@newcoowners,$coowner);
7686: }
7687: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7688: push(@newcoowners,$uname.':'.$udom);
7689: }
7690: @newcoowners = sort(@newcoowners);
7691: } else {
7692: push(@newcoowners,$uname.':'.$udom);
7693: }
7694: } else {
7695: if ($coursehash{'internal.co-owners'}) {
7696: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7697: unless ($coowner eq $uname.':'.$udom) {
7698: push(@newcoowners,$coowner);
7699: }
7700: }
7701: unless (@newcoowners > 0) {
7702: $delcoowners = 1;
7703: $coowners = '';
7704: }
7705: }
7706: }
7707: if (@newcoowners || $delcoowners) {
7708: &store_coowners($cdom,$cnum,$coursehash{'home'},
7709: $delcoowners,@newcoowners);
7710: }
7711: }
7712: }
7713: }
7714: }
7715: }
7716: }
7717:
7718: sub store_coowners {
7719: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7720: my $cid = $cdom.'_'.$cnum;
7721: my ($coowners,$delresult,$putresult);
7722: if (@newcoowners) {
7723: $coowners = join(',',@newcoowners);
7724: my %coownershash = (
7725: 'internal.co-owners' => $coowners,
7726: );
7727: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7728: if ($putresult eq 'ok') {
7729: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7730: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7731: }
7732: }
7733: }
7734: if ($delcoowners) {
7735: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7736: if ($delresult eq 'ok') {
7737: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7738: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7739: }
7740: }
7741: }
7742: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7743: my %crsinfo =
7744: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7745: if (ref($crsinfo{$cid}) eq 'HASH') {
7746: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7747: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7748: }
7749: }
7750: }
7751:
1.169 harris41 7752: # -------------------------------------------------- Modify user authentication
1.197 www 7753: # Overrides without validation
7754:
1.169 harris41 7755: sub modifyuserauth {
7756: my ($udom,$uname,$umode,$upass)=@_;
7757: my $uhome=&homeserver($uname,$udom);
1.197 www 7758: unless (&allowed('mau',$udom)) { return 'refused'; }
7759: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7760: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7761: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7762: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7763: &escape($upass),$uhome);
1.620 albertel 7764: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7765: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7766: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7767: &log($udom,,$uname,$uhome,
1.620 albertel 7768: 'Authentication changed by '.$env{'user.domain'}.', '.
7769: $env{'user.name'}.', '.$umode.
1.197 www 7770: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7771: unless ($reply eq 'ok') {
1.197 www 7772: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7773: return 'error: '.$reply;
7774: }
1.170 harris41 7775: return 'ok';
1.80 www 7776: }
7777:
1.81 www 7778: # --------------------------------------------------------------- Modify a user
1.80 www 7779:
1.81 www 7780: sub modifyuser {
1.206 matthew 7781: my ($udom, $uname, $uid,
7782: $umode, $upass, $first,
7783: $middle, $last, $gene,
1.1058 raeburn 7784: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7785: $udom= &LONCAPA::clean_domain($udom);
7786: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7787: my $showcandelete = 'none';
7788: if (ref($candelete) eq 'ARRAY') {
7789: if (@{$candelete} > 0) {
7790: $showcandelete = join(', ',@{$candelete});
7791: }
7792: }
1.81 www 7793: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7794: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7795: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7796: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7797: ' desiredhome not specified').
1.620 albertel 7798: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7799: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7800: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7801: my $newuser;
7802: if ($uhome eq 'no_host') {
7803: $newuser = 1;
7804: }
1.80 www 7805: # ----------------------------------------------------------------- Create User
1.406 albertel 7806: if (($uhome eq 'no_host') &&
7807: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7808: my $unhome='';
1.844 albertel 7809: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7810: $unhome = $desiredhome;
1.620 albertel 7811: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7812: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7813: } else { # load balancing routine for determining $unhome
1.81 www 7814: my $loadm=10000000;
1.841 albertel 7815: my %servers = &get_servers($udom,'library');
7816: foreach my $tryserver (keys(%servers)) {
7817: my $answer=reply('load',$tryserver);
7818: if (($answer=~/\d+/) && ($answer<$loadm)) {
7819: $loadm=$answer;
7820: $unhome=$tryserver;
7821: }
1.80 www 7822: }
7823: }
7824: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7825: return 'error: unable to find a home server for '.$uname.
7826: ' in domain '.$udom;
1.80 www 7827: }
7828: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7829: &escape($upass),$unhome);
7830: unless ($reply eq 'ok') {
7831: return 'error: '.$reply;
7832: }
1.230 stredwic 7833: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7834: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7835: return 'error: unable verify users home machine.';
1.80 www 7836: }
1.209 matthew 7837: } # End of creation of new user
1.80 www 7838: # ---------------------------------------------------------------------- Add ID
7839: if ($uid) {
7840: $uid=~tr/A-Z/a-z/;
7841: my %uidhash=&idrget($udom,$uname);
1.196 www 7842: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7843: && (!$forceid)) {
1.80 www 7844: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7845: return 'error: user id "'.$uid.'" does not match '.
7846: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7847: }
7848: } else {
7849: &idput($udom,($uname => $uid));
7850: }
7851: }
7852: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7853: my @tmp=&get('environment',
1.899 raeburn 7854: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7855: 'permanentemail','inststatus'],
1.134 albertel 7856: $udom,$uname);
1.1075 raeburn 7857: my (%names,%oldnames);
1.313 matthew 7858: if ($tmp[0] =~ m/^error:.*/) {
7859: %names=();
7860: } else {
7861: %names = @tmp;
1.1075 raeburn 7862: %oldnames = %names;
1.313 matthew 7863: }
1.388 www 7864: #
1.1058 raeburn 7865: # If name, email and/or uid are blank (e.g., because an uploaded file
7866: # of users did not contain them), do not overwrite existing values
7867: # unless field is in $candelete array ref.
7868: #
7869:
7870: my @fields = ('firstname','middlename','lastname','generation',
7871: 'permanentemail','id');
7872: my %newvalues;
7873: if (ref($candelete) eq 'ARRAY') {
7874: foreach my $field (@fields) {
7875: if (grep(/^\Q$field\E$/,@{$candelete})) {
7876: if ($field eq 'firstname') {
7877: $names{$field} = $first;
7878: } elsif ($field eq 'middlename') {
7879: $names{$field} = $middle;
7880: } elsif ($field eq 'lastname') {
7881: $names{$field} = $last;
7882: } elsif ($field eq 'generation') {
7883: $names{$field} = $gene;
7884: } elsif ($field eq 'permanentemail') {
7885: $names{$field} = $email;
7886: } elsif ($field eq 'id') {
7887: $names{$field} = $uid;
7888: }
7889: }
7890: }
7891: }
1.388 www 7892: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7893: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7894: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7895: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7896: if ($email) {
7897: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7898: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7899: }
1.899 raeburn 7900: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7901: if (defined($inststatus)) {
7902: $names{'inststatus'} = '';
7903: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7904: if (ref($usertypes) eq 'HASH') {
7905: my @okstatuses;
7906: foreach my $item (split(/:/,$inststatus)) {
7907: if (defined($usertypes->{$item})) {
7908: push(@okstatuses,$item);
7909: }
7910: }
7911: if (@okstatuses) {
7912: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7913: }
7914: }
7915: }
1.1075 raeburn 7916: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7917: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7918: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7919: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7920: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7921: } else {
7922: $logmsg .= ' during self creation';
7923: }
1.1075 raeburn 7924: my $changed;
7925: if ($newuser) {
7926: $changed = 1;
7927: } else {
7928: foreach my $field (@fields) {
7929: if ($names{$field} ne $oldnames{$field}) {
7930: $changed = 1;
7931: last;
7932: }
7933: }
7934: }
7935: unless ($changed) {
7936: $logmsg = 'No changes in user information needed for: '.$logmsg;
7937: &logthis($logmsg);
7938: return 'ok';
7939: }
7940: my $reply = &put('environment', \%names, $udom,$uname);
7941: if ($reply ne 'ok') {
7942: return 'error: '.$reply;
7943: }
1.1087 raeburn 7944: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7945: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7946: }
1.1075 raeburn 7947: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7948: &devalidate_cache_new('namescache',$uname.':'.$udom);
7949: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7950: &logthis($logmsg);
1.134 albertel 7951: return 'ok';
1.80 www 7952: }
7953:
1.81 www 7954: # -------------------------------------------------------------- Modify student
1.80 www 7955:
1.81 www 7956: sub modifystudent {
7957: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7958: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7959: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7960: if (!$cid) {
1.620 albertel 7961: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7962: return 'not_in_class';
7963: }
1.80 www 7964: }
7965: # --------------------------------------------------------------- Make the user
1.81 www 7966: my $reply=&modifyuser
1.209 matthew 7967: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7968: $desiredhome,$email,$inststatus);
1.80 www 7969: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7970: # This will cause &modify_student_enrollment to get the uid from the
7971: # students environment
7972: $uid = undef if (!$forceid);
1.455 albertel 7973: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7974: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7975: return $reply;
7976: }
7977:
7978: sub modify_student_enrollment {
1.957 raeburn 7979: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7980: my ($cdom,$cnum,$chome);
7981: if (!$cid) {
1.620 albertel 7982: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7983: return 'not_in_class';
7984: }
1.620 albertel 7985: $cdom=$env{'course.'.$cid.'.domain'};
7986: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7987: } else {
7988: ($cdom,$cnum)=split(/_/,$cid);
7989: }
1.620 albertel 7990: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7991: if (!$chome) {
1.457 raeburn 7992: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7993: }
1.455 albertel 7994: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7995: # Make sure the user exists
1.81 www 7996: my $uhome=&homeserver($uname,$udom);
7997: if (($uhome eq '') || ($uhome eq 'no_host')) {
7998: return 'error: no such user';
7999: }
1.297 matthew 8000: # Get student data if we were not given enough information
8001: if (!defined($first) || $first eq '' ||
8002: !defined($last) || $last eq '' ||
8003: !defined($uid) || $uid eq '' ||
8004: !defined($middle) || $middle eq '' ||
8005: !defined($gene) || $gene eq '') {
1.294 matthew 8006: # They did not supply us with enough data to enroll the student, so
8007: # we need to pick up more information.
1.297 matthew 8008: my %tmp = &get('environment',
1.294 matthew 8009: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8010: ,$udom,$uname);
8011:
1.800 albertel 8012: #foreach my $key (keys(%tmp)) {
8013: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8014: #}
1.294 matthew 8015: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8016: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8017: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8018: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8019: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8020: }
1.556 albertel 8021: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8022: my $user = "$uname:$udom";
8023: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8024: my $reply=cput('classlist',
1.1148 raeburn 8025: {$user =>
1.515 raeburn 8026: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 8027: $cdom,$cnum);
1.1148 raeburn 8028: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8029: &devalidate_getsection_cache($udom,$uname,$cid);
8030: } else {
1.81 www 8031: return 'error: '.$reply;
8032: }
1.297 matthew 8033: # Add student role to user
1.83 www 8034: my $uurl='/'.$cid;
1.81 www 8035: $uurl=~s/\_/\//g;
8036: if ($usec) {
8037: $uurl.='/'.$usec;
8038: }
1.1148 raeburn 8039: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8040: $selfenroll,$context);
8041: if ($result ne 'ok') {
8042: if ($old_entry{$user} ne '') {
8043: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8044: } else {
8045: $reply = &del('classlist',[$user],$cdom,$cnum);
8046: }
8047: }
8048: return $result;
1.21 www 8049: }
8050:
1.556 albertel 8051: sub format_name {
8052: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8053: my $name;
8054: if ($first ne 'lastname') {
8055: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8056: } else {
8057: if ($lastname=~/\S/) {
8058: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8059: $name=~s/\s+,/,/;
8060: } else {
8061: $name.= $firstname.' '.$middlename.' '.$generation;
8062: }
8063: }
8064: $name=~s/^\s+//;
8065: $name=~s/\s+$//;
8066: $name=~s/\s+/ /g;
8067: return $name;
8068: }
8069:
1.84 www 8070: # ------------------------------------------------- Write to course preferences
8071:
8072: sub writecoursepref {
8073: my ($courseid,%prefs)=@_;
8074: $courseid=~s/^\///;
8075: $courseid=~s/\_/\//g;
8076: my ($cdomain,$cnum)=split(/\//,$courseid);
8077: my $chome=homeserver($cnum,$cdomain);
8078: if (($chome eq '') || ($chome eq 'no_host')) {
8079: return 'error: no such course';
8080: }
8081: my $cstring='';
1.800 albertel 8082: foreach my $pref (keys(%prefs)) {
8083: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8084: }
1.84 www 8085: $cstring=~s/\&$//;
8086: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8087: }
8088:
8089: # ---------------------------------------------------------- Make/modify course
8090:
8091: sub createcourse {
1.741 raeburn 8092: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8093: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8094: $url=&declutter($url);
8095: my $cid='';
1.1028 raeburn 8096: if ($context eq 'requestcourses') {
8097: my $can_create = 0;
8098: my ($ownername,$ownerdom) = split(':',$course_owner);
8099: if ($udom eq $ownerdom) {
8100: if (&usertools_access($ownername,$ownerdom,$category,undef,
8101: $context)) {
8102: $can_create = 1;
8103: }
8104: } else {
8105: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8106: $category);
8107: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8108: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8109: if (@curr > 0) {
8110: my @options = qw(approval validate autolimit);
8111: my $optregex = join('|',@options);
8112: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8113: $can_create = 1;
8114: }
8115: }
8116: }
8117: }
8118: if ($can_create) {
8119: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8120: unless (&allowed('ccc',$udom)) {
8121: return 'refused';
8122: }
1.1017 raeburn 8123: }
8124: } else {
8125: return 'refused';
8126: }
1.1028 raeburn 8127: } elsif (!&allowed('ccc',$udom)) {
8128: return 'refused';
1.84 www 8129: }
1.1011 raeburn 8130: # --------------------------------------------------------------- Get Unique ID
8131: my $uname;
8132: if ($cnum =~ /^$match_courseid$/) {
8133: my $chome=&homeserver($cnum,$udom,'true');
8134: if (($chome eq '') || ($chome eq 'no_host')) {
8135: $uname = $cnum;
8136: } else {
1.1038 raeburn 8137: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8138: }
8139: } else {
1.1038 raeburn 8140: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8141: }
8142: return $uname if ($uname =~ /^error/);
8143: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8144: if (!defined($course_server)) {
8145: if (defined(&domain($udom,'primary'))) {
8146: $course_server = &domain($udom,'primary');
8147: } else {
8148: $course_server = $env{'user.home'};
8149: }
8150: }
8151: my %host_servers =
8152: &Apache::lonnet::get_servers($udom,'library');
8153: unless ($host_servers{$course_server}) {
8154: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8155: }
1.84 www 8156: # ------------------------------------------------------------- Make the course
8157: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8158: $course_server);
1.84 www 8159: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8160: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8161: if (($uhome eq '') || ($uhome eq 'no_host')) {
8162: return 'error: no such course';
8163: }
1.271 www 8164: # ----------------------------------------------------------------- Course made
1.516 raeburn 8165: # log existence
1.1029 raeburn 8166: my $now = time;
1.918 raeburn 8167: my $newcourse = {
8168: $udom.'_'.$uname => {
1.921 raeburn 8169: description => $description,
8170: inst_code => $inst_code,
8171: owner => $course_owner,
8172: type => $crstype,
1.1029 raeburn 8173: creator => $env{'user.name'}.':'.
8174: $env{'user.domain'},
8175: created => $now,
8176: context => $context,
1.918 raeburn 8177: },
8178: };
1.921 raeburn 8179: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8180: # set toplevel url
1.271 www 8181: my $topurl=$url;
8182: unless ($nonstandard) {
8183: # ------------------------------------------ For standard courses, make top url
8184: my $mapurl=&clutter($url);
1.278 www 8185: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8186: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8187: <map>
8188: <resource id="1" type="start"></resource>
8189: <resource id="2" src="$mapurl"></resource>
8190: <resource id="3" type="finish"></resource>
8191: <link index="1" from="1" to="2"></link>
8192: <link index="2" from="2" to="3"></link>
8193: </map>
8194: ENDINITMAP
8195: $topurl=&declutter(
1.638 albertel 8196: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8197: );
8198: }
8199: # ----------------------------------------------------------- Write preferences
1.84 www 8200: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8201: ('description' => $description,
8202: 'url' => $topurl,
8203: 'internal.creator' => $env{'user.name'}.':'.
8204: $env{'user.domain'},
8205: 'internal.created' => $now,
8206: 'internal.creationcontext' => $context)
8207: );
1.84 www 8208: return '/'.$udom.'/'.$uname;
8209: }
8210:
1.1011 raeburn 8211: # ------------------------------------------------------------------- Create ID
8212: sub generate_coursenum {
1.1038 raeburn 8213: my ($udom,$crstype) = @_;
1.1011 raeburn 8214: my $domdesc = &domain($udom);
8215: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8216: my $first;
8217: if ($crstype eq 'Community') {
8218: $first = '0';
8219: } else {
8220: $first = int(1+rand(9));
8221: }
8222: my $uname=$first.
1.1011 raeburn 8223: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8224: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8225: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8226: # ----------------------------------------------- Make sure that does not exist
8227: my $uhome=&homeserver($uname,$udom,'true');
8228: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8229: if ($crstype eq 'Community') {
8230: $first = '0';
8231: } else {
8232: $first = int(1+rand(9));
8233: }
8234: $uname=$first.
1.1011 raeburn 8235: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8236: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8237: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8238: $uhome=&homeserver($uname,$udom,'true');
8239: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8240: return 'error: unable to generate unique course-ID';
8241: }
8242: }
8243: return $uname;
8244: }
8245:
1.813 albertel 8246: sub is_course {
1.1167 droeschl 8247: my ($cdom, $cnum) = scalar(@_) == 1 ?
8248: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8249:
8250: return unless $cdom and $cnum;
8251:
8252: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8253: '.');
8254:
8255: return unless exists($courses{$cdom.'_'.$cnum});
8256: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8257: }
8258:
1.1015 raeburn 8259: sub store_userdata {
8260: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8261: my $result;
1.1016 raeburn 8262: if ($datakey ne '') {
1.1013 raeburn 8263: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8264: if ($udom eq '' || $uname eq '') {
8265: $udom = $env{'user.domain'};
8266: $uname = $env{'user.name'};
8267: }
8268: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8269: if (($uhome eq '') || ($uhome eq 'no_host')) {
8270: $result = 'error: no_host';
8271: } else {
8272: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8273: $storehash->{'host'} = $perlvar{'lonHostID'};
8274:
8275: my $namevalue='';
8276: foreach my $key (keys(%{$storehash})) {
8277: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8278: }
8279: $namevalue=~s/\&$//;
1.1105 raeburn 8280: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8281: $namevalue,$uhome);
1.1013 raeburn 8282: }
8283: } else {
8284: $result = 'error: data to store was not a hash reference';
8285: }
8286: } else {
8287: $result= 'error: invalid requestkey';
8288: }
8289: return $result;
8290: }
8291:
1.21 www 8292: # ---------------------------------------------------------- Assign Custom Role
8293:
8294: sub assigncustomrole {
1.957 raeburn 8295: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8296: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8297: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8298: }
8299:
8300: # ----------------------------------------------------------------- Revoke Role
8301:
8302: sub revokerole {
1.957 raeburn 8303: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8304: my $now=time;
1.965 raeburn 8305: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8306: }
8307:
8308: # ---------------------------------------------------------- Revoke Custom Role
8309:
8310: sub revokecustomrole {
1.957 raeburn 8311: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8312: my $now=time;
1.357 www 8313: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8314: $deleteflag,$selfenroll,$context);
1.17 www 8315: }
8316:
1.533 banghart 8317: # ------------------------------------------------------------ Disk usage
1.535 albertel 8318: sub diskusage {
1.955 raeburn 8319: my ($udom,$uname,$directorypath,$getpropath)=@_;
8320: $directorypath =~ s/\/$//;
8321: my $listing=&reply('du2:'.&escape($directorypath).':'
8322: .&escape($getpropath).':'.&escape($uname).':'
8323: .&escape($udom),homeserver($uname,$udom));
8324: if ($listing eq 'unknown_cmd') {
8325: if ($getpropath) {
8326: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8327: }
8328: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8329: }
1.514 albertel 8330: return $listing;
1.512 banghart 8331: }
8332:
1.566 banghart 8333: sub is_locked {
1.1096 raeburn 8334: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8335: my @check;
8336: my $is_locked;
1.1093 raeburn 8337: push (@check,$file_name);
1.613 albertel 8338: my %locked = &get('file_permissions',\@check,
1.620 albertel 8339: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8340: my ($tmp)=keys(%locked);
8341: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8342:
1.566 banghart 8343: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8344: $is_locked = 'false';
8345: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8346: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8347: $is_locked = 'true';
1.1096 raeburn 8348: if (ref($which) eq 'ARRAY') {
8349: push(@{$which},$entry);
8350: } else {
8351: last;
8352: }
1.745 raeburn 8353: }
8354: }
1.566 banghart 8355: } else {
8356: $is_locked = 'false';
8357: }
1.1093 raeburn 8358: return $is_locked;
1.566 banghart 8359: }
8360:
1.759 albertel 8361: sub declutter_portfile {
8362: my ($file) = @_;
1.833 albertel 8363: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8364: return $file;
8365: }
8366:
1.559 banghart 8367: # ------------------------------------------------------------- Mark as Read Only
8368:
8369: sub mark_as_readonly {
8370: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8371: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8372: my ($tmp)=keys(%current_permissions);
8373: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8374: foreach my $file (@{$files}) {
1.759 albertel 8375: $file = &declutter_portfile($file);
1.561 banghart 8376: push(@{$current_permissions{$file}},$what);
1.559 banghart 8377: }
1.613 albertel 8378: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8379: return;
8380: }
8381:
1.572 banghart 8382: # ------------------------------------------------------------Save Selected Files
8383:
8384: sub save_selected_files {
8385: my ($user, $path, @files) = @_;
8386: my $filename = $user."savedfiles";
1.573 banghart 8387: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8388: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8389: foreach my $file (@files) {
1.620 albertel 8390: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8391: }
8392: foreach my $file (@other_files) {
1.574 banghart 8393: print (OUT $file."\n");
1.572 banghart 8394: }
1.574 banghart 8395: close (OUT);
1.572 banghart 8396: return 'ok';
8397: }
8398:
1.574 banghart 8399: sub clear_selected_files {
8400: my ($user) = @_;
8401: my $filename = $user."savedfiles";
1.1117 foxr 8402: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8403: print (OUT undef);
8404: close (OUT);
8405: return ("ok");
8406: }
8407:
1.572 banghart 8408: sub files_in_path {
8409: my ($user, $path) = @_;
8410: my $filename = $user."savedfiles";
8411: my %return_files;
1.1117 foxr 8412: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8413: while (my $line_in = <IN>) {
1.574 banghart 8414: chomp ($line_in);
8415: my @paths_and_file = split (m!/!, $line_in);
8416: my $file_part = pop (@paths_and_file);
8417: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8418: $path_part.='/';
8419: my $path_and_file = $path_part.$file_part;
8420: if ($path_part eq $path) {
8421: $return_files{$file_part}= 'selected';
8422: }
8423: }
1.574 banghart 8424: close (IN);
8425: return (\%return_files);
1.572 banghart 8426: }
8427:
8428: # called in portfolio select mode, to show files selected NOT in current directory
8429: sub files_not_in_path {
8430: my ($user, $path) = @_;
8431: my $filename = $user."savedfiles";
8432: my @return_files;
8433: my $path_part;
1.1117 foxr 8434: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8435: while (my $line = <IN>) {
1.572 banghart 8436: #ok, I know it's clunky, but I want it to work
1.800 albertel 8437: my @paths_and_file = split(m|/|, $line);
8438: my $file_part = pop(@paths_and_file);
8439: chomp($file_part);
8440: my $path_part = join('/', @paths_and_file);
1.572 banghart 8441: $path_part .= '/';
8442: my $path_and_file = $path_part.$file_part;
8443: if ($path_part ne $path) {
1.800 albertel 8444: push(@return_files, ($path_and_file));
1.572 banghart 8445: }
8446: }
1.800 albertel 8447: close(OUT);
1.574 banghart 8448: return (@return_files);
1.572 banghart 8449: }
8450:
1.745 raeburn 8451: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8452:
1.745 raeburn 8453: sub get_portfile_permissions {
8454: my ($domain,$user) = @_;
1.613 albertel 8455: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8456: my ($tmp)=keys(%current_permissions);
8457: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8458: return \%current_permissions;
8459: }
8460:
8461: #---------------------------------------------Get portfolio file access controls
8462:
1.749 raeburn 8463: sub get_access_controls {
1.745 raeburn 8464: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8465: my %access;
8466: my $real_file = $file;
8467: $file =~ s/\.meta$//;
1.745 raeburn 8468: if (defined($file)) {
1.749 raeburn 8469: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8470: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8471: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8472: }
8473: }
1.745 raeburn 8474: } else {
1.749 raeburn 8475: foreach my $key (keys(%{$current_permissions})) {
8476: if ($key =~ /\0accesscontrol$/) {
8477: if (defined($group)) {
8478: if ($key !~ m-^\Q$group\E/-) {
8479: next;
8480: }
8481: }
8482: my ($fullpath) = split(/\0/,$key);
8483: if (ref($$current_permissions{$key}) eq 'HASH') {
8484: foreach my $control (keys(%{$$current_permissions{$key}})) {
8485: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8486: }
8487: }
8488: }
8489: }
8490: }
8491: return %access;
8492: }
8493:
8494: sub modify_access_controls {
8495: my ($file_name,$changes,$domain,$user)=@_;
8496: my ($outcome,$deloutcome);
8497: my %store_permissions;
8498: my %new_values;
8499: my %new_control;
8500: my %translation;
8501: my @deletions = ();
8502: my $now = time;
8503: if (exists($$changes{'activate'})) {
8504: if (ref($$changes{'activate'}) eq 'HASH') {
8505: my @newitems = sort(keys(%{$$changes{'activate'}}));
8506: my $numnew = scalar(@newitems);
8507: for (my $i=0; $i<$numnew; $i++) {
8508: my $newkey = $newitems[$i];
8509: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8510: if ($newkey =~ /^\d+:/) {
8511: $newkey =~ s/^(\d+)/$newid/;
8512: $translation{$1} = $newid;
8513: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8514: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8515: $translation{$1} = $newid;
8516: }
1.749 raeburn 8517: $new_values{$file_name."\0".$newkey} =
8518: $$changes{'activate'}{$newitems[$i]};
8519: $new_control{$newkey} = $now;
8520: }
8521: }
8522: }
8523: my %todelete;
8524: my %changed_items;
8525: foreach my $action ('delete','update') {
8526: if (exists($$changes{$action})) {
8527: if (ref($$changes{$action}) eq 'HASH') {
8528: foreach my $key (keys(%{$$changes{$action}})) {
8529: my ($itemnum) = ($key =~ /^([^:]+):/);
8530: if ($action eq 'delete') {
8531: $todelete{$itemnum} = 1;
8532: } else {
8533: $changed_items{$itemnum} = $key;
8534: }
8535: }
1.745 raeburn 8536: }
8537: }
1.749 raeburn 8538: }
8539: # get lock on access controls for file.
8540: my $lockhash = {
8541: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8542: ':'.$env{'user.domain'},
8543: };
8544: my $tries = 0;
8545: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8546:
8547: while (($gotlock ne 'ok') && $tries <3) {
8548: $tries ++;
8549: sleep 1;
8550: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8551: }
8552: if ($gotlock eq 'ok') {
8553: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8554: my ($tmp)=keys(%curr_permissions);
8555: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8556: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8557: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8558: if (ref($curr_controls) eq 'HASH') {
8559: foreach my $control_item (keys(%{$curr_controls})) {
8560: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8561: if (defined($todelete{$itemnum})) {
8562: push(@deletions,$file_name."\0".$control_item);
8563: } else {
8564: if (defined($changed_items{$itemnum})) {
8565: $new_control{$changed_items{$itemnum}} = $now;
8566: push(@deletions,$file_name."\0".$control_item);
8567: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8568: } else {
8569: $new_control{$control_item} = $$curr_controls{$control_item};
8570: }
8571: }
1.745 raeburn 8572: }
8573: }
8574: }
1.970 raeburn 8575: my ($group);
8576: if (&is_course($domain,$user)) {
8577: ($group,my $file) = split(/\//,$file_name,2);
8578: }
1.749 raeburn 8579: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8580: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8581: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8582: # remove lock
8583: my @del_lock = ($file_name."\0".'locked_access_records');
8584: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8585: my $sqlresult =
1.970 raeburn 8586: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8587: $group);
1.749 raeburn 8588: } else {
8589: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8590: }
1.749 raeburn 8591: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8592: }
8593:
1.827 raeburn 8594: sub make_public_indefinitely {
8595: my ($requrl) = @_;
8596: my $now = time;
8597: my $action = 'activate';
8598: my $aclnum = 0;
8599: if (&is_portfolio_url($requrl)) {
8600: my (undef,$udom,$unum,$file_name,$group) =
8601: &parse_portfolio_url($requrl);
8602: my $current_perms = &get_portfile_permissions($udom,$unum);
8603: my %access_controls = &get_access_controls($current_perms,
8604: $group,$file_name);
8605: foreach my $key (keys(%{$access_controls{$file_name}})) {
8606: my ($num,$scope,$end,$start) =
8607: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8608: if ($scope eq 'public') {
8609: if ($start <= $now && $end == 0) {
8610: $action = 'none';
8611: } else {
8612: $action = 'update';
8613: $aclnum = $num;
8614: }
8615: last;
8616: }
8617: }
8618: if ($action eq 'none') {
8619: return 'ok';
8620: } else {
8621: my %changes;
8622: my $newend = 0;
8623: my $newstart = $now;
8624: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8625: $changes{$action}{$newkey} = {
8626: type => 'public',
8627: time => {
8628: start => $newstart,
8629: end => $newend,
8630: },
8631: };
8632: my ($outcome,$deloutcome,$new_values,$translation) =
8633: &modify_access_controls($file_name,\%changes,$udom,$unum);
8634: return $outcome;
8635: }
8636: } else {
8637: return 'invalid';
8638: }
8639: }
8640:
1.745 raeburn 8641: #------------------------------------------------------Get Marked as Read Only
8642:
8643: sub get_marked_as_readonly {
8644: my ($domain,$user,$what,$group) = @_;
8645: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8646: my @readonly_files;
1.629 banghart 8647: my $cmp1=$what;
8648: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8649: while (my ($file_name,$value) = each(%{$current_permissions})) {
8650: if (defined($group)) {
8651: if ($file_name !~ m-^\Q$group\E/-) {
8652: next;
8653: }
8654: }
1.561 banghart 8655: if (ref($value) eq "ARRAY"){
8656: foreach my $stored_what (@{$value}) {
1.629 banghart 8657: my $cmp2=$stored_what;
1.759 albertel 8658: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8659: $cmp2=join('',@{$stored_what});
1.745 raeburn 8660: }
1.629 banghart 8661: if ($cmp1 eq $cmp2) {
1.561 banghart 8662: push(@readonly_files, $file_name);
1.745 raeburn 8663: last;
1.563 banghart 8664: } elsif (!defined($what)) {
8665: push(@readonly_files, $file_name);
1.745 raeburn 8666: last;
1.561 banghart 8667: }
8668: }
1.745 raeburn 8669: }
1.561 banghart 8670: }
8671: return @readonly_files;
8672: }
1.577 banghart 8673: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8674:
1.577 banghart 8675: sub get_marked_as_readonly_hash {
1.745 raeburn 8676: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8677: my %readonly_files;
1.745 raeburn 8678: while (my ($file_name,$value) = each(%{$current_permissions})) {
8679: if (defined($group)) {
8680: if ($file_name !~ m-^\Q$group\E/-) {
8681: next;
8682: }
8683: }
1.577 banghart 8684: if (ref($value) eq "ARRAY"){
8685: foreach my $stored_what (@{$value}) {
1.745 raeburn 8686: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8687: foreach my $lock_descriptor(@{$stored_what}) {
8688: if ($lock_descriptor eq 'graded') {
8689: $readonly_files{$file_name} = 'graded';
8690: } elsif ($lock_descriptor eq 'handback') {
8691: $readonly_files{$file_name} = 'handback';
8692: } else {
8693: if (!exists($readonly_files{$file_name})) {
8694: $readonly_files{$file_name} = 'locked';
8695: }
8696: }
1.745 raeburn 8697: }
1.750 banghart 8698: }
1.577 banghart 8699: }
8700: }
8701: }
8702: return %readonly_files;
8703: }
1.559 banghart 8704: # ------------------------------------------------------------ Unmark as Read Only
8705:
8706: sub unmark_as_readonly {
1.629 banghart 8707: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8708: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8709: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8710: $file_name = &declutter_portfile($file_name);
1.634 albertel 8711: my $symb_crs = $what;
8712: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8713: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8714: my ($tmp)=keys(%current_permissions);
8715: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8716: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8717: foreach my $file (@readonly_files) {
1.759 albertel 8718: my $clean_file = &declutter_portfile($file);
8719: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8720: my $current_locks = $current_permissions{$file};
1.563 banghart 8721: my @new_locks;
8722: my @del_keys;
8723: if (ref($current_locks) eq "ARRAY"){
8724: foreach my $locker (@{$current_locks}) {
1.632 albertel 8725: my $compare=$locker;
1.749 raeburn 8726: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8727: $compare=join('',@{$locker});
1.746 raeburn 8728: if ($compare ne $symb_crs) {
8729: push(@new_locks, $locker);
8730: }
1.563 banghart 8731: }
8732: }
1.650 albertel 8733: if (scalar(@new_locks) > 0) {
1.563 banghart 8734: $current_permissions{$file} = \@new_locks;
8735: } else {
8736: push(@del_keys, $file);
1.613 albertel 8737: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8738: delete($current_permissions{$file});
1.563 banghart 8739: }
8740: }
1.561 banghart 8741: }
1.613 albertel 8742: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8743: return;
8744: }
1.512 banghart 8745:
1.17 www 8746: # ------------------------------------------------------------ Directory lister
8747:
8748: sub dirlist {
1.955 raeburn 8749: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8750: $uri=~s/^\///;
8751: $uri=~s/\/$//;
1.253 stredwic 8752: my ($udom, $uname);
1.955 raeburn 8753: if ($getuserdir) {
1.253 stredwic 8754: $udom = $userdomain;
8755: $uname = $username;
1.955 raeburn 8756: } else {
8757: (undef,$udom,$uname)=split(/\//,$uri);
8758: if(defined($userdomain)) {
8759: $udom = $userdomain;
8760: }
8761: if(defined($username)) {
8762: $uname = $username;
8763: }
1.253 stredwic 8764: }
1.955 raeburn 8765: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8766:
1.955 raeburn 8767: $dirRoot = $perlvar{'lonDocRoot'};
8768: if (defined($getpropath)) {
8769: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8770: $dirRoot =~ s/\/$//;
1.955 raeburn 8771: } elsif (defined($getuserdir)) {
8772: my $subdir=$uname.'__';
8773: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8774: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8775: ."/$udom/$subdir/$uname";
8776: } elsif (defined($alternateRoot)) {
8777: $dirRoot = $alternateRoot;
1.751 banghart 8778: }
1.253 stredwic 8779:
8780: if($udom) {
8781: if($uname) {
1.1135 raeburn 8782: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8783: if ($uhome eq 'no_host') {
8784: return ([],'no_host');
8785: }
1.955 raeburn 8786: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8787: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8788: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8789: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8790: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8791: } else {
8792: @listing_results = map { &unescape($_); } split(/:/,$listing);
8793: }
1.605 matthew 8794: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8795: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8796: @listing_results = split(/:/,$listing);
8797: } else {
8798: @listing_results = map { &unescape($_); } split(/:/,$listing);
8799: }
1.1135 raeburn 8800: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8801: ($listing eq 'rejected') || ($listing eq 'refused') ||
8802: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8803: return ([],$listing);
8804: } else {
8805: return (\@listing_results);
1.1135 raeburn 8806: }
1.955 raeburn 8807: } elsif(!$alternateRoot) {
1.1136 raeburn 8808: my (%allusers,%listerror);
1.841 albertel 8809: my %servers = &get_servers($udom,'library');
1.955 raeburn 8810: foreach my $tryserver (keys(%servers)) {
8811: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8812: &escape($udom),$tryserver);
8813: if ($listing eq 'unknown_cmd') {
8814: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8815: $udom, $tryserver);
8816: } else {
8817: @listing_results = map { &unescape($_); } split(/:/,$listing);
8818: }
1.841 albertel 8819: if ($listing eq 'unknown_cmd') {
8820: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8821: $udom, $tryserver);
8822: @listing_results = split(/:/,$listing);
8823: } else {
8824: @listing_results =
8825: map { &unescape($_); } split(/:/,$listing);
8826: }
1.1136 raeburn 8827: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8828: ($listing eq 'rejected') || ($listing eq 'refused') ||
8829: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8830: $listerror{$tryserver} = $listing;
8831: } else {
1.841 albertel 8832: foreach my $line (@listing_results) {
8833: my ($entry) = split(/&/,$line,2);
8834: $allusers{$entry} = 1;
8835: }
8836: }
1.253 stredwic 8837: }
1.1136 raeburn 8838: my @alluserslist=();
1.800 albertel 8839: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8840: push(@alluserslist,$user.'&user');
1.253 stredwic 8841: }
1.1136 raeburn 8842: return (\@alluserslist);
1.253 stredwic 8843: } else {
1.1136 raeburn 8844: return ([],'missing username');
1.253 stredwic 8845: }
1.955 raeburn 8846: } elsif(!defined($getpropath)) {
1.1136 raeburn 8847: my $path = $perlvar{'lonDocRoot'}.'/res/';
8848: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8849: return (\@all_domains);
1.955 raeburn 8850: } else {
1.1136 raeburn 8851: return ([],'missing domain');
1.275 stredwic 8852: }
8853: }
8854:
8855: # --------------------------------------------- GetFileTimestamp
8856: # This function utilizes dirlist and returns the date stamp for
8857: # when it was last modified. It will also return an error of -1
8858: # if an error occurs
8859:
8860: sub GetFileTimestamp {
1.955 raeburn 8861: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8862: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8863: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8864: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8865: undef,$getuserdir);
8866: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8867: return -1;
8868: }
8869: if (ref($fileref) eq 'ARRAY') {
8870: my @stats = split('&',$fileref->[0]);
1.375 matthew 8871: # @stats contains first the filename, then the stat output
8872: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8873: } else {
8874: return -1;
1.253 stredwic 8875: }
1.26 www 8876: }
8877:
1.712 albertel 8878: sub stat_file {
8879: my ($uri) = @_;
1.787 albertel 8880: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8881:
1.955 raeburn 8882: my ($udom,$uname,$file);
1.712 albertel 8883: if ($uri =~ m-^/(uploaded|editupload)/-) {
8884: ($udom,$uname,$file) =
1.811 albertel 8885: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8886: $file = 'userfiles/'.$file;
8887: }
8888: if ($uri =~ m-^/res/-) {
8889: ($udom,$uname) =
1.807 albertel 8890: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8891: $file = $uri;
8892: }
8893:
8894: if (!$udom || !$uname || !$file) {
8895: # unable to handle the uri
8896: return ();
8897: }
1.956 raeburn 8898: my $getpropath;
8899: if ($file =~ /^userfiles\//) {
8900: $getpropath = 1;
8901: }
1.1136 raeburn 8902: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8903: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8904: return ();
8905: } else {
8906: if (ref($listref) eq 'ARRAY') {
8907: my @stats = split('&',$listref->[0]);
8908: shift(@stats); #filename is first
8909: return @stats;
8910: }
1.712 albertel 8911: }
8912: return ();
8913: }
8914:
1.26 www 8915: # -------------------------------------------------------- Value of a Condition
8916:
1.713 albertel 8917: # gets the value of a specific preevaluated condition
8918: # stored in the string $env{user.state.<cid>}
8919: # or looks up a condition reference in the bighash and if if hasn't
8920: # already been evaluated recurses into docondval to get the value of
8921: # the condition, then memoizing it to
8922: # $env{user.state.<cid>.<condition>}
1.40 www 8923: sub directcondval {
8924: my $number=shift;
1.620 albertel 8925: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8926: &Apache::lonuserstate::evalstate();
8927: }
1.713 albertel 8928: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8929: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8930: } elsif ($number =~ /^_/) {
8931: my $sub_condition;
8932: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8933: &GDBM_READER(),0640)) {
8934: $sub_condition=$bighash{'conditions'.$number};
8935: untie(%bighash);
8936: }
8937: my $value = &docondval($sub_condition);
1.949 raeburn 8938: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8939: return $value;
8940: }
1.620 albertel 8941: if ($env{'user.state.'.$env{'request.course.id'}}) {
8942: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8943: } else {
8944: return 2;
8945: }
8946: }
8947:
1.713 albertel 8948: # get the collection of conditions for this resource
1.26 www 8949: sub condval {
8950: my $condidx=shift;
1.54 www 8951: my $allpathcond='';
1.713 albertel 8952: foreach my $cond (split(/\|/,$condidx)) {
8953: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8954: $allpathcond.=
8955: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8956: }
1.191 harris41 8957: }
1.54 www 8958: $allpathcond=~s/\|$//;
1.713 albertel 8959: return &docondval($allpathcond);
8960: }
8961:
8962: #evaluates an expression of conditions
8963: sub docondval {
8964: my ($allpathcond) = @_;
8965: my $result=0;
8966: if ($env{'request.course.id'}
8967: && defined($allpathcond)) {
8968: my $operand='|';
8969: my @stack;
8970: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8971: if ($chunk eq '(') {
8972: push @stack,($operand,$result);
8973: } elsif ($chunk eq ')') {
8974: my $before=pop @stack;
8975: if (pop @stack eq '&') {
8976: $result=$result>$before?$before:$result;
8977: } else {
8978: $result=$result>$before?$result:$before;
8979: }
8980: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8981: $operand=$chunk;
8982: } else {
8983: my $new=directcondval($chunk);
8984: if ($operand eq '&') {
8985: $result=$result>$new?$new:$result;
8986: } else {
8987: $result=$result>$new?$result:$new;
8988: }
8989: }
8990: }
1.26 www 8991: }
8992: return $result;
1.421 albertel 8993: }
8994:
8995: # ---------------------------------------------------- Devalidate courseresdata
8996:
8997: sub devalidatecourseresdata {
8998: my ($coursenum,$coursedomain)=@_;
8999: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9000: &devalidate_cache_new('courseres',$hashid);
1.28 www 9001: }
9002:
1.763 www 9003:
1.200 www 9004: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9005: #
9006: # Parameters:
9007: # $coursenum - Number of the course.
9008: # $coursedomain - Domain at which the course was created.
9009: # Returns:
9010: # A hash of the course parameters along (I think) with timestamps
9011: # and version info.
1.877 foxr 9012:
1.624 albertel 9013: sub get_courseresdata {
9014: my ($coursenum,$coursedomain)=@_;
1.200 www 9015: my $coursehom=&homeserver($coursenum,$coursedomain);
9016: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9017: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9018: my %dumpreply;
1.417 albertel 9019: unless (defined($cached)) {
1.624 albertel 9020: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9021: $result=\%dumpreply;
1.251 albertel 9022: my ($tmp) = keys(%dumpreply);
9023: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9024: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9025: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9026: return $tmp;
1.416 albertel 9027: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9028: $result=undef;
1.599 albertel 9029: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9030: }
9031: }
1.624 albertel 9032: return $result;
9033: }
9034:
1.633 albertel 9035: sub devalidateuserresdata {
9036: my ($uname,$udom)=@_;
9037: my $hashid="$udom:$uname";
9038: &devalidate_cache_new('userres',$hashid);
9039: }
9040:
1.624 albertel 9041: sub get_userresdata {
9042: my ($uname,$udom)=@_;
9043: #most student don\'t have any data set, check if there is some data
9044: if (&EXT_cache_status($udom,$uname)) { return undef; }
9045:
9046: my $hashid="$udom:$uname";
9047: my ($result,$cached)=&is_cached_new('userres',$hashid);
9048: if (!defined($cached)) {
9049: my %resourcedata=&dump('resourcedata',$udom,$uname);
9050: $result=\%resourcedata;
9051: &do_cache_new('userres',$hashid,$result,600);
9052: }
9053: my ($tmp)=keys(%$result);
9054: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9055: return $result;
9056: }
9057: #error 2 occurs when the .db doesn't exist
9058: if ($tmp!~/error: 2 /) {
1.672 albertel 9059: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9060: " Trying to get resource data for ".
9061: $uname." at ".$udom.": ".
9062: $tmp."</font>");
9063: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9064: #&EXT_cache_set($udom,$uname);
9065: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9066: undef($tmp); # not really an error so don't send it back
1.624 albertel 9067: }
9068: return $tmp;
9069: }
1.879 foxr 9070: #----------------------------------------------- resdata - return resource data
9071: # Purpose:
9072: # Return resource data for either users or for a course.
9073: # Parameters:
9074: # $name - Course/user name.
9075: # $domain - Name of the domain the user/course is registered on.
9076: # $type - Type of thing $name is (must be 'course' or 'user'
9077: # @which - Array of names of resources desired.
9078: # Returns:
9079: # The value of the first reasource in @which that is found in the
9080: # resource hash.
9081: # Exceptional Conditions:
9082: # If the $type passed in is not valid (not the string 'course' or
9083: # 'user', an undefined reference is returned.
9084: # If none of the resources are found, an undef is returned
1.624 albertel 9085: sub resdata {
9086: my ($name,$domain,$type,@which)=@_;
9087: my $result;
9088: if ($type eq 'course') {
9089: $result=&get_courseresdata($name,$domain);
9090: } elsif ($type eq 'user') {
9091: $result=&get_userresdata($name,$domain);
9092: }
9093: if (!ref($result)) { return $result; }
1.251 albertel 9094: foreach my $item (@which) {
1.927 albertel 9095: if (defined($result->{$item->[0]})) {
9096: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9097: }
1.250 albertel 9098: }
1.291 albertel 9099: return undef;
1.200 www 9100: }
9101:
1.379 matthew 9102: #
9103: # EXT resource caching routines
9104: #
9105:
9106: sub clear_EXT_cache_status {
1.383 albertel 9107: &delenv('cache.EXT.');
1.379 matthew 9108: }
9109:
9110: sub EXT_cache_status {
9111: my ($target_domain,$target_user) = @_;
1.383 albertel 9112: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9113: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9114: # We know already the user has no data
9115: return 1;
9116: } else {
9117: return 0;
9118: }
9119: }
9120:
9121: sub EXT_cache_set {
9122: my ($target_domain,$target_user) = @_;
1.383 albertel 9123: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9124: #&appenv({$cachename => time});
1.379 matthew 9125: }
9126:
1.28 www 9127: # --------------------------------------------------------- Value of a Variable
1.58 www 9128: sub EXT {
1.715 albertel 9129:
1.395 albertel 9130: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 9131: unless ($varname) { return ''; }
1.218 albertel 9132: #get real user name/domain, courseid and symb
9133: my $courseid;
1.359 albertel 9134: my $publicuser;
1.427 www 9135: if ($symbparm) {
9136: $symbparm=&get_symb_from_alias($symbparm);
9137: }
1.218 albertel 9138: if (!($uname && $udom)) {
1.790 albertel 9139: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9140: if (!$symbparm) { $symbparm=$cursymb; }
9141: } else {
1.620 albertel 9142: $courseid=$env{'request.course.id'};
1.218 albertel 9143: }
1.48 www 9144: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9145: my $rest;
1.320 albertel 9146: if (defined($therest[0])) {
1.48 www 9147: $rest=join('.',@therest);
9148: } else {
9149: $rest='';
9150: }
1.320 albertel 9151:
1.57 www 9152: my $qualifierrest=$qualifier;
9153: if ($rest) { $qualifierrest.='.'.$rest; }
9154: my $spacequalifierrest=$space;
9155: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9156: if ($realm eq 'user') {
1.48 www 9157: # --------------------------------------------------------------- user.resource
9158: if ($space eq 'resource') {
1.651 albertel 9159: if ( (defined($Apache::lonhomework::parsing_a_problem)
9160: || defined($Apache::lonhomework::parsing_a_task))
9161: &&
1.744 albertel 9162: ($symbparm eq &symbread()) ) {
9163: # if we are in the middle of processing the resource the
9164: # get the value we are planning on committing
9165: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9166: return $Apache::lonhomework::results{$qualifierrest};
9167: } else {
9168: return $Apache::lonhomework::history{$qualifierrest};
9169: }
1.335 albertel 9170: } else {
1.359 albertel 9171: my %restored;
1.620 albertel 9172: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9173: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9174: } else {
9175: %restored=&restore($symbparm,$courseid,$udom,$uname);
9176: }
1.335 albertel 9177: return $restored{$qualifierrest};
9178: }
1.48 www 9179: # ----------------------------------------------------------------- user.access
9180: } elsif ($space eq 'access') {
1.218 albertel 9181: # FIXME - not supporting calls for a specific user
1.48 www 9182: return &allowed($qualifier,$rest);
9183: # ------------------------------------------ user.preferences, user.environment
9184: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9185: if (($uname eq $env{'user.name'}) &&
9186: ($udom eq $env{'user.domain'})) {
9187: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9188: } else {
1.359 albertel 9189: my %returnhash;
9190: if (!$publicuser) {
9191: %returnhash=&userenvironment($udom,$uname,
9192: $qualifierrest);
9193: }
1.218 albertel 9194: return $returnhash{$qualifierrest};
9195: }
1.48 www 9196: # ----------------------------------------------------------------- user.course
9197: } elsif ($space eq 'course') {
1.218 albertel 9198: # FIXME - not supporting calls for a specific user
1.620 albertel 9199: return $env{join('.',('request.course',$qualifier))};
1.48 www 9200: # ------------------------------------------------------------------- user.role
9201: } elsif ($space eq 'role') {
1.218 albertel 9202: # FIXME - not supporting calls for a specific user
1.620 albertel 9203: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9204: if ($qualifier eq 'value') {
9205: return $role;
9206: } elsif ($qualifier eq 'extent') {
9207: return $where;
9208: }
9209: # ----------------------------------------------------------------- user.domain
9210: } elsif ($space eq 'domain') {
1.218 albertel 9211: return $udom;
1.48 www 9212: # ------------------------------------------------------------------- user.name
9213: } elsif ($space eq 'name') {
1.218 albertel 9214: return $uname;
1.48 www 9215: # ---------------------------------------------------- Any other user namespace
1.29 www 9216: } else {
1.359 albertel 9217: my %reply;
9218: if (!$publicuser) {
9219: %reply=&get($space,[$qualifierrest],$udom,$uname);
9220: }
9221: return $reply{$qualifierrest};
1.48 www 9222: }
1.236 www 9223: } elsif ($realm eq 'query') {
9224: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9225: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9226: [$spacequalifierrest]);
1.620 albertel 9227: return $env{'form.'.$spacequalifierrest};
1.236 www 9228: } elsif ($realm eq 'request') {
1.48 www 9229: # ------------------------------------------------------------- request.browser
9230: if ($space eq 'browser') {
1.1145 bisitz 9231: return $env{'browser.'.$qualifier};
1.57 www 9232: # ------------------------------------------------------------ request.filename
9233: } else {
1.620 albertel 9234: return $env{'request.'.$spacequalifierrest};
1.29 www 9235: }
1.28 www 9236: } elsif ($realm eq 'course') {
1.48 www 9237: # ---------------------------------------------------------- course.description
1.620 albertel 9238: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9239: } elsif ($realm eq 'resource') {
1.165 www 9240:
1.620 albertel 9241: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9242: if (!$symbparm) { $symbparm=&symbread(); }
9243: }
1.693 albertel 9244:
9245: if ($space eq 'title') {
9246: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9247: return &gettitle($symbparm);
9248: }
9249:
9250: if ($space eq 'map') {
9251: my ($map) = &decode_symb($symbparm);
9252: return &symbread($map);
9253: }
1.905 albertel 9254: if ($space eq 'filename') {
9255: if ($symbparm) {
9256: return &clutter((&decode_symb($symbparm))[2]);
9257: }
9258: return &hreflocation('',$env{'request.filename'});
9259: }
1.693 albertel 9260:
9261: my ($section, $group, @groups);
1.593 albertel 9262: my ($courselevelm,$courselevel);
1.539 albertel 9263: if ($symbparm && defined($courseid) &&
1.620 albertel 9264: $courseid eq $env{'request.course.id'}) {
1.165 www 9265:
1.218 albertel 9266: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9267:
1.60 www 9268: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9269: my $symbp=$symbparm;
1.735 albertel 9270: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9271:
9272: my $symbparm=$symbp.'.'.$spacequalifierrest;
9273: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9274:
1.620 albertel 9275: if (($env{'user.name'} eq $uname) &&
9276: ($env{'user.domain'} eq $udom)) {
9277: $section=$env{'request.course.sec'};
1.733 raeburn 9278: @groups = split(/:/,$env{'request.course.groups'});
9279: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9280: } else {
1.539 albertel 9281: if (! defined($usection)) {
1.551 albertel 9282: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9283: } else {
9284: $section = $usection;
9285: }
1.733 raeburn 9286: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9287: }
9288:
9289: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9290: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9291: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9292:
1.593 albertel 9293: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9294: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9295: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9296:
1.60 www 9297: # ----------------------------------------------------------- first, check user
1.624 albertel 9298:
9299: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9300: ([$courselevelr,'resource'],
9301: [$courselevelm,'map' ],
9302: [$courselevel, 'course' ]));
1.931 albertel 9303: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9304:
1.594 albertel 9305: # ------------------------------------------------ second, check some of course
1.684 raeburn 9306: my $coursereply;
1.691 raeburn 9307: if (@groups > 0) {
9308: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9309: $mapparm,$spacequalifierrest);
1.927 albertel 9310: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9311: }
1.96 www 9312:
1.684 raeburn 9313: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9314: $env{'course.'.$courseid.'.domain'},
9315: 'course',
9316: ([$seclevelr, 'resource'],
9317: [$seclevelm, 'map' ],
9318: [$seclevel, 'course' ],
9319: [$courselevelr,'resource']));
9320: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9321:
1.60 www 9322: # ------------------------------------------------------ third, check map parms
1.218 albertel 9323: my %parmhash=();
9324: my $thisparm='';
9325: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9326: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9327: &GDBM_READER(),0640)) {
1.218 albertel 9328: $thisparm=$parmhash{$symbparm};
9329: untie(%parmhash);
9330: }
1.927 albertel 9331: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9332: }
1.594 albertel 9333: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9334:
1.218 albertel 9335: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9336: my $filename;
9337: if (!$symbparm) { $symbparm=&symbread(); }
9338: if ($symbparm) {
1.409 www 9339: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9340: } else {
1.620 albertel 9341: $filename=$env{'request.filename'};
1.282 albertel 9342: }
9343: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9344: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9345: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9346: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9347:
1.927 albertel 9348: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9349: if ($symbparm && defined($courseid) &&
1.620 albertel 9350: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9351: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9352: $env{'course.'.$courseid.'.domain'},
9353: 'course',
1.927 albertel 9354: ([$courselevelm,'map' ],
9355: [$courselevel, 'course']));
9356: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9357: }
1.145 www 9358: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9359: unless ($space eq '0') {
1.336 albertel 9360: my @parts=split(/_/,$space);
9361: my $id=pop(@parts);
9362: my $part=join('_',@parts);
9363: if ($part eq '') { $part='0'; }
1.927 albertel 9364: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9365: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9366: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9367: }
1.395 albertel 9368: if ($recurse) { return undef; }
9369: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9370: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9371: # ---------------------------------------------------- Any other user namespace
9372: } elsif ($realm eq 'environment') {
9373: # ----------------------------------------------------------------- environment
1.620 albertel 9374: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9375: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9376: } else {
1.770 albertel 9377: if ($uname eq 'anonymous' && $udom eq '') {
9378: return '';
9379: }
1.219 albertel 9380: my %returnhash=&userenvironment($udom,$uname,
9381: $spacequalifierrest);
9382: return $returnhash{$spacequalifierrest};
9383: }
1.28 www 9384: } elsif ($realm eq 'system') {
1.48 www 9385: # ----------------------------------------------------------------- system.time
9386: if ($space eq 'time') {
9387: return time;
9388: }
1.696 albertel 9389: } elsif ($realm eq 'server') {
9390: # ----------------------------------------------------------------- system.time
9391: if ($space eq 'name') {
9392: return $ENV{'SERVER_NAME'};
9393: }
1.28 www 9394: }
1.48 www 9395: return '';
1.61 www 9396: }
9397:
1.927 albertel 9398: sub get_reply {
9399: my ($reply_value) = @_;
1.940 raeburn 9400: if (ref($reply_value) eq 'ARRAY') {
9401: if (wantarray) {
9402: return @$reply_value;
9403: }
9404: return $reply_value->[0];
9405: } else {
9406: return $reply_value;
1.927 albertel 9407: }
9408: }
9409:
1.691 raeburn 9410: sub check_group_parms {
9411: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9412: my @groupitems = ();
9413: my $resultitem;
1.927 albertel 9414: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9415: foreach my $group (@{$groups}) {
9416: foreach my $level (@levels) {
1.927 albertel 9417: my $item = $courseid.'.['.$group.'].'.$level->[0];
9418: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9419: }
9420: }
9421: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9422: $env{'course.'.$courseid.'.domain'},
9423: 'course',@groupitems);
9424: return $coursereply;
9425: }
9426:
9427: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9428: my ($courseid,@groups) = @_;
9429: @groups = sort(@groups);
1.691 raeburn 9430: return @groups;
9431: }
9432:
1.395 albertel 9433: sub packages_tab_default {
9434: my ($uri,$varname)=@_;
9435: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9436:
9437: my (@extension,@specifics,$do_default);
9438: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9439: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9440: if ($pack_type eq 'default') {
9441: $do_default=1;
9442: } elsif ($pack_type eq 'extension') {
9443: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9444: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9445: # only look at packages defaults for packages that this id is
1.738 albertel 9446: push(@specifics,[$package,$pack_type,$pack_part]);
9447: }
9448: }
9449: # first look for a package that matches the requested part id
9450: foreach my $package (@specifics) {
9451: my (undef,$pack_type,$pack_part)=@{$package};
9452: next if ($pack_part ne $part);
9453: if (defined($packagetab{"$pack_type&$name&default"})) {
9454: return $packagetab{"$pack_type&$name&default"};
9455: }
9456: }
9457: # look for any possible matching non extension_ package
9458: foreach my $package (@specifics) {
9459: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9460: if (defined($packagetab{"$pack_type&$name&default"})) {
9461: return $packagetab{"$pack_type&$name&default"};
9462: }
1.585 albertel 9463: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9464: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9465: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9466: }
9467: }
1.738 albertel 9468: # look for any posible extension_ match
9469: foreach my $package (@extension) {
9470: my ($package,$pack_type)=@{$package};
9471: if (defined($packagetab{"$pack_type&$name&default"})) {
9472: return $packagetab{"$pack_type&$name&default"};
9473: }
9474: if (defined($packagetab{$package."&$name&default"})) {
9475: return $packagetab{$package."&$name&default"};
9476: }
9477: }
9478: # look for a global default setting
9479: if ($do_default && defined($packagetab{"default&$name&default"})) {
9480: return $packagetab{"default&$name&default"};
9481: }
1.395 albertel 9482: return undef;
9483: }
9484:
1.334 albertel 9485: sub add_prefix_and_part {
9486: my ($prefix,$part)=@_;
9487: my $keyroot;
9488: if (defined($prefix) && $prefix !~ /^__/) {
9489: # prefix that has a part already
9490: $keyroot=$prefix;
9491: } elsif (defined($prefix)) {
9492: # prefix that is missing a part
9493: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9494: } else {
9495: # no prefix at all
9496: if (defined($part)) { $keyroot='_'.$part; }
9497: }
9498: return $keyroot;
9499: }
9500:
1.71 www 9501: # ---------------------------------------------------------------- Get metadata
9502:
1.599 albertel 9503: my %metaentry;
1.1070 www 9504: my %importedpartids;
1.71 www 9505: sub metadata {
1.176 www 9506: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9507: $uri=&declutter($uri);
1.288 albertel 9508: # if it is a non metadata possible uri return quickly
1.529 albertel 9509: if (($uri eq '') ||
9510: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9511: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9512: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9513: return undef;
9514: }
1.1140 www 9515: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9516: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9517: return undef;
1.288 albertel 9518: }
1.73 www 9519: my $filename=$uri;
9520: $uri=~s/\.meta$//;
1.172 www 9521: #
9522: # Is the metadata already cached?
1.177 www 9523: # Look at timestamp of caching
1.172 www 9524: # Everything is cached by the main uri, libraries are never directly cached
9525: #
1.428 albertel 9526: if (!defined($liburi)) {
1.599 albertel 9527: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9528: if (defined($cached)) { return $result->{':'.$what}; }
9529: }
9530: {
1.1069 www 9531: # Imported parts would go here
1.1070 www 9532: my %importedids=();
9533: my @origfileimportpartids=();
1.1069 www 9534: my $importedparts=0;
1.172 www 9535: #
9536: # Is this a recursive call for a library?
9537: #
1.599 albertel 9538: # if (! exists($metacache{$uri})) {
9539: # $metacache{$uri}={};
9540: # }
1.924 albertel 9541: my $cachetime = 60*60;
1.171 www 9542: if ($liburi) {
9543: $liburi=&declutter($liburi);
9544: $filename=$liburi;
1.401 bowersj2 9545: } else {
1.599 albertel 9546: &devalidate_cache_new('meta',$uri);
9547: undef(%metaentry);
1.401 bowersj2 9548: }
1.140 www 9549: my %metathesekeys=();
1.73 www 9550: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9551: my $metastring;
1.1140 www 9552: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9553: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9554: $metastring =
1.929 albertel 9555: &Apache::lonnet::ssi_body($which,
1.924 albertel 9556: ('grade_target' => 'meta'));
9557: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9558: } elsif (($uri !~ m -^(editupload)/-) &&
9559: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9560: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9561: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9562: $metastring=&getfile($file);
1.489 albertel 9563: }
1.208 albertel 9564: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9565: my $token;
1.140 www 9566: undef %metathesekeys;
1.71 www 9567: while ($token=$parser->get_token) {
1.339 albertel 9568: if ($token->[0] eq 'S') {
9569: if (defined($token->[2]->{'package'})) {
1.172 www 9570: #
9571: # This is a package - get package info
9572: #
1.339 albertel 9573: my $package=$token->[2]->{'package'};
9574: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9575: if (defined($token->[2]->{'id'})) {
9576: $keyroot.='_'.$token->[2]->{'id'};
9577: }
1.599 albertel 9578: if ($metaentry{':packages'}) {
9579: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9580: } else {
1.599 albertel 9581: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9582: }
1.736 albertel 9583: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9584: my $part=$keyroot;
9585: $part=~s/^\_//;
1.736 albertel 9586: if ($pack_entry=~/^\Q$package\E\&/ ||
9587: $pack_entry=~/^\Q$package\E_0\&/) {
9588: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9589: # ignore package.tab specified default values
9590: # here &package_tab_default() will fetch those
9591: if ($subp eq 'default') { next; }
1.736 albertel 9592: my $value=$packagetab{$pack_entry};
1.432 albertel 9593: my $unikey;
9594: if ($pack =~ /_0$/) {
9595: $unikey='parameter_0_'.$name;
9596: $part=0;
9597: } else {
9598: $unikey='parameter'.$keyroot.'_'.$name;
9599: }
1.339 albertel 9600: if ($subp eq 'display') {
9601: $value.=' [Part: '.$part.']';
9602: }
1.599 albertel 9603: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9604: $metathesekeys{$unikey}=1;
1.599 albertel 9605: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9606: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9607: }
1.599 albertel 9608: if (defined($metaentry{':'.$unikey.'.default'})) {
9609: $metaentry{':'.$unikey}=
9610: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9611: }
1.339 albertel 9612: }
9613: }
9614: } else {
1.172 www 9615: #
9616: # This is not a package - some other kind of start tag
1.339 albertel 9617: #
9618: my $entry=$token->[1];
1.1068 www 9619: my $unikey='';
1.175 www 9620:
1.339 albertel 9621: if ($entry eq 'import') {
1.175 www 9622: #
9623: # Importing a library here
1.339 albertel 9624: #
1.1067 www 9625: my $location=$parser->get_text('/import');
9626: my $dir=$filename;
9627: $dir=~s|[^/]*$||;
9628: $location=&filelocation($dir,$location);
1.1069 www 9629:
1.1068 www 9630: my $importmode=$token->[2]->{'importmode'};
9631: if ($importmode eq 'problem') {
1.1069 www 9632: # Import as problem/response
1.1068 www 9633: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9634: } elsif ($importmode eq 'part') {
9635: # Import as part(s)
1.1069 www 9636: $importedparts=1;
9637: # We need to get the original file and the imported file to get the part order correct
9638: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9639: # Load and inspect original file
1.1070 www 9640: if ($#origfileimportpartids<0) {
9641: undef(%importedpartids);
9642: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9643: my $origfile=&getfile($origfilelocation);
9644: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9645: }
9646:
1.1069 www 9647: # Load and inspect imported file
9648: my $impfile=&getfile($location);
9649: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9650: if ($#impfilepartids>=0) {
9651: # This problem had parts
1.1070 www 9652: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9653: } else {
9654: # Importing by turning a single problem into a problem part
9655: # It gets the import-tags ID as part-ID
9656: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9657: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9658: }
1.1068 www 9659: } else {
9660: # Normal import
9661: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9662: if (defined($token->[2]->{'id'})) {
9663: $unikey.='_'.$token->[2]->{'id'};
9664: }
1.1067 www 9665: }
9666:
1.339 albertel 9667: if ($depthcount<20) {
1.736 albertel 9668: my $metadata =
9669: &metadata($uri,'keys', $location,$unikey,
9670: $depthcount+1);
9671: foreach my $meta (split(',',$metadata)) {
9672: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9673: $metathesekeys{$meta}=1;
1.339 albertel 9674: }
1.1068 www 9675:
9676: }
1.1067 www 9677: } else {
9678: #
9679: # Not importing, some other kind of non-package, non-library start tag
9680: #
9681: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9682: if (defined($token->[2]->{'id'})) {
9683: $unikey.='_'.$token->[2]->{'id'};
9684: }
1.339 albertel 9685: if (defined($token->[2]->{'name'})) {
9686: $unikey.='_'.$token->[2]->{'name'};
9687: }
9688: $metathesekeys{$unikey}=1;
1.736 albertel 9689: foreach my $param (@{$token->[3]}) {
9690: $metaentry{':'.$unikey.'.'.$param} =
9691: $token->[2]->{$param};
1.339 albertel 9692: }
9693: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9694: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9695: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9696: # only ws inside the tag, and not in default, so use default
9697: # as value
1.599 albertel 9698: $metaentry{':'.$unikey}=$default;
1.908 albertel 9699: } elsif ( $internaltext =~ /\S/ ) {
9700: # something interesting inside the tag
9701: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9702: } else {
1.908 albertel 9703: # no interesting values, don't set a default
1.339 albertel 9704: }
1.172 www 9705: # end of not-a-package not-a-library import
1.339 albertel 9706: }
1.172 www 9707: # end of not-a-package start tag
1.339 albertel 9708: }
1.172 www 9709: # the next is the end of "start tag"
1.339 albertel 9710: }
9711: }
1.483 albertel 9712: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9713: $extension = lc($extension);
9714: if ($extension eq 'htm') { $extension='html'; }
9715:
1.737 albertel 9716: foreach my $key (keys(%packagetab)) {
1.483 albertel 9717: #no specific packages #how's our extension
9718: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9719: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9720: \%metathesekeys);
9721: }
1.883 albertel 9722:
9723: if (!exists($metaentry{':packages'})
9724: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9725: foreach my $key (keys(%packagetab)) {
1.483 albertel 9726: #no specific packages well let's get default then
9727: if ($key!~/^default&/) { next; }
1.488 albertel 9728: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9729: \%metathesekeys);
9730: }
9731: }
1.338 www 9732: # are there custom rights to evaluate
1.599 albertel 9733: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9734:
1.338 www 9735: #
9736: # Importing a rights file here
1.339 albertel 9737: #
9738: unless ($depthcount) {
1.599 albertel 9739: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9740: my $dir=$filename;
9741: $dir=~s|[^/]*$||;
9742: $location=&filelocation($dir,$location);
1.736 albertel 9743: my $rights_metadata =
9744: &metadata($uri,'keys',$location,'_rights',
9745: $depthcount+1);
9746: foreach my $rights (split(',',$rights_metadata)) {
9747: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9748: $metathesekeys{$rights}=1;
1.339 albertel 9749: }
9750: }
9751: }
1.737 albertel 9752: # uniqifiy package listing
9753: my %seen;
9754: my @uniq_packages =
9755: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9756: $metaentry{':packages'} = join(',',@uniq_packages);
9757:
1.1070 www 9758: if ($importedparts) {
9759: # We had imported parts and need to rebuild partorder
9760: $metaentry{':partorder'}='';
9761: $metathesekeys{'partorder'}=1;
9762: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9763: if ($origfileimportpartids[$index] eq 'part') {
9764: # original part, part of the problem
9765: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9766: } else {
9767: # we have imported parts at this position
9768: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9769: }
9770: }
9771: $metaentry{':partorder'}=~s/^\,//;
9772: }
9773:
1.737 albertel 9774: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9775: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9776: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9777: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9778: # this is the end of "was not already recently cached
1.71 www 9779: }
1.599 albertel 9780: return $metaentry{':'.$what};
1.261 albertel 9781: }
9782:
1.488 albertel 9783: sub metadata_create_package_def {
1.483 albertel 9784: my ($uri,$key,$package,$metathesekeys)=@_;
9785: my ($pack,$name,$subp)=split(/\&/,$key);
9786: if ($subp eq 'default') { next; }
9787:
1.599 albertel 9788: if (defined($metaentry{':packages'})) {
9789: $metaentry{':packages'}.=','.$package;
1.483 albertel 9790: } else {
1.599 albertel 9791: $metaentry{':packages'}=$package;
1.483 albertel 9792: }
9793: my $value=$packagetab{$key};
9794: my $unikey;
9795: $unikey='parameter_0_'.$name;
1.599 albertel 9796: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9797: $$metathesekeys{$unikey}=1;
1.599 albertel 9798: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9799: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9800: }
1.599 albertel 9801: if (defined($metaentry{':'.$unikey.'.default'})) {
9802: $metaentry{':'.$unikey}=
9803: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9804: }
9805: }
9806:
1.261 albertel 9807: sub metadata_generate_part0 {
9808: my ($metadata,$metacache,$uri) = @_;
9809: my %allnames;
1.737 albertel 9810: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9811: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9812: my $part=$$metacache{':'.$metakey.'.part'};
9813: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9814: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9815: $allnames{$name}=$part;
9816: }
9817: }
9818: }
9819: foreach my $name (keys(%allnames)) {
9820: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9821: my $key=":parameter_0_$name";
1.261 albertel 9822: $$metacache{"$key.part"}='0';
9823: $$metacache{"$key.name"}=$name;
1.428 albertel 9824: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9825: $allnames{$name}.'_'.$name.
9826: '.type'};
1.428 albertel 9827: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9828: '.display'};
1.644 www 9829: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9830: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9831: $$metacache{"$key.display"}=$olddis;
9832: }
1.71 www 9833: }
9834:
1.764 albertel 9835: # ------------------------------------------------------ Devalidate title cache
9836:
9837: sub devalidate_title_cache {
9838: my ($url)=@_;
9839: if (!$env{'request.course.id'}) { return; }
9840: my $symb=&symbread($url);
9841: if (!$symb) { return; }
9842: my $key=$env{'request.course.id'}."\0".$symb;
9843: &devalidate_cache_new('title',$key);
9844: }
9845:
1.1014 droeschl 9846: # ------------------------------------------------- Get the title of a course
9847:
9848: sub current_course_title {
9849: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9850: }
1.301 www 9851: # ------------------------------------------------- Get the title of a resource
9852:
9853: sub gettitle {
9854: my $urlsymb=shift;
9855: my $symb=&symbread($urlsymb);
1.534 albertel 9856: if ($symb) {
1.620 albertel 9857: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9858: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9859: if (defined($cached)) {
9860: return $result;
9861: }
1.534 albertel 9862: my ($map,$resid,$url)=&decode_symb($symb);
9863: my $title='';
1.907 albertel 9864: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9865: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9866: } else {
9867: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9868: &GDBM_READER(),0640)) {
9869: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9870: $title=$bighash{'title_'.$mapid.'.'.$resid};
9871: untie(%bighash);
9872: }
1.534 albertel 9873: }
9874: $title=~s/\&colon\;/\:/gs;
9875: if ($title) {
1.1159 www 9876: # Remember both $symb and $title for dynamic metadata
9877: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9878: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9879: # Cache this title and then return it
1.599 albertel 9880: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9881: }
9882: $urlsymb=$url;
9883: }
9884: my $title=&metadata($urlsymb,'title');
9885: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9886: return $title;
1.301 www 9887: }
1.613 albertel 9888:
1.614 albertel 9889: sub get_slot {
9890: my ($which,$cnum,$cdom)=@_;
9891: if (!$cnum || !$cdom) {
1.790 albertel 9892: (undef,my $courseid)=&whichuser();
1.620 albertel 9893: $cdom=$env{'course.'.$courseid.'.domain'};
9894: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9895: }
1.703 albertel 9896: my $key=join("\0",'slots',$cdom,$cnum,$which);
9897: my %slotinfo;
9898: if (exists($remembered{$key})) {
9899: $slotinfo{$which} = $remembered{$key};
9900: } else {
9901: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9902: &Apache::lonhomework::showhash(%slotinfo);
9903: my ($tmp)=keys(%slotinfo);
9904: if ($tmp=~/^error:/) { return (); }
9905: $remembered{$key} = $slotinfo{$which};
9906: }
1.616 albertel 9907: if (ref($slotinfo{$which}) eq 'HASH') {
9908: return %{$slotinfo{$which}};
9909: }
9910: return $slotinfo{$which};
1.614 albertel 9911: }
1.1150 raeburn 9912:
9913: sub get_reservable_slots {
9914: my ($cnum,$cdom,$uname,$udom) = @_;
9915: my $now = time;
9916: my $reservable_info;
9917: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9918: if (exists($remembered{$key})) {
9919: $reservable_info = $remembered{$key};
9920: } else {
9921: my %resv;
9922: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9923: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9924: $reservable_info = \%resv;
9925: $remembered{$key} = $reservable_info;
9926: }
9927: return $reservable_info;
9928: }
9929:
9930: sub get_course_slots {
9931: my ($cnum,$cdom) = @_;
9932: my $hashid=$cnum.':'.$cdom;
9933: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9934: if (defined($cached)) {
9935: if (ref($result) eq 'HASH') {
9936: return %{$result};
9937: }
9938: } else {
9939: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9940: my ($tmp) = keys(%slots);
9941: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9942: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9943: return %slots;
9944: }
9945: }
9946: return;
9947: }
9948:
9949: sub devalidate_slots_cache {
9950: my ($cnum,$cdom)=@_;
9951: my $hashid=$cnum.':'.$cdom;
9952: &devalidate_cache_new('allslots',$hashid);
9953: }
9954:
1.1181 raeburn 9955: sub get_coursechange {
9956: my ($cdom,$cnum) = @_;
9957: if ($cdom eq '' || $cnum eq '') {
9958: return unless ($env{'request.course.id'});
9959: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9960: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9961: }
9962: my $hashid=$cdom.'_'.$cnum;
9963: my ($change,$cached)=&is_cached_new('crschange',$hashid);
9964: if ((defined($cached)) && ($change ne '')) {
9965: return $change;
9966: } else {
9967: my %crshash;
9968: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
9969: if ($crshash{'internal.contentchange'} eq '') {
9970: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
9971: if ($change eq '') {
9972: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
9973: $change = $crshash{'internal.created'};
9974: }
9975: } else {
9976: $change = $crshash{'internal.contentchange'};
9977: }
9978: my $cachetime = 600;
9979: &do_cache_new('crschange',$hashid,$change,$cachetime);
9980: }
9981: return $change;
9982: }
9983:
9984: sub devalidate_coursechange_cache {
9985: my ($cnum,$cdom)=@_;
9986: my $hashid=$cnum.':'.$cdom;
9987: &devalidate_cache_new('crschange',$hashid);
9988: }
9989:
1.31 www 9990: # ------------------------------------------------- Update symbolic store links
9991:
9992: sub symblist {
9993: my ($mapname,%newhash)=@_;
1.438 www 9994: $mapname=&deversion(&declutter($mapname));
1.31 www 9995: my %hash;
1.620 albertel 9996: if (($env{'request.course.fn'}) && (%newhash)) {
9997: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9998: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9999: foreach my $url (keys(%newhash)) {
1.711 albertel 10000: next if ($url eq 'last_known'
10001: && $env{'form.no_update_last_known'});
10002: $hash{declutter($url)}=&encode_symb($mapname,
10003: $newhash{$url}->[1],
10004: $newhash{$url}->[0]);
1.191 harris41 10005: }
1.31 www 10006: if (untie(%hash)) {
10007: return 'ok';
10008: }
10009: }
10010: }
10011: return 'error';
1.212 www 10012: }
10013:
10014: # --------------------------------------------------------------- Verify a symb
10015:
10016: sub symbverify {
1.510 www 10017: my ($symb,$thisurl)=@_;
10018: my $thisfn=$thisurl;
1.439 www 10019: $thisfn=&declutter($thisfn);
1.215 www 10020: # direct jump to resource in page or to a sequence - will construct own symbs
10021: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10022: # check URL part
1.409 www 10023: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10024:
1.431 www 10025: unless ($url eq $thisfn) { return 0; }
1.213 www 10026:
1.216 www 10027: $symb=&symbclean($symb);
1.510 www 10028: $thisurl=&deversion($thisurl);
1.439 www 10029: $thisfn=&deversion($thisfn);
1.213 www 10030:
10031: my %bighash;
10032: my $okay=0;
1.431 www 10033:
1.620 albertel 10034: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10035: &GDBM_READER(),0640)) {
1.1032 raeburn 10036: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10037: $thisurl =~ s/\?.+$//;
10038: }
1.510 www 10039: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 10040: unless ($ids) {
10041: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10042: $ids=$bighash{$idkey};
1.216 www 10043: }
10044: if ($ids) {
10045: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 10046: foreach my $id (split(/\,/,$ids)) {
10047: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 10048: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10049: $symb =~ s/\?.+$//;
10050: }
1.216 www 10051: if (
10052: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10053: eq $symb) {
1.620 albertel 10054: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10055: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10056: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 10057: $okay=1;
10058: }
10059: }
1.216 www 10060: }
10061: }
1.213 www 10062: untie(%bighash);
10063: }
10064: return $okay;
1.31 www 10065: }
10066:
1.210 www 10067: # --------------------------------------------------------------- Clean-up symb
10068:
10069: sub symbclean {
10070: my $symb=shift;
1.568 albertel 10071: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10072: # remove version from map
10073: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10074:
1.210 www 10075: # remove version from URL
10076: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10077:
1.507 www 10078: # remove wrapper
10079:
1.510 www 10080: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10081: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10082: return $symb;
1.409 www 10083: }
10084:
10085: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10086:
10087: sub encode_symb {
10088: my ($map,$resid,$url)=@_;
10089: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10090: }
1.409 www 10091:
10092: sub decode_symb {
1.568 albertel 10093: my $symb=shift;
10094: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10095: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10096: return (&fixversion($map),$resid,&fixversion($url));
10097: }
10098:
10099: sub fixversion {
10100: my $fn=shift;
1.609 banghart 10101: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10102: my %bighash;
10103: my $uri=&clutter($fn);
1.620 albertel 10104: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10105: # is this cached?
1.599 albertel 10106: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10107: if (defined($cached)) { return $result; }
10108: # unfortunately not cached, or expired
1.620 albertel 10109: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10110: &GDBM_READER(),0640)) {
10111: if ($bighash{'version_'.$uri}) {
10112: my $version=$bighash{'version_'.$uri};
1.444 www 10113: unless (($version eq 'mostrecent') ||
10114: ($version==&getversion($uri))) {
1.440 www 10115: $uri=~s/\.(\w+)$/\.$version\.$1/;
10116: }
10117: }
10118: untie %bighash;
1.413 www 10119: }
1.599 albertel 10120: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10121: }
10122:
10123: sub deversion {
10124: my $url=shift;
10125: $url=~s/\.\d+\.(\w+)$/\.$1/;
10126: return $url;
1.210 www 10127: }
10128:
1.31 www 10129: # ------------------------------------------------------ Return symb list entry
10130:
10131: sub symbread {
1.249 www 10132: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 10133: my $cache_str='request.symbread.cached.'.$thisfn;
1.1179 raeburn 10134: if (defined($env{$cache_str})) {
10135: if (($thisfn) || ($env{$cache_str} ne '')) {
10136: return $env{$cache_str};
10137: }
10138: }
1.242 www 10139: # no filename provided? try from environment
1.44 www 10140: unless ($thisfn) {
1.620 albertel 10141: if ($env{'request.symb'}) {
10142: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10143: }
1.620 albertel 10144: $thisfn=$env{'request.filename'};
1.44 www 10145: }
1.569 albertel 10146: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10147: # is that filename actually a symb? Verify, clean, and return
10148: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10149: if (&symbverify($thisfn,$1)) {
1.620 albertel 10150: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10151: }
1.242 www 10152: }
1.44 www 10153: $thisfn=declutter($thisfn);
1.31 www 10154: my %hash;
1.37 www 10155: my %bighash;
10156: my $syval='';
1.620 albertel 10157: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10158: my $targetfn = $thisfn;
1.609 banghart 10159: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10160: $targetfn = 'adm/wrapper/'.$thisfn;
10161: }
1.687 albertel 10162: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10163: $targetfn=$1;
10164: }
1.620 albertel 10165: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10166: &GDBM_READER(),0640)) {
1.481 raeburn 10167: $syval=$hash{$targetfn};
1.37 www 10168: untie(%hash);
10169: }
10170: # ---------------------------------------------------------- There was an entry
10171: if ($syval) {
1.601 albertel 10172: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10173: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10174: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10175: #return $env{$cache_str}='';
1.601 albertel 10176: #}
10177: #$syval.=$1;
10178: #}
1.37 www 10179: } else {
10180: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10181: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10182: &GDBM_READER(),0640)) {
1.37 www 10183: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10184: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10185: unless ($ids) {
10186: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10187: }
10188: unless ($ids) {
10189: # alias?
10190: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10191: }
1.37 www 10192: if ($ids) {
10193: # ------------------------------------------------------------------- Has ID(s)
10194: my @possibilities=split(/\,/,$ids);
1.39 www 10195: if ($#possibilities==0) {
10196: # ----------------------------------------------- There is only one possibility
1.37 www 10197: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10198: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10199: $resid,$thisfn);
1.249 www 10200: } elsif (!$donotrecurse) {
1.39 www 10201: # ------------------------------------------ There is more than one possibility
10202: my $realpossible=0;
1.800 albertel 10203: foreach my $id (@possibilities) {
10204: my $file=$bighash{'src_'.$id};
1.39 www 10205: if (&allowed('bre',$file)) {
1.800 albertel 10206: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10207: if ($bighash{'map_type_'.$mapid} ne 'page') {
10208: $realpossible++;
1.626 albertel 10209: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10210: $resid,$thisfn);
1.39 www 10211: }
10212: }
1.191 harris41 10213: }
1.39 www 10214: if ($realpossible!=1) { $syval=''; }
1.249 www 10215: } else {
10216: $syval='';
1.37 www 10217: }
10218: }
10219: untie(%bighash)
1.481 raeburn 10220: }
1.31 www 10221: }
1.62 www 10222: if ($syval) {
1.620 albertel 10223: return $env{$cache_str}=$syval;
1.62 www 10224: }
1.31 www 10225: }
1.949 raeburn 10226: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10227: return $env{$cache_str}='';
1.31 www 10228: }
10229:
10230: # ---------------------------------------------------------- Return random seed
10231:
1.32 www 10232: sub numval {
10233: my $txt=shift;
10234: $txt=~tr/A-J/0-9/;
10235: $txt=~tr/a-j/0-9/;
10236: $txt=~tr/K-T/0-9/;
10237: $txt=~tr/k-t/0-9/;
10238: $txt=~tr/U-Z/0-5/;
10239: $txt=~tr/u-z/0-5/;
10240: $txt=~s/\D//g;
1.564 albertel 10241: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10242: return int($txt);
1.368 albertel 10243: }
10244:
1.484 albertel 10245: sub numval2 {
10246: my $txt=shift;
10247: $txt=~tr/A-J/0-9/;
10248: $txt=~tr/a-j/0-9/;
10249: $txt=~tr/K-T/0-9/;
10250: $txt=~tr/k-t/0-9/;
10251: $txt=~tr/U-Z/0-5/;
10252: $txt=~tr/u-z/0-5/;
10253: $txt=~s/\D//g;
10254: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10255: my $total;
10256: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10257: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10258: return int($total);
10259: }
10260:
1.575 albertel 10261: sub numval3 {
10262: use integer;
10263: my $txt=shift;
10264: $txt=~tr/A-J/0-9/;
10265: $txt=~tr/a-j/0-9/;
10266: $txt=~tr/K-T/0-9/;
10267: $txt=~tr/k-t/0-9/;
10268: $txt=~tr/U-Z/0-5/;
10269: $txt=~tr/u-z/0-5/;
10270: $txt=~s/\D//g;
10271: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10272: my $total;
10273: foreach my $val (@txts) { $total+=$val; }
10274: if ($_64bit) { $total=(($total<<32)>>32); }
10275: return $total;
10276: }
10277:
1.675 albertel 10278: sub digest {
10279: my ($data)=@_;
10280: my $digest=&Digest::MD5::md5($data);
10281: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10282: my ($e,$f);
10283: {
10284: use integer;
10285: $e=($a+$b);
10286: $f=($c+$d);
10287: if ($_64bit) {
10288: $e=(($e<<32)>>32);
10289: $f=(($f<<32)>>32);
10290: }
10291: }
10292: if (wantarray) {
10293: return ($e,$f);
10294: } else {
10295: my $g;
10296: {
10297: use integer;
10298: $g=($e+$f);
10299: if ($_64bit) {
10300: $g=(($g<<32)>>32);
10301: }
10302: }
10303: return $g;
10304: }
10305: }
10306:
1.368 albertel 10307: sub latest_rnd_algorithm_id {
1.675 albertel 10308: return '64bit5';
1.366 albertel 10309: }
1.32 www 10310:
1.503 albertel 10311: sub get_rand_alg {
10312: my ($courseid)=@_;
1.790 albertel 10313: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10314: if ($courseid) {
1.620 albertel 10315: return $env{"course.$courseid.rndseed"};
1.503 albertel 10316: }
10317: return &latest_rnd_algorithm_id();
10318: }
10319:
1.562 albertel 10320: sub validCODE {
10321: my ($CODE)=@_;
10322: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10323: return 0;
10324: }
10325:
1.491 albertel 10326: sub getCODE {
1.620 albertel 10327: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10328: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10329: defined($Apache::lonhomework::parsing_a_task) ) &&
10330: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10331: return $Apache::lonhomework::history{'resource.CODE'};
10332: }
10333: return undef;
10334: }
1.1133 foxr 10335: #
10336: # Determines the random seed for a specific context:
10337: #
10338: # parameters:
10339: # symb - in course context the symb for the seed.
10340: # course_id - The course id of the form domain_coursenum.
10341: # domain - Domain for the user.
10342: # course - Course for the user.
10343: # cenv - environment of the course.
10344: #
10345: # NOTE:
10346: # All parameters are picked out of the environment if missing
10347: # or not defined.
10348: # If a symb cannot be determined the current time is used instead.
10349: #
10350: # For a given well defined symb, courside, domain, username,
10351: # and course environment, the seed is reproducible.
10352: #
1.31 www 10353: sub rndseed {
1.1133 foxr 10354: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10355: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10356: if (!defined($symb)) {
1.366 albertel 10357: unless ($symb=$wsymb) { return time; }
10358: }
1.1146 foxr 10359: if (!defined $courseid) {
10360: $courseid=$wcourseid;
10361: }
10362: if (!defined $domain) { $domain=$wdomain; }
10363: if (!defined $username) { $username=$wusername }
1.1133 foxr 10364:
10365: my $which;
10366: if (defined($cenv->{'rndseed'})) {
10367: $which = $cenv->{'rndseed'};
10368: } else {
10369: $which =&get_rand_alg($courseid);
10370: }
1.491 albertel 10371: if (defined(&getCODE())) {
1.1133 foxr 10372:
1.675 albertel 10373: if ($which eq '64bit5') {
10374: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10375: } elsif ($which eq '64bit4') {
1.575 albertel 10376: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10377: } else {
10378: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10379: }
1.675 albertel 10380: } elsif ($which eq '64bit5') {
10381: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10382: } elsif ($which eq '64bit4') {
10383: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10384: } elsif ($which eq '64bit3') {
10385: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10386: } elsif ($which eq '64bit2') {
10387: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10388: } elsif ($which eq '64bit') {
10389: return &rndseed_64bit($symb,$courseid,$domain,$username);
10390: }
10391: return &rndseed_32bit($symb,$courseid,$domain,$username);
10392: }
10393:
10394: sub rndseed_32bit {
10395: my ($symb,$courseid,$domain,$username)=@_;
10396: {
10397: use integer;
10398: my $symbchck=unpack("%32C*",$symb) << 27;
10399: my $symbseed=numval($symb) << 22;
10400: my $namechck=unpack("%32C*",$username) << 17;
10401: my $nameseed=numval($username) << 12;
10402: my $domainseed=unpack("%32C*",$domain) << 7;
10403: my $courseseed=unpack("%32C*",$courseid);
10404: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10405: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10406: #&logthis("rndseed :$num:$symb");
1.564 albertel 10407: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10408: return $num;
10409: }
10410: }
10411:
10412: sub rndseed_64bit {
10413: my ($symb,$courseid,$domain,$username)=@_;
10414: {
10415: use integer;
10416: my $symbchck=unpack("%32S*",$symb) << 21;
10417: my $symbseed=numval($symb) << 10;
10418: my $namechck=unpack("%32S*",$username);
10419:
10420: my $nameseed=numval($username) << 21;
10421: my $domainseed=unpack("%32S*",$domain) << 10;
10422: my $courseseed=unpack("%32S*",$courseid);
10423:
10424: my $num1=$symbchck+$symbseed+$namechck;
10425: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10426: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10427: #&logthis("rndseed :$num:$symb");
1.564 albertel 10428: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10429: return "$num1,$num2";
1.155 albertel 10430: }
1.366 albertel 10431: }
10432:
1.443 albertel 10433: sub rndseed_64bit2 {
10434: my ($symb,$courseid,$domain,$username)=@_;
10435: {
10436: use integer;
10437: # strings need to be an even # of cahracters long, it it is odd the
10438: # last characters gets thrown away
10439: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10440: my $symbseed=numval($symb) << 10;
10441: my $namechck=unpack("%32S*",$username.' ');
10442:
10443: my $nameseed=numval($username) << 21;
1.501 albertel 10444: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10445: my $courseseed=unpack("%32S*",$courseid.' ');
10446:
10447: my $num1=$symbchck+$symbseed+$namechck;
10448: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10449: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10450: #&logthis("rndseed :$num:$symb");
1.803 albertel 10451: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10452: return "$num1,$num2";
10453: }
10454: }
10455:
10456: sub rndseed_64bit3 {
10457: my ($symb,$courseid,$domain,$username)=@_;
10458: {
10459: use integer;
10460: # strings need to be an even # of cahracters long, it it is odd the
10461: # last characters gets thrown away
10462: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10463: my $symbseed=numval2($symb) << 10;
10464: my $namechck=unpack("%32S*",$username.' ');
10465:
10466: my $nameseed=numval2($username) << 21;
1.443 albertel 10467: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10468: my $courseseed=unpack("%32S*",$courseid.' ');
10469:
10470: my $num1=$symbchck+$symbseed+$namechck;
10471: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10472: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10473: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10474: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10475:
1.503 albertel 10476: return "$num1:$num2";
1.443 albertel 10477: }
10478: }
10479:
1.575 albertel 10480: sub rndseed_64bit4 {
10481: my ($symb,$courseid,$domain,$username)=@_;
10482: {
10483: use integer;
10484: # strings need to be an even # of cahracters long, it it is odd the
10485: # last characters gets thrown away
10486: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10487: my $symbseed=numval3($symb) << 10;
10488: my $namechck=unpack("%32S*",$username.' ');
10489:
10490: my $nameseed=numval3($username) << 21;
10491: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10492: my $courseseed=unpack("%32S*",$courseid.' ');
10493:
10494: my $num1=$symbchck+$symbseed+$namechck;
10495: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10496: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10497: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10498: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10499:
1.575 albertel 10500: return "$num1:$num2";
10501: }
10502: }
10503:
1.675 albertel 10504: sub rndseed_64bit5 {
10505: my ($symb,$courseid,$domain,$username)=@_;
10506: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10507: return "$num1:$num2";
10508: }
10509:
1.366 albertel 10510: sub rndseed_CODE_64bit {
10511: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10512: {
1.366 albertel 10513: use integer;
1.443 albertel 10514: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10515: my $symbseed=numval2($symb);
1.491 albertel 10516: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10517: my $CODEseed=numval(&getCODE());
1.443 albertel 10518: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10519: my $num1=$symbseed+$CODEchck;
10520: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10521: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10522: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10523: if ($_64bit) { $num1=(($num1<<32)>>32); }
10524: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10525: return "$num1:$num2";
1.366 albertel 10526: }
10527: }
10528:
1.575 albertel 10529: sub rndseed_CODE_64bit4 {
10530: my ($symb,$courseid,$domain,$username)=@_;
10531: {
10532: use integer;
10533: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10534: my $symbseed=numval3($symb);
10535: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10536: my $CODEseed=numval3(&getCODE());
10537: my $courseseed=unpack("%32S*",$courseid.' ');
10538: my $num1=$symbseed+$CODEchck;
10539: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10540: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10541: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10542: if ($_64bit) { $num1=(($num1<<32)>>32); }
10543: if ($_64bit) { $num2=(($num2<<32)>>32); }
10544: return "$num1:$num2";
10545: }
10546: }
10547:
1.675 albertel 10548: sub rndseed_CODE_64bit5 {
10549: my ($symb,$courseid,$domain,$username)=@_;
10550: my $code = &getCODE();
10551: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10552: return "$num1:$num2";
10553: }
10554:
1.366 albertel 10555: sub setup_random_from_rndseed {
10556: my ($rndseed)=@_;
1.503 albertel 10557: if ($rndseed =~/([,:])/) {
10558: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10559: &Math::Random::random_set_seed(abs($num1),abs($num2));
10560: } else {
10561: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10562: }
1.36 albertel 10563: }
10564:
1.474 albertel 10565: sub latest_receipt_algorithm_id {
1.835 albertel 10566: return 'receipt3';
1.474 albertel 10567: }
10568:
1.480 www 10569: sub recunique {
10570: my $fucourseid=shift;
10571: my $unique;
1.835 albertel 10572: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10573: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10574: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10575: } else {
10576: $unique=$perlvar{'lonReceipt'};
10577: }
10578: return unpack("%32C*",$unique);
10579: }
10580:
10581: sub recprefix {
10582: my $fucourseid=shift;
10583: my $prefix;
1.835 albertel 10584: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10585: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10586: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10587: } else {
10588: $prefix=$perlvar{'lonHostID'};
10589: }
10590: return unpack("%32C*",$prefix);
10591: }
10592:
1.76 www 10593: sub ireceipt {
1.474 albertel 10594: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10595:
10596: my $return =&recprefix($fucourseid).'-';
10597:
10598: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10599: $env{'request.state'} eq 'construct') {
10600: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10601: return $return;
10602: }
10603:
1.76 www 10604: my $cuname=unpack("%32C*",$funame);
10605: my $cudom=unpack("%32C*",$fudom);
10606: my $cucourseid=unpack("%32C*",$fucourseid);
10607: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10608: my $cunique=&recunique($fucourseid);
1.474 albertel 10609: my $cpart=unpack("%32S*",$part);
1.835 albertel 10610: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10611:
1.790 albertel 10612: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10613:
10614: $return.= ($cunique%$cuname+
10615: $cunique%$cudom+
10616: $cusymb%$cuname+
10617: $cusymb%$cudom+
10618: $cucourseid%$cuname+
10619: $cucourseid%$cudom+
10620: $cpart%$cuname+
10621: $cpart%$cudom);
10622: } else {
10623: $return.= ($cunique%$cuname+
10624: $cunique%$cudom+
10625: $cusymb%$cuname+
10626: $cusymb%$cudom+
10627: $cucourseid%$cuname+
10628: $cucourseid%$cudom);
10629: }
10630: return $return;
1.76 www 10631: }
10632:
10633: sub receipt {
1.474 albertel 10634: my ($part)=@_;
1.790 albertel 10635: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10636: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10637: }
1.260 ng 10638:
1.790 albertel 10639: sub whichuser {
10640: my ($passedsymb)=@_;
10641: my ($symb,$courseid,$domain,$name,$publicuser);
10642: if (defined($env{'form.grade_symb'})) {
10643: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10644: my $allowed=&allowed('vgr',$tmp_courseid);
10645: if (!$allowed &&
10646: exists($env{'request.course.sec'}) &&
10647: $env{'request.course.sec'} !~ /^\s*$/) {
10648: $allowed=&allowed('vgr',$tmp_courseid.
10649: '/'.$env{'request.course.sec'});
10650: }
10651: if ($allowed) {
10652: ($symb)=&get_env_multiple('form.grade_symb');
10653: $courseid=$tmp_courseid;
10654: ($domain)=&get_env_multiple('form.grade_domain');
10655: ($name)=&get_env_multiple('form.grade_username');
10656: return ($symb,$courseid,$domain,$name,$publicuser);
10657: }
10658: }
10659: if (!$passedsymb) {
10660: $symb=&symbread();
10661: } else {
10662: $symb=$passedsymb;
10663: }
10664: $courseid=$env{'request.course.id'};
10665: $domain=$env{'user.domain'};
10666: $name=$env{'user.name'};
10667: if ($name eq 'public' && $domain eq 'public') {
10668: if (!defined($env{'form.username'})) {
10669: $env{'form.username'}.=time.rand(10000000);
10670: }
10671: $name.=$env{'form.username'};
10672: }
10673: return ($symb,$courseid,$domain,$name,$publicuser);
10674:
10675: }
10676:
1.36 albertel 10677: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10678: # returns either the contents of the file or
10679: # -1 if the file doesn't exist
1.481 raeburn 10680: #
10681: # if the target is a file that was uploaded via DOCS,
10682: # a check will be made to see if a current copy exists on the local server,
10683: # if it does this will be served, otherwise a copy will be retrieved from
10684: # the home server for the course and stored in /home/httpd/html/userfiles on
10685: # the local server.
1.472 albertel 10686:
1.36 albertel 10687: sub getfile {
1.538 albertel 10688: my ($file) = @_;
1.609 banghart 10689: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10690: &repcopy($file);
10691: return &readfile($file);
10692: }
10693:
10694: sub repcopy_userfile {
10695: my ($file)=@_;
1.1142 raeburn 10696: my $londocroot = $perlvar{'lonDocRoot'};
10697: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 10698: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10699: my ($cdom,$cnum,$filename) =
1.811 albertel 10700: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10701: my $uri="/uploaded/$cdom/$cnum/$filename";
10702: if (-e "$file") {
1.828 www 10703: # we already have a local copy, check it out
1.538 albertel 10704: my @fileinfo = stat($file);
1.828 www 10705: my $rtncode;
10706: my $info;
1.538 albertel 10707: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10708: if ($lwpresp ne 'ok') {
1.828 www 10709: # there is no such file anymore, even though we had a local copy
1.482 albertel 10710: if ($rtncode eq '404') {
1.538 albertel 10711: unlink($file);
1.482 albertel 10712: }
10713: return -1;
10714: }
10715: if ($info < $fileinfo[9]) {
1.828 www 10716: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10717: return 'ok';
1.828 www 10718: } else {
10719: # the file is outdated, get rid of it
10720: unlink($file);
1.482 albertel 10721: }
1.828 www 10722: }
10723: # one way or the other, at this point, we don't have the file
10724: # construct the correct path for the file
10725: my @parts = ($cdom,$cnum);
10726: if ($filename =~ m|^(.+)/[^/]+$|) {
10727: push @parts, split(/\//,$1);
10728: }
10729: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10730: foreach my $part (@parts) {
10731: $path .= '/'.$part;
10732: if (!-e $path) {
10733: mkdir($path,0770);
1.482 albertel 10734: }
10735: }
1.828 www 10736: # now the path exists for sure
10737: # get a user agent
10738: my $ua=new LWP::UserAgent;
10739: my $transferfile=$file.'.in.transfer';
10740: # FIXME: this should flock
10741: if (-e $transferfile) { return 'ok'; }
10742: my $request;
10743: $uri=~s/^\///;
1.980 raeburn 10744: my $homeserver = &homeserver($cnum,$cdom);
10745: my $protocol = $protocol{$homeserver};
10746: $protocol = 'http' if ($protocol ne 'https');
10747: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10748: my $response=$ua->request($request,$transferfile);
10749: # did it work?
10750: if ($response->is_error()) {
10751: unlink($transferfile);
10752: &logthis("Userfile repcopy failed for $uri");
10753: return -1;
10754: }
10755: # worked, rename the transfer file
10756: rename($transferfile,$file);
1.607 raeburn 10757: return 'ok';
1.481 raeburn 10758: }
10759:
1.517 albertel 10760: sub tokenwrapper {
10761: my $uri=shift;
1.980 raeburn 10762: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10763: $uri=~s|^/||;
1.620 albertel 10764: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10765: my $token=$1;
1.552 albertel 10766: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10767: if ($udom && $uname && $file) {
10768: $file=~s|(\?\.*)*$||;
1.949 raeburn 10769: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10770: my $homeserver = &homeserver($uname,$udom);
10771: my $protocol = $protocol{$homeserver};
10772: $protocol = 'http' if ($protocol ne 'https');
10773: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10774: (($uri=~/\?/)?'&':'?').'token='.$token.
10775: '&tokenissued='.$perlvar{'lonHostID'};
10776: } else {
10777: return '/adm/notfound.html';
10778: }
10779: }
10780:
1.828 www 10781: # call with reqtype HEAD: get last modification time
10782: # call with reqtype GET: get the file contents
10783: # Do not call this with reqtype GET for large files! It loads everything into memory
10784: #
1.481 raeburn 10785: sub getuploaded {
10786: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10787: $uri=~s/^\///;
1.980 raeburn 10788: my $homeserver = &homeserver($cnum,$cdom);
10789: my $protocol = $protocol{$homeserver};
10790: $protocol = 'http' if ($protocol ne 'https');
10791: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10792: my $ua=new LWP::UserAgent;
10793: my $request=new HTTP::Request($reqtype,$uri);
10794: my $response=$ua->request($request);
10795: $$rtncode = $response->code;
1.482 albertel 10796: if (! $response->is_success()) {
10797: return 'failed';
10798: }
10799: if ($reqtype eq 'HEAD') {
1.486 www 10800: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10801: } elsif ($reqtype eq 'GET') {
10802: $$info = $response->content;
1.472 albertel 10803: }
1.482 albertel 10804: return 'ok';
1.36 albertel 10805: }
10806:
1.481 raeburn 10807: sub readfile {
10808: my $file = shift;
10809: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10810: my $fh;
10811: open($fh,"<$file");
10812: my $a='';
1.800 albertel 10813: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10814: return $a;
10815: }
10816:
1.36 albertel 10817: sub filelocation {
1.590 banghart 10818: my ($dir,$file) = @_;
10819: my $location;
10820: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10821:
10822: if ($file =~ m-^/adm/-) {
10823: $file=~s-^/adm/wrapper/-/-;
10824: $file=~s-^/adm/coursedocs/showdoc/-/-;
10825: }
1.882 albertel 10826:
1.1139 www 10827: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10828: $location = $file;
1.609 banghart 10829: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10830: my ($udom,$uname,$filename)=
1.811 albertel 10831: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10832: my $home=&homeserver($uname,$udom);
10833: my $is_me=0;
10834: my @ids=¤t_machine_ids();
10835: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10836: if ($is_me) {
1.1117 foxr 10837: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10838: } else {
10839: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10840: $udom.'/'.$uname.'/'.$filename;
10841: }
1.882 albertel 10842: } elsif ($file =~ m-^/adm/-) {
10843: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10844: } else {
10845: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10846: $file=~s:^/(res|priv)/:/:;
10847: my $space=$1;
1.590 banghart 10848: if ( !( $file =~ m:^/:) ) {
10849: $location = $dir. '/'.$file;
10850: } else {
1.1142 raeburn 10851: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10852: }
1.59 albertel 10853: }
1.590 banghart 10854: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10855: while ($location=~m{/\.\./}) {
10856: if ($location =~ m{/[^/]+/\.\./}) {
10857: $location=~ s{/[^/]+/\.\./}{/}g;
10858: } else {
10859: $location=~ s{/\.\./}{/}g;
10860: }
10861: } #remove dir/..
1.590 banghart 10862: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10863: return $location;
1.46 www 10864: }
1.36 albertel 10865:
1.46 www 10866: sub hreflocation {
10867: my ($dir,$file)=@_;
1.980 raeburn 10868: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10869: $file=filelocation($dir,$file);
1.700 albertel 10870: } elsif ($file=~m-^/adm/-) {
10871: $file=~s-^/adm/wrapper/-/-;
10872: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10873: }
10874: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10875: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10876: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10877: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10878: {/uploaded/$1/$2/}x;
1.46 www 10879: }
1.913 albertel 10880: if ($file=~ m{^/userfiles/}) {
10881: $file =~ s{^/userfiles/}{/uploaded/};
10882: }
1.462 albertel 10883: return $file;
1.465 albertel 10884: }
10885:
1.1139 www 10886:
10887:
10888:
10889:
1.465 albertel 10890: sub current_machine_domains {
1.853 albertel 10891: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10892: }
10893:
10894: sub machine_domains {
10895: my ($hostname) = @_;
1.465 albertel 10896: my @domains;
1.838 albertel 10897: my %hostname = &all_hostnames();
1.465 albertel 10898: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10899: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10900: if ($hostname eq $name) {
1.844 albertel 10901: push(@domains,&host_domain($id));
1.465 albertel 10902: }
10903: }
10904: return @domains;
10905: }
10906:
10907: sub current_machine_ids {
1.853 albertel 10908: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10909: }
10910:
10911: sub machine_ids {
10912: my ($hostname) = @_;
10913: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10914: my @ids;
1.888 albertel 10915: my %name_to_host = &all_names();
1.889 albertel 10916: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10917: return @{ $name_to_host{$hostname} };
10918: }
10919: return;
1.31 www 10920: }
10921:
1.824 raeburn 10922: sub additional_machine_domains {
10923: my @domains;
10924: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10925: while( my $line = <$fh>) {
10926: $line =~ s/\s//g;
10927: push(@domains,$line);
10928: }
10929: return @domains;
10930: }
10931:
10932: sub default_login_domain {
10933: my $domain = $perlvar{'lonDefDomain'};
10934: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10935: foreach my $posdom (¤t_machine_domains(),
10936: &additional_machine_domains()) {
10937: if (lc($posdom) eq lc($testdomain)) {
10938: $domain=$posdom;
10939: last;
10940: }
10941: }
10942: return $domain;
10943: }
10944:
1.31 www 10945: # ------------------------------------------------------------- Declutters URLs
10946:
10947: sub declutter {
10948: my $thisfn=shift;
1.569 albertel 10949: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10950: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10951: $thisfn=~s/^\///;
1.697 albertel 10952: $thisfn=~s|^adm/wrapper/||;
10953: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10954: $thisfn=~s/^res\///;
1.1172 bisitz 10955: $thisfn=~s/^priv\///;
1.1032 raeburn 10956: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10957: $thisfn=~s/\?.+$//;
10958: }
1.268 www 10959: return $thisfn;
10960: }
10961:
10962: # ------------------------------------------------------------- Clutter up URLs
10963:
10964: sub clutter {
10965: my $thisfn='/'.&declutter(shift);
1.887 albertel 10966: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10967: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10968: $thisfn='/res'.$thisfn;
10969: }
1.1031 raeburn 10970: if ($thisfn !~m|^/adm|) {
10971: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10972: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10973: } else {
10974: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10975: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10976: if ($embstyle eq 'ssi'
10977: || ($embstyle eq 'hdn')
10978: || ($embstyle eq 'rat')
10979: || ($embstyle eq 'prv')
10980: || ($embstyle eq 'ign')) {
10981: #do nothing with these
10982: } elsif (($embstyle eq 'img')
1.695 albertel 10983: || ($embstyle eq 'emb')
10984: || ($embstyle eq 'wrp')) {
10985: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10986: } elsif ($embstyle eq 'unk'
10987: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10988: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10989: } else {
1.718 www 10990: # &logthis("Got a blank emb style");
1.695 albertel 10991: }
1.694 albertel 10992: }
10993: }
1.31 www 10994: return $thisfn;
1.12 www 10995: }
10996:
1.787 albertel 10997: sub clutter_with_no_wrapper {
10998: my $uri = &clutter(shift);
10999: if ($uri =~ m-^/adm/-) {
11000: $uri =~ s-^/adm/wrapper/-/-;
11001: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11002: }
11003: return $uri;
11004: }
11005:
1.557 albertel 11006: sub freeze_escape {
11007: my ($value)=@_;
11008: if (ref($value)) {
11009: $value=&nfreeze($value);
11010: return '__FROZEN__'.&escape($value);
11011: }
11012: return &escape($value);
11013: }
11014:
1.11 www 11015:
1.557 albertel 11016: sub thaw_unescape {
11017: my ($value)=@_;
11018: if ($value =~ /^__FROZEN__/) {
11019: substr($value,0,10,undef);
11020: $value=&unescape($value);
11021: return &thaw($value);
11022: }
11023: return &unescape($value);
11024: }
11025:
1.436 albertel 11026: sub correct_line_ends {
11027: my ($result)=@_;
11028: $$result =~s/\r\n/\n/mg;
11029: $$result =~s/\r/\n/mg;
1.415 albertel 11030: }
1.1 albertel 11031: # ================================================================ Main Program
11032:
1.184 www 11033: sub goodbye {
1.204 albertel 11034: &logthis("Starting Shut down");
1.443 albertel 11035: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11036: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11037: #converted
1.599 albertel 11038: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11039: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11040: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11041: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11042: #1.1 only
1.870 albertel 11043: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11044: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11045: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11046: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11047: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11048: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11049: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11050: &flushcourselogs();
11051: &logthis("Shutting down");
11052: }
11053:
1.852 albertel 11054: sub get_dns {
1.869 albertel 11055: my ($url,$func,$ignore_cache) = @_;
11056: if (!$ignore_cache) {
11057: my ($content,$cached)=
11058: &Apache::lonnet::is_cached_new('dns',$url);
11059: if ($cached) {
11060: &$func($content);
11061: return;
11062: }
11063: }
11064:
11065: my %alldns;
1.852 albertel 11066: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11067: foreach my $dns (<$config>) {
11068: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11069: my $line = $1;
11070: my ($host,$protocol) = split(/:/,$line);
11071: if ($protocol ne 'https') {
11072: $protocol = 'http';
11073: }
11074: $alldns{$host} = $protocol;
1.869 albertel 11075: }
11076: while (%alldns) {
11077: my ($dns) = keys(%alldns);
1.852 albertel 11078: my $ua=new LWP::UserAgent;
1.1134 raeburn 11079: $ua->timeout(30);
1.979 raeburn 11080: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11081: my $response=$ua->request($request);
1.979 raeburn 11082: delete($alldns{$dns});
1.852 albertel 11083: next if ($response->is_error());
11084: my @content = split("\n",$response->content);
1.869 albertel 11085: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 11086: &$func(\@content);
1.869 albertel 11087: return;
1.852 albertel 11088: }
11089: close($config);
1.871 albertel 11090: my $which = (split('/',$url))[3];
11091: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11092: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11093: my @content = <$config>;
11094: &$func(\@content);
11095: return;
1.852 albertel 11096: }
1.327 albertel 11097: # ------------------------------------------------------------ Read domain file
11098: {
1.852 albertel 11099: my $loaded;
1.846 albertel 11100: my %domain;
11101:
1.852 albertel 11102: sub parse_domain_tab {
11103: my ($lines) = @_;
11104: foreach my $line (@$lines) {
11105: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11106:
1.846 albertel 11107: chomp($line);
1.852 albertel 11108: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11109: my %this_domain;
11110: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11111: 'lang_def', 'city', 'longi', 'lati',
11112: 'primary') {
11113: $this_domain{$field} = shift(@elements);
11114: }
11115: $domain{$name} = \%this_domain;
1.852 albertel 11116: }
11117: }
1.864 albertel 11118:
11119: sub reset_domain_info {
11120: undef($loaded);
11121: undef(%domain);
11122: }
11123:
1.852 albertel 11124: sub load_domain_tab {
1.869 albertel 11125: my ($ignore_cache) = @_;
11126: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11127: my $fh;
11128: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11129: my @lines = <$fh>;
11130: &parse_domain_tab(\@lines);
1.448 albertel 11131: }
1.852 albertel 11132: close($fh);
11133: $loaded = 1;
1.327 albertel 11134: }
1.846 albertel 11135:
11136: sub domain {
1.852 albertel 11137: &load_domain_tab() if (!$loaded);
11138:
1.846 albertel 11139: my ($name,$what) = @_;
11140: return if ( !exists($domain{$name}) );
11141:
11142: if (!$what) {
11143: return $domain{$name}{'description'};
11144: }
11145: return $domain{$name}{$what};
11146: }
1.974 raeburn 11147:
11148: sub domain_info {
11149: &load_domain_tab() if (!$loaded);
11150: return %domain;
11151: }
11152:
1.327 albertel 11153: }
11154:
11155:
1.1 albertel 11156: # ------------------------------------------------------------- Read hosts file
11157: {
1.838 albertel 11158: my %hostname;
1.844 albertel 11159: my %hostdom;
1.845 albertel 11160: my %libserv;
1.852 albertel 11161: my $loaded;
1.888 albertel 11162: my %name_to_host;
1.1074 raeburn 11163: my %internetdom;
1.1107 raeburn 11164: my %LC_dns_serv;
1.852 albertel 11165:
11166: sub parse_hosts_tab {
11167: my ($file) = @_;
11168: foreach my $configline (@$file) {
11169: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11170: chomp($configline);
11171: if ($configline =~ /^\^/) {
11172: if ($configline =~ /^\^([\w.\-]+)/) {
11173: $LC_dns_serv{$1} = 1;
11174: }
11175: next;
11176: }
1.1074 raeburn 11177: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11178: $name=~s/\s//g;
11179: if ($id && $domain && $role && $name) {
11180: $hostname{$id}=$name;
1.888 albertel 11181: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11182: $hostdom{$id}=$domain;
11183: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11184: if (defined($protocol)) {
11185: if ($protocol eq 'https') {
11186: $protocol{$id} = $protocol;
11187: } else {
11188: $protocol{$id} = 'http';
11189: }
1.968 raeburn 11190: } else {
1.969 raeburn 11191: $protocol{$id} = 'http';
1.968 raeburn 11192: }
1.1074 raeburn 11193: if (defined($intdom)) {
11194: $internetdom{$id} = $intdom;
11195: }
1.852 albertel 11196: }
11197: }
11198: }
1.864 albertel 11199:
11200: sub reset_hosts_info {
1.897 albertel 11201: &purge_remembered();
1.864 albertel 11202: &reset_domain_info();
11203: &reset_hosts_ip_info();
1.892 albertel 11204: undef(%name_to_host);
1.864 albertel 11205: undef(%hostname);
11206: undef(%hostdom);
11207: undef(%libserv);
11208: undef($loaded);
11209: }
1.1 albertel 11210:
1.852 albertel 11211: sub load_hosts_tab {
1.869 albertel 11212: my ($ignore_cache) = @_;
11213: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11214: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11215: my @config = <$config>;
11216: &parse_hosts_tab(\@config);
11217: close($config);
11218: $loaded=1;
1.1 albertel 11219: }
1.852 albertel 11220:
1.838 albertel 11221: sub hostname {
1.852 albertel 11222: &load_hosts_tab() if (!$loaded);
11223:
1.838 albertel 11224: my ($lonid) = @_;
11225: return $hostname{$lonid};
11226: }
1.845 albertel 11227:
1.838 albertel 11228: sub all_hostnames {
1.852 albertel 11229: &load_hosts_tab() if (!$loaded);
11230:
1.838 albertel 11231: return %hostname;
11232: }
1.845 albertel 11233:
1.888 albertel 11234: sub all_names {
11235: &load_hosts_tab() if (!$loaded);
11236:
11237: return %name_to_host;
11238: }
11239:
1.974 raeburn 11240: sub all_host_domain {
11241: &load_hosts_tab() if (!$loaded);
11242: return %hostdom;
11243: }
11244:
1.845 albertel 11245: sub is_library {
1.852 albertel 11246: &load_hosts_tab() if (!$loaded);
11247:
1.845 albertel 11248: return exists($libserv{$_[0]});
11249: }
11250:
11251: sub all_library {
1.852 albertel 11252: &load_hosts_tab() if (!$loaded);
11253:
1.845 albertel 11254: return %libserv;
11255: }
11256:
1.1062 droeschl 11257: sub unique_library {
11258: #2x reverse removes all hostnames that appear more than once
11259: my %unique = reverse &all_library();
11260: return reverse %unique;
11261: }
11262:
1.841 albertel 11263: sub get_servers {
1.852 albertel 11264: &load_hosts_tab() if (!$loaded);
11265:
1.841 albertel 11266: my ($domain,$type) = @_;
11267: my %possible_hosts = ($type eq 'library') ? %libserv
11268: : %hostname;
11269: my %result;
1.842 albertel 11270: if (ref($domain) eq 'ARRAY') {
11271: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11272: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11273: $result{$host} = $hostname;
11274: }
11275: }
11276: } else {
11277: while ( my ($host,$hostname) = each(%possible_hosts)) {
11278: if ($hostdom{$host} eq $domain) {
11279: $result{$host} = $hostname;
11280: }
1.841 albertel 11281: }
11282: }
11283: return %result;
11284: }
1.845 albertel 11285:
1.1062 droeschl 11286: sub get_unique_servers {
11287: my %unique = reverse &get_servers(@_);
11288: return reverse %unique;
11289: }
11290:
1.844 albertel 11291: sub host_domain {
1.852 albertel 11292: &load_hosts_tab() if (!$loaded);
11293:
1.844 albertel 11294: my ($lonid) = @_;
11295: return $hostdom{$lonid};
11296: }
11297:
1.841 albertel 11298: sub all_domains {
1.852 albertel 11299: &load_hosts_tab() if (!$loaded);
11300:
1.841 albertel 11301: my %seen;
11302: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11303: return @uniq;
11304: }
1.1074 raeburn 11305:
11306: sub internet_dom {
11307: &load_hosts_tab() if (!$loaded);
11308:
11309: my ($lonid) = @_;
11310: return $internetdom{$lonid};
11311: }
1.1107 raeburn 11312:
11313: sub is_LC_dns {
11314: &load_hosts_tab() if (!$loaded);
11315:
11316: my ($hostname) = @_;
11317: return exists($LC_dns_serv{$hostname});
11318: }
11319:
1.1 albertel 11320: }
11321:
1.847 albertel 11322: {
11323: my %iphost;
1.856 albertel 11324: my %name_to_ip;
11325: my %lonid_to_ip;
1.869 albertel 11326:
1.847 albertel 11327: sub get_hosts_from_ip {
11328: my ($ip) = @_;
11329: my %iphosts = &get_iphost();
11330: if (ref($iphosts{$ip})) {
11331: return @{$iphosts{$ip}};
11332: }
11333: return;
1.839 albertel 11334: }
1.864 albertel 11335:
11336: sub reset_hosts_ip_info {
11337: undef(%iphost);
11338: undef(%name_to_ip);
11339: undef(%lonid_to_ip);
11340: }
1.856 albertel 11341:
11342: sub get_host_ip {
11343: my ($lonid) = @_;
11344: if (exists($lonid_to_ip{$lonid})) {
11345: return $lonid_to_ip{$lonid};
11346: }
11347: my $name=&hostname($lonid);
11348: my $ip = gethostbyname($name);
11349: return if (!$ip || length($ip) ne 4);
11350: $ip=inet_ntoa($ip);
11351: $name_to_ip{$name} = $ip;
11352: $lonid_to_ip{$lonid} = $ip;
11353: return $ip;
11354: }
1.847 albertel 11355:
11356: sub get_iphost {
1.869 albertel 11357: my ($ignore_cache) = @_;
1.894 albertel 11358:
1.869 albertel 11359: if (!$ignore_cache) {
11360: if (%iphost) {
11361: return %iphost;
11362: }
11363: my ($ip_info,$cached)=
11364: &Apache::lonnet::is_cached_new('iphost','iphost');
11365: if ($cached) {
11366: %iphost = %{$ip_info->[0]};
11367: %name_to_ip = %{$ip_info->[1]};
11368: %lonid_to_ip = %{$ip_info->[2]};
11369: return %iphost;
11370: }
11371: }
1.894 albertel 11372:
11373: # get yesterday's info for fallback
11374: my %old_name_to_ip;
11375: my ($ip_info,$cached)=
11376: &Apache::lonnet::is_cached_new('iphost','iphost');
11377: if ($cached) {
11378: %old_name_to_ip = %{$ip_info->[1]};
11379: }
11380:
1.888 albertel 11381: my %name_to_host = &all_names();
11382: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11383: my $ip;
11384: if (!exists($name_to_ip{$name})) {
11385: $ip = gethostbyname($name);
11386: if (!$ip || length($ip) ne 4) {
1.894 albertel 11387: if (defined($old_name_to_ip{$name})) {
11388: $ip = $old_name_to_ip{$name};
11389: &logthis("Can't find $name defaulting to old $ip");
11390: } else {
11391: &logthis("Name $name no IP found");
11392: next;
11393: }
11394: } else {
11395: $ip=inet_ntoa($ip);
1.847 albertel 11396: }
11397: $name_to_ip{$name} = $ip;
11398: } else {
11399: $ip = $name_to_ip{$name};
1.653 albertel 11400: }
1.888 albertel 11401: foreach my $id (@{ $name_to_host{$name} }) {
11402: $lonid_to_ip{$id} = $ip;
11403: }
11404: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11405: }
1.869 albertel 11406: &Apache::lonnet::do_cache_new('iphost','iphost',
11407: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11408: 48*60*60);
1.869 albertel 11409:
1.847 albertel 11410: return %iphost;
1.598 albertel 11411: }
11412:
1.992 raeburn 11413: #
11414: # Given a DNS returns the loncapa host name for that DNS
11415: #
11416: sub host_from_dns {
11417: my ($dns) = @_;
11418: my @hosts;
11419: my $ip;
11420:
1.993 raeburn 11421: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11422: $ip = $name_to_ip{$dns};
11423: }
11424: if (!$ip) {
11425: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11426: if (length($ip) == 4) {
11427: $ip = &IO::Socket::inet_ntoa($ip);
11428: }
11429: }
11430: if ($ip) {
11431: @hosts = get_hosts_from_ip($ip);
11432: return $hosts[0];
11433: }
11434: return undef;
1.986 foxr 11435: }
1.992 raeburn 11436:
1.1074 raeburn 11437: sub get_internet_names {
11438: my ($lonid) = @_;
11439: return if ($lonid eq '');
11440: my ($idnref,$cached)=
11441: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11442: if ($cached) {
11443: return $idnref;
11444: }
11445: my $ip = &get_host_ip($lonid);
11446: my @hosts = &get_hosts_from_ip($ip);
11447: my %iphost = &get_iphost();
11448: my (@idns,%seen);
11449: foreach my $id (@hosts) {
11450: my $dom = &host_domain($id);
11451: my $prim_id = &domain($dom,'primary');
11452: my $prim_ip = &get_host_ip($prim_id);
11453: next if ($seen{$prim_ip});
11454: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11455: foreach my $id (@{$iphost{$prim_ip}}) {
11456: my $intdom = &internet_dom($id);
11457: unless (grep(/^\Q$intdom\E$/,@idns)) {
11458: push(@idns,$intdom);
11459: }
11460: }
11461: }
11462: $seen{$prim_ip} = 1;
11463: }
11464: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11465: }
11466:
1.986 foxr 11467: }
11468:
1.1079 raeburn 11469: sub all_loncaparevs {
11470: 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);
11471: }
11472:
1.862 albertel 11473: BEGIN {
11474:
11475: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11476: unless ($readit) {
11477: {
11478: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11479: %perlvar = (%perlvar,%{$configvars});
11480: }
11481:
11482:
1.1 albertel 11483: # ------------------------------------------------------ Read spare server file
11484: {
1.448 albertel 11485: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11486:
11487: while (my $configline=<$config>) {
11488: chomp($configline);
1.284 matthew 11489: if ($configline) {
1.784 albertel 11490: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11491: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11492: push(@{ $spareid{$type} }, $host);
1.1 albertel 11493: }
11494: }
1.448 albertel 11495: close($config);
1.1 albertel 11496: }
1.11 www 11497: # ------------------------------------------------------------ Read permissions
11498: {
1.448 albertel 11499: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11500:
11501: while (my $configline=<$config>) {
1.448 albertel 11502: chomp($configline);
11503: if ($configline) {
11504: my ($role,$perm)=split(/ /,$configline);
11505: if ($perm ne '') { $pr{$role}=$perm; }
11506: }
1.11 www 11507: }
1.448 albertel 11508: close($config);
1.11 www 11509: }
11510:
11511: # -------------------------------------------- Read plain texts for permissions
11512: {
1.448 albertel 11513: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11514:
11515: while (my $configline=<$config>) {
1.448 albertel 11516: chomp($configline);
11517: if ($configline) {
1.742 raeburn 11518: my ($short,@plain)=split(/:/,$configline);
11519: %{$prp{$short}} = ();
11520: if (@plain > 0) {
11521: $prp{$short}{'std'} = $plain[0];
11522: for (my $i=1; $i<@plain; $i++) {
11523: $prp{$short}{'alt'.$i} = $plain[$i];
11524: }
11525: }
1.448 albertel 11526: }
1.135 www 11527: }
1.448 albertel 11528: close($config);
1.135 www 11529: }
11530:
11531: # ---------------------------------------------------------- Read package table
11532: {
1.448 albertel 11533: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11534:
11535: while (my $configline=<$config>) {
1.483 albertel 11536: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11537: chomp($configline);
11538: my ($short,$plain)=split(/:/,$configline);
11539: my ($pack,$name)=split(/\&/,$short);
11540: if ($plain ne '') {
11541: $packagetab{$pack.'&'.$name.'&name'}=$name;
11542: $packagetab{$short}=$plain;
11543: }
1.11 www 11544: }
1.448 albertel 11545: close($config);
1.329 matthew 11546: }
11547:
1.1073 raeburn 11548: # ---------------------------------------------------------- Read loncaparev table
11549: {
11550: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11551: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11552: while (my $configline=<$config>) {
11553: chomp($configline);
11554: my ($hostid,$loncaparev)=split(/:/,$configline);
11555: $loncaparevs{$hostid}=$loncaparev;
11556: }
11557: close($config);
11558: }
11559: }
11560: }
11561:
1.1074 raeburn 11562: # ---------------------------------------------------------- Read serverhostID table
11563: {
11564: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11565: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11566: while (my $configline=<$config>) {
11567: chomp($configline);
11568: my ($name,$id)=split(/:/,$configline);
11569: $serverhomeIDs{$name}=$id;
11570: }
11571: close($config);
11572: }
11573: }
11574: }
11575:
1.1079 raeburn 11576: {
11577: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11578: if (-e $file) {
11579: my $parser = HTML::LCParser->new($file);
11580: while (my $token = $parser->get_token()) {
11581: if ($token->[0] eq 'S') {
11582: my $item = $token->[1];
11583: my $name = $token->[2]{'name'};
11584: my $value = $token->[2]{'value'};
11585: if ($item ne '' && $name ne '' && $value ne '') {
11586: my $release = $parser->get_text();
11587: $release =~ s/(^\s*|\s*$ )//gx;
11588: $needsrelease{$item.':'.$name.':'.$value} = $release;
11589: }
11590: }
11591: }
11592: }
1.1073 raeburn 11593: }
11594:
1.1138 raeburn 11595: # ---------------------------------------------------------- Read managers table
11596: {
11597: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11598: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11599: while (my $configline=<$config>) {
11600: chomp($configline);
11601: next if ($configline =~ /^\#/);
11602: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11603: $managerstab{$configline} = 1;
11604: }
11605: }
11606: close($config);
11607: }
11608: }
11609: }
11610:
1.329 matthew 11611: # ------------- set up temporary directory
11612: {
1.1117 foxr 11613: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11614:
1.11 www 11615: }
11616:
1.794 albertel 11617: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11618: 'compress_threshold'=> 20_000,
11619: });
1.185 www 11620:
1.281 www 11621: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11622: $dumpcount=0;
1.958 www 11623: $locknum=0;
1.22 www 11624:
1.163 harris41 11625: &logtouch();
1.672 albertel 11626: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11627: $readit=1;
1.564 albertel 11628: {
11629: use integer;
11630: my $test=(2**32)+1;
1.568 albertel 11631: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11632: &logthis(" Detected 64bit platform ($_64bit)");
11633: }
1.195 www 11634: }
1.1 albertel 11635: }
1.179 www 11636:
1.1 albertel 11637: 1;
1.191 harris41 11638: __END__
11639:
1.243 albertel 11640: =pod
11641:
1.191 harris41 11642: =head1 NAME
11643:
1.243 albertel 11644: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11645:
11646: =head1 SYNOPSIS
11647:
1.243 albertel 11648: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11649:
11650: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11651:
1.243 albertel 11652: Common parameters:
11653:
11654: =over 4
11655:
11656: =item *
11657:
11658: $uname : an internal username (if $cname expecting a course Id specifically)
11659:
11660: =item *
11661:
11662: $udom : a domain (if $cdom expecting a course's domain specifically)
11663:
11664: =item *
11665:
11666: $symb : a resource instance identifier
11667:
11668: =item *
11669:
11670: $namespace : the name of a .db file that contains the data needed or
11671: being set.
11672:
11673: =back
11674:
1.394 bowersj2 11675: =head1 OVERVIEW
1.191 harris41 11676:
1.394 bowersj2 11677: lonnet provides subroutines which interact with the
11678: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11679: about classes, users, and resources.
1.243 albertel 11680:
11681: For many of these objects you can also use this to store data about
11682: them or modify them in various ways.
1.191 harris41 11683:
1.394 bowersj2 11684: =head2 Symbs
1.191 harris41 11685:
1.394 bowersj2 11686: To identify a specific instance of a resource, LON-CAPA uses symbols
11687: or "symbs"X<symb>. These identifiers are built from the URL of the
11688: map, the resource number of the resource in the map, and the URL of
11689: the resource itself. The latter is somewhat redundant, but might help
11690: if maps change.
11691:
11692: An example is
11693:
11694: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11695:
11696: The respective map entry is
11697:
11698: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11699: title="Problem 2">
11700: </resource>
11701:
11702: Symbs are used by the random number generator, as well as to store and
11703: restore data specific to a certain instance of for example a problem.
11704:
11705: =head2 Storing And Retrieving Data
11706:
11707: X<store()>X<cstore()>X<restore()>Three of the most important functions
11708: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11709: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11710: is is the non-critical message twin of cstore. These functions are for
11711: handlers to store a perl hash to a user's permanent data space in an
11712: easy manner, and to retrieve it again on another call. It is expected
11713: that a handler would use this once at the beginning to retrieve data,
11714: and then again once at the end to send only the new data back.
11715:
11716: The data is stored in the user's data directory on the user's
11717: homeserver under the ID of the course.
11718:
11719: The hash that is returned by restore will have all of the previous
11720: value for all of the elements of the hash.
11721:
11722: Example:
11723:
11724: #creating a hash
11725: my %hash;
11726: $hash{'foo'}='bar';
11727:
11728: #storing it
11729: &Apache::lonnet::cstore(\%hash);
11730:
11731: #changing a value
11732: $hash{'foo'}='notbar';
11733:
11734: #adding a new value
11735: $hash{'bar'}='foo';
11736: &Apache::lonnet::cstore(\%hash);
11737:
11738: #retrieving the hash
11739: my %history=&Apache::lonnet::restore();
11740:
11741: #print the hash
11742: foreach my $key (sort(keys(%history))) {
11743: print("\%history{$key} = $history{$key}");
11744: }
11745:
11746: Will print out:
1.191 harris41 11747:
1.394 bowersj2 11748: %history{1:foo} = bar
11749: %history{1:keys} = foo:timestamp
11750: %history{1:timestamp} = 990455579
11751: %history{2:bar} = foo
11752: %history{2:foo} = notbar
11753: %history{2:keys} = foo:bar:timestamp
11754: %history{2:timestamp} = 990455580
11755: %history{bar} = foo
11756: %history{foo} = notbar
11757: %history{timestamp} = 990455580
11758: %history{version} = 2
11759:
11760: Note that the special hash entries C<keys>, C<version> and
11761: C<timestamp> were added to the hash. C<version> will be equal to the
11762: total number of versions of the data that have been stored. The
11763: C<timestamp> attribute will be the UNIX time the hash was
11764: stored. C<keys> is available in every historical section to list which
11765: keys were added or changed at a specific historical revision of a
11766: hash.
11767:
11768: B<Warning>: do not store the hash that restore returns directly. This
11769: will cause a mess since it will restore the historical keys as if the
11770: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11771:
1.394 bowersj2 11772: Calling convention:
1.191 harris41 11773:
1.394 bowersj2 11774: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11775: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11776:
1.394 bowersj2 11777: For more detailed information, see lonnet specific documentation.
1.191 harris41 11778:
1.394 bowersj2 11779: =head1 RETURN MESSAGES
1.191 harris41 11780:
1.394 bowersj2 11781: =over 4
1.191 harris41 11782:
1.394 bowersj2 11783: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11784:
1.394 bowersj2 11785: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11786: when the connection is brought back up
1.191 harris41 11787:
1.394 bowersj2 11788: =item * B<con_failed>: unable to contact remote host and unable to save message
11789: for later delivery
1.191 harris41 11790:
1.967 bisitz 11791: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11792:
1.394 bowersj2 11793: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11794: that was requested
1.191 harris41 11795:
1.243 albertel 11796: =back
1.191 harris41 11797:
1.243 albertel 11798: =head1 PUBLIC SUBROUTINES
1.191 harris41 11799:
1.243 albertel 11800: =head2 Session Environment Functions
1.191 harris41 11801:
1.243 albertel 11802: =over 4
1.191 harris41 11803:
1.394 bowersj2 11804: =item *
11805: X<appenv()>
1.949 raeburn 11806: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11807: the user envirnoment file, and will be restored for each access this
1.620 albertel 11808: user makes during this session, also modifies the %env for the current
1.949 raeburn 11809: process. Optional rolesarrayref - if defined contains a reference to an array
11810: of roles which are exempt from the restriction on modifying user.role entries
11811: in the user's environment.db and in %env.
1.191 harris41 11812:
11813: =item *
1.394 bowersj2 11814: X<delenv()>
1.987 raeburn 11815: B<delenv($delthis,$regexp)>: removes all items from the session
11816: environment file that begin with $delthis. If the
11817: optional second arg - $regexp - is true, $delthis is treated as a
11818: regular expression, otherwise \Q$delthis\E is used.
11819: The values are also deleted from the current processes %env.
1.191 harris41 11820:
1.795 albertel 11821: =item * get_env_multiple($name)
11822:
11823: gets $name from the %env hash, it seemlessly handles the cases where multiple
11824: values may be defined and end up as an array ref.
11825:
11826: returns an array of values
11827:
1.243 albertel 11828: =back
11829:
11830: =head2 User Information
1.191 harris41 11831:
1.243 albertel 11832: =over 4
1.191 harris41 11833:
11834: =item *
1.394 bowersj2 11835: X<queryauthenticate()>
11836: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11837: authentication scheme
11838:
11839: =item *
1.394 bowersj2 11840: X<authenticate()>
1.1073 raeburn 11841: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11842: authenticate user from domain's lib servers (first use the current
11843: one). C<$upass> should be the users password.
1.1073 raeburn 11844: $checkdefauth is optional (value is 1 if a check should be made to
11845: authenticate user using default authentication method, and allow
11846: account creation if username does not have account in the domain).
11847: $clientcancheckhost is optional (value is 1 if checking whether the
11848: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11849:
11850: =item *
1.394 bowersj2 11851: X<homeserver()>
11852: B<homeserver($uname,$udom)>: find the server which has
11853: the user's directory and files (there must be only one), this caches
11854: the answer, and also caches if there is a borken connection.
1.191 harris41 11855:
11856: =item *
1.394 bowersj2 11857: X<idget()>
11858: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11859: (IDs are a unique resource in a domain, there must be only 1 ID per
11860: username, and only 1 username per ID in a specific domain) (returns
11861: hash: id=>name,id=>name)
1.191 harris41 11862:
11863: =item *
1.394 bowersj2 11864: X<idrget()>
11865: B<idrget($udom,@unames)>: find the IDs behind a list of
11866: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11867:
11868: =item *
1.394 bowersj2 11869: X<idput()>
11870: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11871:
11872: =item *
1.394 bowersj2 11873: X<rolesinit()>
1.1169 droeschl 11874: B<rolesinit($udom,$username)>: get user privileges.
11875: returns user role, first access and timer interval hashes
1.243 albertel 11876:
11877: =item *
1.1171 droeschl 11878: X<privileged()>
11879: B<privileged($username,$domain)>: returns a true if user has a
11880: privileged and active role (i.e. su or dc), false otherwise.
11881:
11882: =item *
1.551 albertel 11883: X<getsection()>
11884: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11885: course $cname, return section name/number or '' for "not in course"
11886: and '-1' for "no section"
11887:
11888: =item *
1.394 bowersj2 11889: X<userenvironment()>
11890: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11891: passed in @what from the requested user's environment, returns a hash
11892:
1.858 raeburn 11893: =item *
11894: X<userlog_query()>
1.859 albertel 11895: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11896: activity.log file. %filters defines filters applied when parsing the
11897: log file. These can be start or end timestamps, or the type of action
11898: - log to look for Login or Logout events, check for Checkin or
11899: Checkout, role for role selection. The response is in the form
11900: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11901: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11902:
1.243 albertel 11903: =back
11904:
11905: =head2 User Roles
11906:
11907: =over 4
11908:
11909: =item *
11910:
1.810 raeburn 11911: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11912: F: full access
11913: U,I,K: authentication modes (cxx only)
11914: '': forbidden
11915: 1: user needs to choose course
11916: 2: browse allowed
1.766 albertel 11917: A: passphrase authentication needed
1.243 albertel 11918:
11919: =item *
11920:
11921: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11922: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11923: and course level
11924:
11925: =item *
11926:
1.988 raeburn 11927: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11928: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11929: $type is Course (default) or Community.
1.988 raeburn 11930: If $forcedefault evaluates to true, text returned will be default
11931: text for $type. Otherwise, if this is a course, the text returned
11932: will be a custom name for the role (if defined in the course's
11933: environment). If no custom name is defined the default is returned.
11934:
1.832 raeburn 11935: =item *
11936:
1.935 raeburn 11937: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11938: All arguments are optional. Returns a hash of a roles, either for
11939: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11940: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11941: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11942: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11943: For each key, value is set to colon-separated start and end times for
11944: the role. If no username and domain are specified, will default to
1.934 raeburn 11945: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11946: of role statuses (active, future or previous), roles
11947: (e.g., cc,in, st etc.) and domains of the roles which can be used
11948: to restrict the list of roles reported. If no array ref is
11949: provided for types, will default to return only active roles.
1.834 albertel 11950:
1.243 albertel 11951: =back
11952:
11953: =head2 User Modification
11954:
11955: =over 4
11956:
11957: =item *
11958:
1.957 raeburn 11959: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11960: user for the level given by URL. Optional start and end dates (leave empty
11961: string or zero for "no date")
1.191 harris41 11962:
11963: =item *
11964:
1.243 albertel 11965: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11966: change a users, password, possible return values are: ok,
11967: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11968: refused
1.191 harris41 11969:
11970: =item *
11971:
1.243 albertel 11972: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11973:
11974: =item *
11975:
1.1058 raeburn 11976: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11977: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11978:
11979: will update user information (firstname,middlename,lastname,generation,
11980: permanentemail), and if forceid is true, student/employee ID also.
11981: A user's institutional affiliation(s) can also be updated.
11982: User information fields will not be overwritten with empty entries
11983: unless the field is included in the $candelete array reference.
11984: This array is included when a single user is modified via "Manage Users",
11985: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11986:
11987: =item *
11988:
1.286 matthew 11989: modifystudent
11990:
1.957 raeburn 11991: modify a student's enrollment and identification information.
1.286 matthew 11992: The course id is resolved based on the current users environment.
11993: This means the envoking user must be a course coordinator or otherwise
11994: associated with a course.
11995:
1.297 matthew 11996: This call is essentially a wrapper for lonnet::modifyuser and
11997: lonnet::modify_student_enrollment
1.286 matthew 11998:
11999: Inputs:
12000:
12001: =over 4
12002:
1.957 raeburn 12003: =item B<$udom> Student's loncapa domain
1.286 matthew 12004:
1.957 raeburn 12005: =item B<$uname> Student's loncapa login name
1.286 matthew 12006:
1.964 bisitz 12007: =item B<$uid> Student/Employee ID
1.286 matthew 12008:
1.957 raeburn 12009: =item B<$umode> Student's authentication mode
1.286 matthew 12010:
1.957 raeburn 12011: =item B<$upass> Student's password
1.286 matthew 12012:
1.957 raeburn 12013: =item B<$first> Student's first name
1.286 matthew 12014:
1.957 raeburn 12015: =item B<$middle> Student's middle name
1.286 matthew 12016:
1.957 raeburn 12017: =item B<$last> Student's last name
1.286 matthew 12018:
1.957 raeburn 12019: =item B<$gene> Student's generation
1.286 matthew 12020:
1.957 raeburn 12021: =item B<$usec> Student's section in course
1.286 matthew 12022:
12023: =item B<$end> Unix time of the roles expiration
12024:
12025: =item B<$start> Unix time of the roles start date
12026:
12027: =item B<$forceid> If defined, allow $uid to be changed
12028:
12029: =item B<$desiredhome> server to use as home server for student
12030:
1.957 raeburn 12031: =item B<$email> Student's permanent e-mail address
12032:
12033: =item B<$type> Type of enrollment (auto or manual)
12034:
1.963 raeburn 12035: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12036:
12037: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12038:
1.963 raeburn 12039: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12040:
1.963 raeburn 12041: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12042:
1.963 raeburn 12043: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 12044:
1.286 matthew 12045: =back
1.297 matthew 12046:
12047: =item *
12048:
12049: modify_student_enrollment
12050:
12051: Change a students enrollment status in a class. The environment variable
12052: 'role.request.course' must be defined for this function to proceed.
12053:
12054: Inputs:
12055:
12056: =over 4
12057:
12058: =item $udom, students domain
12059:
12060: =item $uname, students name
12061:
12062: =item $uid, students user id
12063:
12064: =item $first, students first name
12065:
12066: =item $middle
12067:
12068: =item $last
12069:
12070: =item $gene
12071:
12072: =item $usec
12073:
12074: =item $end
12075:
12076: =item $start
12077:
1.957 raeburn 12078: =item $type
12079:
12080: =item $locktype
12081:
12082: =item $cid
12083:
12084: =item $selfenroll
12085:
12086: =item $context
12087:
1.297 matthew 12088: =back
12089:
1.191 harris41 12090:
12091: =item *
12092:
1.243 albertel 12093: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12094: custom role; give a custom role to a user for the level given by URL. Specify
12095: name and domain of role author, and role name
1.191 harris41 12096:
12097: =item *
12098:
1.243 albertel 12099: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12100:
12101: =item *
12102:
1.243 albertel 12103: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12104:
12105: =back
12106:
12107: =head2 Course Infomation
12108:
12109: =over 4
1.191 harris41 12110:
12111: =item *
12112:
1.1118 foxr 12113: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12114: specified course id, including all environment settings for the
12115: course, the description of the course will be in the hash under the
12116: key 'description'
1.191 harris41 12117:
1.1118 foxr 12118: $options is an optional parameter that if supplied is a hash reference that controls
12119: what how this function works. It has the following key/values:
12120:
12121: =over 4
12122:
12123: =item freshen_cache
12124:
12125: If defined, and the environment cache for the course is valid, it is
12126: returned in the returned hash.
12127:
12128: =item one_time
12129:
12130: If defined, the last cache time is set to _now_
12131:
12132: =item user
12133:
12134: If defined, the supplied username is used instead of the current user.
12135:
12136:
12137: =back
12138:
1.191 harris41 12139: =item *
12140:
1.624 albertel 12141: resdata($name,$domain,$type,@which) : request for current parameter
12142: setting for a specific $type, where $type is either 'course' or 'user',
12143: @what should be a list of parameters to ask about. This routine caches
12144: answers for 5 minutes.
1.243 albertel 12145:
1.877 foxr 12146: =item *
12147:
12148: get_courseresdata($courseid, $domain) : dump the entire course resource
12149: data base, returning a hash that is keyed by the resource name and has
12150: values that are the resource value. I believe that the timestamps and
12151: versions are also returned.
12152:
12153:
1.243 albertel 12154: =back
12155:
12156: =head2 Course Modification
12157:
12158: =over 4
1.191 harris41 12159:
12160: =item *
12161:
1.243 albertel 12162: writecoursepref($courseid,%prefs) : write preferences (environment
12163: database) for a course
1.191 harris41 12164:
12165: =item *
12166:
1.1011 raeburn 12167: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12168:
12169: =item *
12170:
1.1038 raeburn 12171: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12172:
1.1167 droeschl 12173: =item *
12174:
12175: is_course($courseid), is_course($cdom, $cnum)
12176:
12177: Accepts either a combined $courseid (in the form of domain_courseid) or the
12178: two component version $cdom, $cnum. It checks if the specified course exists.
12179:
12180: Returns:
12181: undef if the course doesn't exist, otherwise
12182: in scalar context the combined courseid.
12183: in list context the two components of the course identifier, domain and
12184: courseid.
12185:
1.243 albertel 12186: =back
12187:
12188: =head2 Resource Subroutines
12189:
12190: =over 4
1.191 harris41 12191:
12192: =item *
12193:
1.243 albertel 12194: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12195:
12196: =item *
12197:
1.243 albertel 12198: repcopy($filename) : subscribes to the requested file, and attempts to
12199: replicate from the owning library server, Might return
1.607 raeburn 12200: 'unavailable', 'not_found', 'forbidden', 'ok', or
12201: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12202: resource. Expects the local filesystem pathname
12203: (/home/httpd/html/res/....)
12204:
12205: =back
12206:
12207: =head2 Resource Information
12208:
12209: =over 4
1.191 harris41 12210:
12211: =item *
12212:
1.243 albertel 12213: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12214: a vairety of different possible values, $varname should be a request
12215: string, and the other parameters can be used to specify who and what
12216: one is asking about.
12217:
12218: Possible values for $varname are environment.lastname (or other item
12219: from the envirnment hash), user.name (or someother aspect about the
12220: user), resource.0.maxtries (or some other part and parameter of a
12221: resource)
1.204 albertel 12222:
12223: =item *
12224:
1.243 albertel 12225: directcondval($number) : get current value of a condition; reads from a state
12226: string
1.204 albertel 12227:
12228: =item *
12229:
1.243 albertel 12230: condval($condidx) : value of condition index based on state
1.204 albertel 12231:
12232: =item *
12233:
1.243 albertel 12234: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12235: resource's metadata, $what should be either a specific key, or either
12236: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12237: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12238:
12239: this function automatically caches all requests
1.191 harris41 12240:
12241: =item *
12242:
1.243 albertel 12243: metadata_query($query,$custom,$customshow) : make a metadata query against the
12244: network of library servers; returns file handle of where SQL and regex results
12245: will be stored for query
1.191 harris41 12246:
12247: =item *
12248:
1.243 albertel 12249: symbread($filename) : return symbolic list entry (filename argument optional);
12250: returns the data handle
1.191 harris41 12251:
12252: =item *
12253:
1.243 albertel 12254: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 12255: a possible symb for the URL in $thisfn, and if is an encryypted
12256: resource that the user accessed using /enc/ returns a 1 on success, 0
12257: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 12258: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 12259:
1.191 harris41 12260:
12261: =item *
12262:
1.243 albertel 12263: symbclean($symb) : removes versions numbers from a symb, returns the
12264: cleaned symb
1.191 harris41 12265:
12266: =item *
12267:
1.243 albertel 12268: is_on_map($uri) : checks if the $uri is somewhere on the current
12269: course map, user must be in a course for it to work.
1.191 harris41 12270:
12271: =item *
12272:
1.243 albertel 12273: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12274:
12275: =item *
12276:
1.243 albertel 12277: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12278: a random seed, all arguments are optional, if they aren't sent it uses the
12279: environment to derive them. Note: if symb isn't sent and it can't get one
12280: from &symbread it will use the current time as its return value
1.191 harris41 12281:
12282: =item *
12283:
1.243 albertel 12284: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12285: unfakeable, receipt
1.191 harris41 12286:
12287: =item *
12288:
1.620 albertel 12289: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12290:
12291: =item *
12292:
1.243 albertel 12293: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12294:
12295: =item *
12296:
1.243 albertel 12297: 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 12298:
12299: =item *
12300:
1.243 albertel 12301: 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 12302:
12303: =item *
12304:
1.243 albertel 12305: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12306:
12307: =item *
12308:
1.243 albertel 12309: devalidate($symb) : devalidate temporary spreadsheet calculations,
12310: forcing spreadsheet to reevaluate the resource scores next time.
12311:
12312: =back
12313:
12314: =head2 Storing/Retreiving Data
12315:
12316: =over 4
1.191 harris41 12317:
12318: =item *
12319:
1.243 albertel 12320: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12321: for this url; hashref needs to be given and should be a \%hashname; the
12322: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12323: be derived from the env
1.191 harris41 12324:
12325: =item *
12326:
1.243 albertel 12327: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12328: uses critical subroutine
1.191 harris41 12329:
12330: =item *
12331:
1.243 albertel 12332: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12333: all args are optional
1.191 harris41 12334:
12335: =item *
12336:
1.717 albertel 12337: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12338: dumps the complete (or key matching regexp) namespace into a hash
12339: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12340: normally &store()ed into
12341:
12342: $range should be either an integer '100' (give me the first 100
12343: matching records)
12344: or be two integers sperated by a - with no spaces
12345: '30-50' (give me the 30th through the 50th matching
12346: records)
12347:
12348:
12349: =item *
12350:
12351: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12352: replaces a &store() version of data with a replacement set of data
12353: for a particular resource in a namespace passed in the $storehash hash
12354: reference
12355:
12356: =item *
12357:
1.243 albertel 12358: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12359: works very similar to store/cstore, but all data is stored in a
12360: temporary location and can be reset using tmpreset, $storehash should
12361: be a hash reference, returns nothing on success
1.191 harris41 12362:
12363: =item *
12364:
1.243 albertel 12365: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12366: similar to restore, but all data is stored in a temporary location and
12367: can be reset using tmpreset. Returns a hash of values on success,
12368: error string otherwise.
1.191 harris41 12369:
12370: =item *
12371:
1.243 albertel 12372: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12373: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12374:
12375: =item *
12376:
1.243 albertel 12377: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12378: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12379:
12380: =item *
12381:
1.243 albertel 12382: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12383: namesp ($udom and $uname are optional)
1.191 harris41 12384:
12385: =item *
12386:
1.702 albertel 12387: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12388: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12389: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12390:
1.702 albertel 12391: $range should be either an integer '100' (give me the first 100
12392: matching records)
12393: or be two integers sperated by a - with no spaces
12394: '30-50' (give me the 30th through the 50th matching
12395: records)
1.449 matthew 12396: =item *
12397:
12398: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12399: $store can be a scalar, an array reference, or if the amount to be
12400: incremented is > 1, a hash reference.
12401:
12402: ($udom and $uname are optional)
1.191 harris41 12403:
12404: =item *
12405:
1.243 albertel 12406: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12407: ($udom and $uname are optional)
1.191 harris41 12408:
12409: =item *
12410:
1.243 albertel 12411: cput($namespace,$storehash,$udom,$uname) : critical put
12412: ($udom and $uname are optional)
1.191 harris41 12413:
12414: =item *
12415:
1.748 albertel 12416: newput($namespace,$storehash,$udom,$uname) :
12417:
12418: Attempts to store the items in the $storehash, but only if they don't
12419: currently exist, if this succeeds you can be certain that you have
12420: successfully created a new key value pair in the $namespace db.
12421:
12422:
12423: Args:
12424: $namespace: name of database to store values to
12425: $storehash: hashref to store to the db
12426: $udom: (optional) domain of user containing the db
12427: $uname: (optional) name of user caontaining the db
12428:
12429: Returns:
12430: 'ok' -> succeeded in storing all keys of $storehash
12431: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12432: least <key> already existed in the db (other
12433: requested keys may also already exist)
1.967 bisitz 12434: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12435: 'con_lost' -> unable to contact request server
12436: 'refused' -> action was not allowed by remote machine
12437:
12438:
12439: =item *
12440:
1.243 albertel 12441: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12442: reference filled in from namesp (encrypts the return communication)
12443: ($udom and $uname are optional)
1.191 harris41 12444:
12445: =item *
12446:
1.243 albertel 12447: log($udom,$name,$home,$message) : write to permanent log for user; use
12448: critical subroutine
12449:
1.806 raeburn 12450: =item *
12451:
1.860 raeburn 12452: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12453: array reference filled in from namespace found in domain level on either
12454: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12455:
12456: =item *
12457:
1.860 raeburn 12458: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12459: domain level either on specified domain server ($uhome) or primary domain
12460: server ($udom and $uhome are optional)
1.806 raeburn 12461:
1.943 raeburn 12462: =item *
12463:
12464: get_domain_defaults($target_domain) : returns hash with defaults for
12465: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12466: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12467: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12468: Values are retrieved from cache (if current), or from domain's configuration.db
12469: (if available), or lastly from values in lonTabs/dns_domain,tab,
12470: or lonTabs/domain.tab.
12471:
12472: %domdefaults = &get_auth_defaults($target_domain);
12473:
1.243 albertel 12474: =back
12475:
12476: =head2 Network Status Functions
12477:
12478: =over 4
1.191 harris41 12479:
12480: =item *
12481:
1.1137 raeburn 12482: dirlist() : return directory list based on URI (first arg).
12483:
12484: Inputs: 1 required, 5 optional.
12485:
12486: =over
12487:
12488: =item
12489: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12490:
12491: =item
12492: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12493:
12494: =item
12495: $username - username of user/course to be listed. Extracted from $uri if absent.
12496:
12497: =item
12498: $getpropath - boolean: 1 if prepend path using &propath().
12499:
12500: =item
12501: $getuserdir - boolean: 1 if prepend path for "userfiles".
12502:
12503: =item
12504: $alternateRoot - path to prepend in place of path from $uri.
12505:
12506: =back
12507:
12508: Returns: Array of up to two items.
12509:
12510: =over
12511:
12512: a reference to an array of files/subdirectories
12513:
12514: =over
12515:
12516: Each element in the array of files/subdirectories is a & separated list of
12517: item name and the result of running stat on the item. If dirlist was requested
12518: for a file instead of a directory, the item name will be ''. For a directory
12519: listing, if the item is a metadata file, the element will end &N&M
12520: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12521: default copyright set (1).
12522:
12523: =back
12524:
12525: a scalar containing error condition (if encountered).
12526:
12527: =over
12528:
12529: =item
12530: no_host (no homeserver identified for $username:$domain).
12531:
12532: =item
12533: no_such_host (server contacted for listing not identified as valid host).
12534:
12535: =item
12536: con_lost (connection to remote server failed).
12537:
12538: =item
12539: refused (invalid $username:$domain received on lond side).
12540:
12541: =item
12542: no_such_dir (directory at specified path on lond side does not exist).
12543:
12544: =item
12545: empty (directory at specified path on lond side is empty).
12546:
12547: =over
12548:
12549: This is currently not encountered because the &ls3, &ls2,
12550: &ls (_handler) routines on the lond side do not filter out
12551: . and .. from a directory listing.
12552:
12553: =back
12554:
12555: =back
12556:
12557: =back
1.191 harris41 12558:
12559: =item *
12560:
1.243 albertel 12561: spareserver() : find server with least workload from spare.tab
12562:
1.986 foxr 12563:
12564: =item *
12565:
12566: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12567: if there is no corresponding loncapa host.
12568:
1.243 albertel 12569: =back
12570:
1.986 foxr 12571:
1.243 albertel 12572: =head2 Apache Request
12573:
12574: =over 4
1.191 harris41 12575:
12576: =item *
12577:
1.243 albertel 12578: ssi($url,%hash) : server side include, does a complete request cycle on url to
12579: localhost, posts hash
12580:
12581: =back
12582:
12583: =head2 Data to String to Data
12584:
12585: =over 4
1.191 harris41 12586:
12587: =item *
12588:
1.243 albertel 12589: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12590: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12591:
12592: =item *
12593:
1.243 albertel 12594: hashref2str($hashref) : convert a hashref into a string complete with
12595: escaping and '=' and '&' separators, supports elements that are
12596: arrayrefs and hashrefs
1.191 harris41 12597:
12598: =item *
12599:
1.243 albertel 12600: arrayref2str($arrayref) : convert an arrayref into a string complete
12601: with escaping and '&' separators, supports elements that are arrayrefs
12602: and hashrefs
1.191 harris41 12603:
12604: =item *
12605:
1.243 albertel 12606: str2hash($string) : convert string to hash using unescaping and
12607: splitting on '=' and '&', supports elements that are arrayrefs and
12608: hashrefs
1.191 harris41 12609:
12610: =item *
12611:
1.243 albertel 12612: str2array($string) : convert string to hash using unescaping and
12613: splitting on '&', supports elements that are arrayrefs and hashrefs
12614:
12615: =back
12616:
12617: =head2 Logging Routines
12618:
12619:
12620: These routines allow one to make log messages in the lonnet.log and
12621: lonnet.perm logfiles.
1.191 harris41 12622:
1.1119 foxr 12623: =over 4
12624:
1.191 harris41 12625: =item *
12626:
1.243 albertel 12627: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12628:
12629: =item *
12630:
1.243 albertel 12631: logthis() : append message to the normal lonnet.log file, it gets
12632: preiodically rolled over and deleted.
1.191 harris41 12633:
12634: =item *
12635:
1.243 albertel 12636: logperm() : append a permanent message to lonnet.perm.log, this log
12637: file never gets deleted by any automated portion of the system, only
12638: messages of critical importance should go in here.
12639:
1.1119 foxr 12640:
1.243 albertel 12641: =back
12642:
12643: =head2 General File Helper Routines
12644:
12645: =over 4
1.191 harris41 12646:
12647: =item *
12648:
1.481 raeburn 12649: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12650: (a) files in /uploaded
12651: (i) If a local copy of the file exists -
12652: compares modification date of local copy with last-modified date for
12653: definitive version stored on home server for course. If local copy is
12654: stale, requests a new version from the home server and stores it.
12655: If the original has been removed from the home server, then local copy
12656: is unlinked.
12657: (ii) If local copy does not exist -
12658: requests the file from the home server and stores it.
12659:
12660: If $caller is 'uploadrep':
12661: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12662: for request for files originally uploaded via DOCS.
12663: - returns 'ok' if fresh local copy now available, -1 otherwise.
12664:
12665: Otherwise:
12666: This indicates a call from the content generation phase of the request.
12667: - returns the entire contents of the file or -1.
12668:
12669: (b) files in /res
12670: - returns the entire contents of a file or -1;
12671: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12672:
1.712 albertel 12673:
12674: =item *
12675:
12676: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12677: reference
12678:
12679: returns either a stat() list of data about the file or an empty list
12680: if the file doesn't exist or couldn't find out about it (connection
12681: problems or user unknown)
12682:
1.191 harris41 12683: =item *
12684:
1.243 albertel 12685: filelocation($dir,$file) : returns file system location of a file
12686: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12687: directory that relative $file lookups are to looked in ($dir of /a/dir
12688: and a file of ../bob will become /a/bob)
1.191 harris41 12689:
12690: =item *
12691:
12692: hreflocation($dir,$file) : returns file system location or a URL; same as
12693: filelocation except for hrefs
12694:
12695: =item *
12696:
12697: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12698:
1.243 albertel 12699: =back
12700:
1.608 albertel 12701: =head2 Usererfile file routines (/uploaded*)
12702:
12703: =over 4
12704:
12705: =item *
12706:
12707: userfileupload(): main rotine for putting a file in a user or course's
12708: filespace, arguments are,
12709:
1.620 albertel 12710: formname - required - this is the name of the element in $env where the
1.608 albertel 12711: filename, and the contents of the file to create/modifed exist
1.620 albertel 12712: the filename is in $env{'form.'.$formname.'.filename'} and the
12713: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12714: context - if coursedoc, store the file in the course of the active role
12715: of the current user;
12716: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12717: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12718: subdir - required - subdirectory to put the file in under ../userfiles/
12719: if undefined, it will be placed in "unknown"
12720:
12721: (This routine calls clean_filename() to remove any dangerous
12722: characters from the filename, and then calls finuserfileupload() to
12723: complete the transaction)
12724:
12725: returns either the url of the uploaded file (/uploaded/....) if successful
12726: and /adm/notfound.html if unsuccessful
12727:
12728: =item *
12729:
12730: clean_filename(): routine for cleaing a filename up for storage in
12731: userfile space, argument is:
12732:
12733: filename - proposed filename
12734:
12735: returns: the new clean filename
12736:
12737: =item *
12738:
1.1090 raeburn 12739: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12740: userspace, probably shouldn't be called directly
12741:
12742: docuname: username or courseid of destination for the file
12743: docudom: domain of user/course of destination for the file
12744: formname: same as for userfileupload()
1.1090 raeburn 12745: fname: filename (including subdirectories) for the file
12746: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12747: allfiles: reference to hash used to store objects found by parser
12748: codebase: reference to hash used for codebases of java objects found by parser
12749: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12750: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12751: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12752: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12753: context: if 'overwrite', will move the uploaded file from its temporary location to
12754: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12755: mimetype: reference to scalar to accommodate mime type determined
12756: from File::MMagic if $parser = parse.
1.608 albertel 12757:
12758: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12759: and /adm/notfound.html if unsuccessful (or an error message if context
12760: was 'overwrite').
12761:
1.608 albertel 12762:
12763: =item *
12764:
12765: renameuserfile(): renames an existing userfile to a new name
12766:
12767: Args:
12768: docuname: username or courseid of destination for the file
12769: docudom: domain of user/course of destination for the file
12770: old: current file name (including any subdirs under userfiles)
12771: new: desired file name (including any subdirs under userfiles)
12772:
12773: =item *
12774:
12775: mkdiruserfile(): creates a directory is a userfiles dir
12776:
12777: Args:
12778: docuname: username or courseid of destination for the file
12779: docudom: domain of user/course of destination for the file
12780: dir: dir to create (including any subdirs under userfiles)
12781:
12782: =item *
12783:
12784: removeuserfile(): removes a file that exists in userfiles
12785:
12786: Args:
12787: docuname: username or courseid of destination for the file
12788: docudom: domain of user/course of destination for the file
12789: fname: filname to delete (including any subdirs under userfiles)
12790:
12791: =item *
12792:
12793: removeuploadedurl(): convience function for removeuserfile()
12794:
12795: Args:
12796: url: a full /uploaded/... url to delete
12797:
1.747 albertel 12798: =item *
12799:
12800: get_portfile_permissions():
12801: Args:
12802: domain: domain of user or course contain the portfolio files
12803: user: name of user or num of course contain the portfolio files
12804: Returns:
12805: hashref of a dump of the proper file_permissions.db
12806:
12807:
12808: =item *
12809:
12810: get_access_controls():
12811:
12812: Args:
12813: current_permissions: the hash ref returned from get_portfile_permissions()
12814: group: (optional) the group you want the files associated with
12815: file: (optional) the file you want access info on
12816:
12817: Returns:
1.749 raeburn 12818: a hash (keys are file names) of hashes containing
12819: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12820: values are XML containing access control settings (see below)
1.747 albertel 12821:
12822: Internal notes:
12823:
1.749 raeburn 12824: access controls are stored in file_permissions.db as key=value pairs.
12825: key -> path to file/file_name\0uniqueID:scope_end_start
12826: where scope -> public,guest,course,group,domains or users.
12827: end -> UNIX time for end of access (0 -> no end date)
12828: start -> UNIX time for start of access
12829:
12830: value -> XML description of access control
12831: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12832: <start></start>
12833: <end></end>
12834:
12835: <password></password> for scope type = guest
12836:
12837: <domain></domain> for scope type = course or group
12838: <number></number>
12839: <roles id="">
12840: <role></role>
12841: <access></access>
12842: <section></section>
12843: <group></group>
12844: </roles>
12845:
12846: <dom></dom> for scope type = domains
12847:
12848: <users> for scope type = users
12849: <user>
12850: <uname></uname>
12851: <udom></udom>
12852: </user>
12853: </users>
12854: </scope>
12855:
12856: Access data is also aggregated for each file in an additional key=value pair:
12857: key -> path to file/file_name\0accesscontrol
12858: value -> reference to hash
12859: hash contains key = value pairs
12860: where key = uniqueID:scope_end_start
12861: value = UNIX time record was last updated
12862:
12863: Used to improve speed of look-ups of access controls for each file.
12864:
12865: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12866:
12867: modify_access_controls():
12868:
12869: Modifies access controls for a portfolio file
12870: Args
12871: 1. file name
12872: 2. reference to hash of required changes,
12873: 3. domain
12874: 4. username
12875: where domain,username are the domain of the portfolio owner
12876: (either a user or a course)
12877:
12878: Returns:
12879: 1. result of additions or updates ('ok' or 'error', with error message).
12880: 2. result of deletions ('ok' or 'error', with error message).
12881: 3. reference to hash of any new or updated access controls.
12882: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12883: key = integer (inbound ID)
12884: value = uniqueID
1.747 albertel 12885:
1.608 albertel 12886: =back
12887:
1.243 albertel 12888: =head2 HTTP Helper Routines
12889:
12890: =over 4
12891:
1.191 harris41 12892: =item *
12893:
12894: escape() : unpack non-word characters into CGI-compatible hex codes
12895:
12896: =item *
12897:
12898: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12899:
1.243 albertel 12900: =back
12901:
12902: =head1 PRIVATE SUBROUTINES
12903:
12904: =head2 Underlying communication routines (Shouldn't call)
12905:
12906: =over 4
12907:
12908: =item *
12909:
12910: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12911:
12912: =item *
12913:
12914: reply() : uses subreply to send a message to remote machine, logs all failures
12915:
12916: =item *
12917:
12918: critical() : passes a critical message to another server; if cannot
12919: get through then place message in connection buffer directory and
12920: returns con_delayed, if incapable of saving message, returns
12921: con_failed
12922:
12923: =item *
12924:
12925: reconlonc() : tries to reconnect lonc client processes.
12926:
12927: =back
12928:
12929: =head2 Resource Access Logging
12930:
12931: =over 4
12932:
12933: =item *
12934:
12935: flushcourselogs() : flush (save) buffer logs and access logs
12936:
12937: =item *
12938:
12939: courselog($what) : save message for course in hash
12940:
12941: =item *
12942:
12943: courseacclog($what) : save message for course using &courselog(). Perform
12944: special processing for specific resource types (problems, exams, quizzes, etc).
12945:
1.191 harris41 12946: =item *
12947:
12948: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12949: as a PerlChildExitHandler
1.243 albertel 12950:
12951: =back
12952:
12953: =head2 Other
12954:
12955: =over 4
12956:
12957: =item *
12958:
12959: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12960:
12961: =back
12962:
12963: =cut
1.877 foxr 12964:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>