File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1241:
download - view:
text,
annotated -
select for diffs
Sun Oct 6 20:33:51 2013 UTC (10 years, 10 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Change to args expected by lonnet::remote_devalidate_cache() and
change to corresponding &server_devalidatecache_handler() on lond side.
- On the lonnet side remote_devalidate_cache() now expects an array of
escaped cache keys as the second argument.
- On the lond side &server_devalidatecache_handler() calls
lonnet::devalidate_cache_new() on each of the cache keys passed to it.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1241 2013/10/06 20:33:51 raeburn Exp $
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: #
28: ###
29:
30: =pod
31:
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:
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:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78:
79: use Encode;
80:
81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
88: %courseownerbuf, %coursetypebuf,$locknum);
89:
90: use IO::Socket;
91: use GDBM_File;
92: use HTML::LCParser;
93: use Fcntl qw(:flock);
94: use Storable qw(thaw nfreeze);
95: use Time::HiRes qw( gettimeofday tv_interval );
96: use Cache::Memcached;
97: use Digest::MD5;
98: use Math::Random;
99: use File::MMagic;
100: use LONCAPA qw(:DEFAULT :match);
101: use LONCAPA::Configuration;
102: use LONCAPA::lonmetadata;
103: use LONCAPA::Lond;
104:
105: use File::Copy;
106:
107: my $readit;
108: my $max_connection_retries = 10; # Or some such value.
109:
110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
115:
116: # ------------------------------------ Logging (parameters, docs, slots, roles)
117: {
118: my $logid;
119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
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: }
126: }
127: $logid ++;
128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
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);
143: }
144: }
145:
146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
164: close($fh);
165: }
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);
174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
178: return 1;
179: }
180:
181: sub create_connection {
182: my ($hostname,$lonid) = @_;
183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
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: }
208:
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:
232: sub get_server_loncaparev {
233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
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)) {
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'};
259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
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;
267: $ua->timeout(4);
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;
275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
283: $loncaparev = $1;
284: }
285: }
286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
287: }
288: }
289:
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:
318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
324: my ($response,$cached);
325: unless ($ignore_cache) {
326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
327: }
328: if (defined($cached)) {
329: $returnhash{$what} = $response;
330: } else {
331: $whatneeded{$what} = 1;
332: }
333: }
334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
344: my @pairs=split(/\&/,$rep);
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);
351: }
352: }
353: }
354: }
355: return ($result,\%returnhash);
356: }
357:
358: sub remote_devalidate_cache {
359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
364: return $response;
365: }
366:
367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
381: # or loncnew child is listening so we can connect or everything's dead.
382: #
383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
391: if ($client) {
392: last; # Connected!
393: } else {
394: &create_connection(&hostname($server),$server);
395: }
396: sleep(1); # Try again later if failed connection.
397: }
398: my $answer;
399: if ($client) {
400: print $client "sethost:$server:$cmd\n";
401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
412: unless (defined(&hostname($server))) { return 'no_such_host'; }
413: my $answer=subreply($cmd,$server);
414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
415: &logthis("<font color=\"blue\">WARNING:".
416: " $cmd to $server returned $answer</font>");
417: }
418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
442: &logthis("Trying to reconnect lonc");
443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
444: if (open(my $fh,"<$loncfile")) {
445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
451: } else {
452: &logthis(
453: "<font color=\"blue\">WARNING:".
454: " lonc at pid $loncpid not responding, giving up</font>");
455: }
456: } else {
457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
462:
463: sub critical {
464: my ($cmd,$server)=@_;
465: unless (&hostname($server)) {
466: &logthis("<font color=\"blue\">WARNING:".
467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
473: my $answer=reply($cmd,$server);
474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
477: $middlename=substr($middlename,0,16);
478: $middlename=~s/\W//g;
479: my $dfilename=
480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
482: {
483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
488: }
489: sleep 2;
490: my $wcmd='';
491: {
492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
497: }
498: chomp($wcmd);
499: if ($wcmd eq $cmd) {
500: &logthis("<font color=\"blue\">WARNING: ".
501: "Connection buffer $dfilename: $cmd</font>");
502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
505: &logthis("<font color=\"red\">CRITICAL:"
506: ." Critical connection failed: $server $cmd</font>");
507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
513: }
514:
515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
532: return 0;
533: }
534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
540: if ($line !~ m/=/) {
541: return 0;
542: }
543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
554: return 1;
555: }
556:
557: # ------------------------------------------- Transfer profile into environment
558: my $env_loaded;
559: sub transfer_profile_to_env {
560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
562:
563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
570: my $convert;
571: {
572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
574: return;
575: }
576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
589: }
590:
591: my %remove;
592: while ( my $envname = each(%env) ) {
593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
595: $remove{$key}++;
596: }
597: }
598: }
599:
600: $env{'user.environment'} = "$lonidsdir/$handle.id";
601: $env_loaded=1;
602: foreach my $expired_key (keys(%remove)) {
603: &delenv($expired_key);
604: }
605: }
606:
607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
609: my ($r,$name) = @_;
610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
624: return undef if (!-e "$lonidsdir/$handle.id");
625:
626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
640: if (($r->user() eq '') && ($apache >= 2.4)) {
641: if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
642: $r->user($disk_env{'user.name'});
643: } else {
644: $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
645: }
646: }
647: return $handle;
648: }
649:
650: sub timed_flock {
651: my ($file,$lock_type) = @_;
652: my $failed=0;
653: eval {
654: local $SIG{__DIE__}='DEFAULT';
655: local $SIG{ALRM}=sub {
656: $failed=1;
657: die("failed lock");
658: };
659: alarm(13);
660: flock($file,$lock_type);
661: alarm(0);
662: };
663: if ($failed) {
664: return undef;
665: } else {
666: return 1;
667: }
668: }
669:
670: # ---------------------------------------------------------- Append Environment
671:
672: sub appenv {
673: my ($newenv,$roles) = @_;
674: if (ref($newenv) eq 'HASH') {
675: foreach my $key (keys(%{$newenv})) {
676: my $refused = 0;
677: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
678: $refused = 1;
679: if (ref($roles) eq 'ARRAY') {
680: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
681: if (grep(/^\Q$role\E$/,@{$roles})) {
682: $refused = 0;
683: }
684: }
685: }
686: if ($refused) {
687: &logthis("<font color=\"blue\">WARNING: ".
688: "Attempt to modify environment ".$key." to ".$newenv->{$key}
689: .'</font>');
690: delete($newenv->{$key});
691: } else {
692: $env{$key}=$newenv->{$key};
693: }
694: }
695: my $opened = open(my $env_file,'+<',$env{'user.environment'});
696: if ($opened
697: && &timed_flock($env_file,LOCK_EX)
698: &&
699: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
700: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
701: while (my ($key,$value) = each(%{$newenv})) {
702: $disk_env{$key} = $value;
703: }
704: untie(%disk_env);
705: }
706: }
707: return 'ok';
708: }
709: # ----------------------------------------------------- Delete from Environment
710:
711: sub delenv {
712: my ($delthis,$regexp,$roles) = @_;
713: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
714: my $refused = 1;
715: if (ref($roles) eq 'ARRAY') {
716: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
717: if (grep(/^\Q$role\E$/,@{$roles})) {
718: $refused = 0;
719: }
720: }
721: if ($refused) {
722: &logthis("<font color=\"blue\">WARNING: ".
723: "Attempt to delete from environment ".$delthis);
724: return 'error';
725: }
726: }
727: my $opened = open(my $env_file,'+<',$env{'user.environment'});
728: if ($opened
729: && &timed_flock($env_file,LOCK_EX)
730: &&
731: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
732: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
733: foreach my $key (keys(%disk_env)) {
734: if ($regexp) {
735: if ($key=~/^$delthis/) {
736: delete($env{$key});
737: delete($disk_env{$key});
738: }
739: } else {
740: if ($key=~/^\Q$delthis\E/) {
741: delete($env{$key});
742: delete($disk_env{$key});
743: }
744: }
745: }
746: untie(%disk_env);
747: }
748: return 'ok';
749: }
750:
751: sub get_env_multiple {
752: my ($name) = @_;
753: my @values;
754: if (defined($env{$name})) {
755: # exists is it an array
756: if (ref($env{$name})) {
757: @values=@{ $env{$name} };
758: } else {
759: $values[0]=$env{$name};
760: }
761: }
762: return(@values);
763: }
764:
765: # ------------------------------------------------------------------- Locking
766:
767: sub set_lock {
768: my ($text)=@_;
769: $locknum++;
770: my $id=$$.'-'.$locknum;
771: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
772: 'session.lock.'.$id => $text});
773: return $id;
774: }
775:
776: sub get_locks {
777: my $num=0;
778: my %texts=();
779: foreach my $lock (split(/\,/,$env{'session.locks'})) {
780: if ($lock=~/\w/) {
781: $num++;
782: $texts{$lock}=$env{'session.lock.'.$lock};
783: }
784: }
785: return ($num,%texts);
786: }
787:
788: sub remove_lock {
789: my ($id)=@_;
790: my $newlocks='';
791: foreach my $lock (split(/\,/,$env{'session.locks'})) {
792: if (($lock=~/\w/) && ($lock ne $id)) {
793: $newlocks.=','.$lock;
794: }
795: }
796: &appenv({'session.locks' => $newlocks});
797: &delenv('session.lock.'.$id);
798: }
799:
800: sub remove_all_locks {
801: my $activelocks=$env{'session.locks'};
802: foreach my $lock (split(/\,/,$env{'session.locks'})) {
803: if ($lock=~/\w/) {
804: &remove_lock($lock);
805: }
806: }
807: }
808:
809:
810: # ------------------------------------------ Find out current server userload
811: sub userload {
812: my $numusers=0;
813: {
814: opendir(LONIDS,$perlvar{'lonIDsDir'});
815: my $filename;
816: my $curtime=time;
817: while ($filename=readdir(LONIDS)) {
818: next if ($filename eq '.' || $filename eq '..');
819: next if ($filename =~ /publicuser_\d+\.id/);
820: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
821: if ($curtime-$mtime < 1800) { $numusers++; }
822: }
823: closedir(LONIDS);
824: }
825: my $userloadpercent=0;
826: my $maxuserload=$perlvar{'lonUserLoadLim'};
827: if ($maxuserload) {
828: $userloadpercent=100*$numusers/$maxuserload;
829: }
830: $userloadpercent=sprintf("%.2f",$userloadpercent);
831: return $userloadpercent;
832: }
833:
834: # ------------------------------ Find server with least workload from spare.tab
835:
836: sub spareserver {
837: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
838: my $spare_server;
839: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
840: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
841: : $userloadpercent;
842: my ($uint_dom,$remotesessions);
843: if (($udom ne '') && (&domain($udom) ne '')) {
844: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
845: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
846: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
847: $remotesessions = $udomdefaults{'remotesessions'};
848: }
849: my $spareshash = &this_host_spares($udom);
850: if (ref($spareshash) eq 'HASH') {
851: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
852: foreach my $try_server (@{ $spareshash->{'primary'} }) {
853: if ($uint_dom) {
854: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
855: $try_server));
856: }
857: ($spare_server, $lowest_load) =
858: &compare_server_load($try_server, $spare_server, $lowest_load);
859: }
860: }
861:
862: my $found_server = ($spare_server ne '' && $lowest_load < 100);
863:
864: if (!$found_server) {
865: if (ref($spareshash->{'default'}) eq 'ARRAY') {
866: foreach my $try_server (@{ $spareshash->{'default'} }) {
867: if ($uint_dom) {
868: next unless (&spare_can_host($udom,$uint_dom,
869: $remotesessions,$try_server));
870: }
871: ($spare_server, $lowest_load) =
872: &compare_server_load($try_server, $spare_server, $lowest_load);
873: }
874: }
875: }
876: }
877:
878: if (!$want_server_name) {
879: my $protocol = 'http';
880: if ($protocol{$spare_server} eq 'https') {
881: $protocol = $protocol{$spare_server};
882: }
883: if (defined($spare_server)) {
884: my $hostname = &hostname($spare_server);
885: if (defined($hostname)) {
886: $spare_server = $protocol.'://'.$hostname;
887: }
888: }
889: }
890: return $spare_server;
891: }
892:
893: sub compare_server_load {
894: my ($try_server, $spare_server, $lowest_load) = @_;
895:
896: my $loadans = &reply('load', $try_server);
897: my $userloadans = &reply('userload',$try_server);
898:
899: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
900: return ($spare_server, $lowest_load); #didn't get a number from the server
901: }
902:
903: my $load;
904: if ($loadans =~ /\d/) {
905: if ($userloadans =~ /\d/) {
906: #both are numbers, pick the bigger one
907: $load = ($loadans > $userloadans) ? $loadans
908: : $userloadans;
909: } else {
910: $load = $loadans;
911: }
912: } else {
913: $load = $userloadans;
914: }
915:
916: if (($load =~ /\d/) && ($load < $lowest_load)) {
917: $spare_server = $try_server;
918: $lowest_load = $load;
919: }
920: return ($spare_server,$lowest_load);
921: }
922:
923: # --------------------------- ask offload servers if user already has a session
924: sub find_existing_session {
925: my ($udom,$uname) = @_;
926: my $spareshash = &this_host_spares($udom);
927: if (ref($spareshash) eq 'HASH') {
928: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'primary'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
933: if (ref($spareshash->{'default'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'default'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
938: }
939: return;
940: }
941:
942: # -------------------------------- ask if server already has a session for user
943: sub has_user_session {
944: my ($lonid,$udom,$uname) = @_;
945: my $result = &reply(join(':','userhassession',
946: map {&escape($_)} ($udom,$uname)),$lonid);
947: return 1 if ($result eq 'ok');
948:
949: return 0;
950: }
951:
952: # --------- determine least loaded server in a user's domain which allows login
953:
954: sub choose_server {
955: my ($udom,$checkloginvia) = @_;
956: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
957: my %servers = &get_servers($udom);
958: my $lowest_load = 30000;
959: my ($login_host,$hostname,$portal_path,$isredirect);
960: foreach my $lonhost (keys(%servers)) {
961: my $loginvia;
962: if ($checkloginvia) {
963: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
964: if ($loginvia) {
965: my ($server,$path) = split(/:/,$loginvia);
966: ($login_host, $lowest_load) =
967: &compare_server_load($server, $login_host, $lowest_load);
968: if ($login_host eq $server) {
969: $portal_path = $path;
970: $isredirect = 1;
971: }
972: } else {
973: ($login_host, $lowest_load) =
974: &compare_server_load($lonhost, $login_host, $lowest_load);
975: if ($login_host eq $lonhost) {
976: $portal_path = '';
977: $isredirect = '';
978: }
979: }
980: } else {
981: ($login_host, $lowest_load) =
982: &compare_server_load($lonhost, $login_host, $lowest_load);
983: }
984: }
985: if ($login_host ne '') {
986: $hostname = &hostname($login_host);
987: }
988: return ($login_host,$hostname,$portal_path,$isredirect);
989: }
990:
991: # --------------------------------------------- Try to change a user's password
992:
993: sub changepass {
994: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
995: $currentpass = &escape($currentpass);
996: $newpass = &escape($newpass);
997: my $lonhost = $perlvar{'lonHostID'};
998: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
999: $server);
1000: if (! $answer) {
1001: &logthis("No reply on password change request to $server ".
1002: "by $uname in domain $udom.");
1003: } elsif ($answer =~ "^ok") {
1004: &logthis("$uname in $udom successfully changed their password ".
1005: "on $server.");
1006: } elsif ($answer =~ "^pwchange_failure") {
1007: &logthis("$uname in $udom was unable to change their password ".
1008: "on $server. The action was blocked by either lcpasswd ".
1009: "or pwchange");
1010: } elsif ($answer =~ "^non_authorized") {
1011: &logthis("$uname in $udom did not get their password correct when ".
1012: "attempting to change it on $server.");
1013: } elsif ($answer =~ "^auth_mode_error") {
1014: &logthis("$uname in $udom attempted to change their password despite ".
1015: "not being locally or internally authenticated on $server.");
1016: } elsif ($answer =~ "^unknown_user") {
1017: &logthis("$uname in $udom attempted to change their password ".
1018: "on $server but were unable to because $server is not ".
1019: "their home server.");
1020: } elsif ($answer =~ "^refused") {
1021: &logthis("$server refused to change $uname in $udom password because ".
1022: "it was sent an unencrypted request to change the password.");
1023: } elsif ($answer =~ "invalid_client") {
1024: &logthis("$server refused to change $uname in $udom password because ".
1025: "it was a reset by e-mail originating from an invalid server.");
1026: }
1027: return $answer;
1028: }
1029:
1030: # ----------------------- Try to determine user's current authentication scheme
1031:
1032: sub queryauthenticate {
1033: my ($uname,$udom)=@_;
1034: my $uhome=&homeserver($uname,$udom);
1035: if (!$uhome) {
1036: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1037: return 'no_host';
1038: }
1039: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1040: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1041: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1042: }
1043: return $answer;
1044: }
1045:
1046: # --------- Try to authenticate user from domain's lib servers (first this one)
1047:
1048: sub authenticate {
1049: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1050: $upass=&escape($upass);
1051: $uname= &LONCAPA::clean_username($uname);
1052: my $uhome=&homeserver($uname,$udom,1);
1053: my $newhome;
1054: if ((!$uhome) || ($uhome eq 'no_host')) {
1055: # Maybe the machine was offline and only re-appeared again recently?
1056: &reconlonc();
1057: # One more
1058: $uhome=&homeserver($uname,$udom,1);
1059: if (($uhome eq 'no_host') && $checkdefauth) {
1060: if (defined(&domain($udom,'primary'))) {
1061: $newhome=&domain($udom,'primary');
1062: }
1063: if ($newhome ne '') {
1064: $uhome = $newhome;
1065: }
1066: }
1067: if ((!$uhome) || ($uhome eq 'no_host')) {
1068: &logthis("User $uname at $udom is unknown in authenticate");
1069: return 'no_host';
1070: }
1071: }
1072: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1073: if ($answer eq 'authorized') {
1074: if ($newhome) {
1075: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1076: return 'no_account_on_host';
1077: } else {
1078: &logthis("User $uname at $udom authorized by $uhome");
1079: return $uhome;
1080: }
1081: }
1082: if ($answer eq 'non_authorized') {
1083: &logthis("User $uname at $udom rejected by $uhome");
1084: return 'no_host';
1085: }
1086: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1087: return 'no_host';
1088: }
1089:
1090: sub can_host_session {
1091: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1092: my $canhost = 1;
1093: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1094: if (ref($remotesessions) eq 'HASH') {
1095: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1096: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1097: $canhost = 0;
1098: } else {
1099: $canhost = 1;
1100: }
1101: }
1102: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1103: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1104: $canhost = 1;
1105: } else {
1106: $canhost = 0;
1107: }
1108: }
1109: if ($canhost) {
1110: if ($remotesessions->{'version'} ne '') {
1111: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1112: if ($reqmajor ne '' && $reqminor ne '') {
1113: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1114: my $major = $1;
1115: my $minor = $2;
1116: if (($major < $reqmajor ) ||
1117: (($major == $reqmajor) && ($minor < $reqminor))) {
1118: $canhost = 0;
1119: }
1120: } else {
1121: $canhost = 0;
1122: }
1123: }
1124: }
1125: }
1126: }
1127: if ($canhost) {
1128: if (ref($hostedsessions) eq 'HASH') {
1129: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1130: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1131: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1132: if (($uint_dom ne '') &&
1133: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1134: $canhost = 0;
1135: } else {
1136: $canhost = 1;
1137: }
1138: }
1139: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1140: if (($uint_dom ne '') &&
1141: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1142: $canhost = 1;
1143: } else {
1144: $canhost = 0;
1145: }
1146: }
1147: }
1148: }
1149: return $canhost;
1150: }
1151:
1152: sub spare_can_host {
1153: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1154: my $canhost=1;
1155: my @intdoms;
1156: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1157: if (ref($internet_names) eq 'ARRAY') {
1158: @intdoms = @{$internet_names};
1159: }
1160: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1161: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1162: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1163: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1164: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1165: $canhost = &can_host_session($udom,$try_server,$remoterev,
1166: $remotesessions,
1167: $defdomdefaults{'hostedsessions'});
1168: }
1169: return $canhost;
1170: }
1171:
1172: sub this_host_spares {
1173: my ($dom) = @_;
1174: my ($dom_in_use,$lonhost_in_use,$result);
1175: my @hosts = ¤t_machine_ids();
1176: foreach my $lonhost (@hosts) {
1177: if (&host_domain($lonhost) eq $dom) {
1178: $dom_in_use = $dom;
1179: $lonhost_in_use = $lonhost;
1180: last;
1181: }
1182: }
1183: if ($dom_in_use ne '') {
1184: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1185: }
1186: if (ref($result) ne 'HASH') {
1187: $lonhost_in_use = $perlvar{'lonHostID'};
1188: $dom_in_use = &host_domain($lonhost_in_use);
1189: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1190: if (ref($result) ne 'HASH') {
1191: $result = \%spareid;
1192: }
1193: }
1194: return $result;
1195: }
1196:
1197: sub spares_for_offload {
1198: my ($dom_in_use,$lonhost_in_use) = @_;
1199: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1200: if (defined($cached)) {
1201: return $result;
1202: } else {
1203: my $cachetime = 60*60*24;
1204: my %domconfig =
1205: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1206: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1207: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1208: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1209: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1210: }
1211: }
1212: }
1213: }
1214: return;
1215: }
1216:
1217: sub get_lonbalancer_config {
1218: my ($servers) = @_;
1219: my ($currbalancer,$currtargets);
1220: if (ref($servers) eq 'HASH') {
1221: foreach my $server (keys(%{$servers})) {
1222: my %what = (
1223: spareid => 1,
1224: perlvar => 1,
1225: );
1226: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1227: if ($result eq 'ok') {
1228: if (ref($returnhash) eq 'HASH') {
1229: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1230: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1231: $currbalancer = $server;
1232: $currtargets = {};
1233: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1234: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1235: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1236: }
1237: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1238: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1239: }
1240: }
1241: last;
1242: }
1243: }
1244: }
1245: }
1246: }
1247: }
1248: return ($currbalancer,$currtargets);
1249: }
1250:
1251: sub check_loadbalancing {
1252: my ($uname,$udom) = @_;
1253: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1254: $rule_in_effect,$offloadto,$otherserver);
1255: my $lonhost = $perlvar{'lonHostID'};
1256: my @hosts = ¤t_machine_ids();
1257: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1258: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1259: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1260: my $serverhomedom = &host_domain($lonhost);
1261:
1262: my $cachetime = 60*60*24;
1263:
1264: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1265: $dom_in_use = $udom;
1266: $homeintdom = 1;
1267: } else {
1268: $dom_in_use = $serverhomedom;
1269: }
1270: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1271: unless (defined($cached)) {
1272: my %domconfig =
1273: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1274: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1275: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1276: }
1277: }
1278: if (ref($result) eq 'HASH') {
1279: ($is_balancer,$currtargets,$currrules) =
1280: &check_balancer_result($result,@hosts);
1281: if ($is_balancer) {
1282: if (ref($currrules) eq 'HASH') {
1283: if ($homeintdom) {
1284: if ($uname ne '') {
1285: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1286: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1287: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1288: $rule_in_effect = $currrules->{'_LC_author'};
1289: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1290: $rule_in_effect = $currrules->{'_LC_adv'}
1291: }
1292: }
1293: if ($rule_in_effect eq '') {
1294: my %userenv = &userenvironment($udom,$uname,'inststatus');
1295: if ($userenv{'inststatus'} ne '') {
1296: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1297: my ($othertitle,$usertypes,$types) =
1298: &Apache::loncommon::sorted_inst_types($udom);
1299: if (ref($types) eq 'ARRAY') {
1300: foreach my $type (@{$types}) {
1301: if (grep(/^\Q$type\E$/,@statuses)) {
1302: if (exists($currrules->{$type})) {
1303: $rule_in_effect = $currrules->{$type};
1304: }
1305: }
1306: }
1307: }
1308: } else {
1309: if (exists($currrules->{'default'})) {
1310: $rule_in_effect = $currrules->{'default'};
1311: }
1312: }
1313: }
1314: } else {
1315: if (exists($currrules->{'default'})) {
1316: $rule_in_effect = $currrules->{'default'};
1317: }
1318: }
1319: } else {
1320: if ($currrules->{'_LC_external'} ne '') {
1321: $rule_in_effect = $currrules->{'_LC_external'};
1322: }
1323: }
1324: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1325: $uname,$udom);
1326: }
1327: }
1328: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1329: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1330: unless (defined($cached)) {
1331: my %domconfig =
1332: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1333: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1334: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1335: }
1336: }
1337: if (ref($result) eq 'HASH') {
1338: ($is_balancer,$currtargets,$currrules) =
1339: &check_balancer_result($result,@hosts);
1340: if ($is_balancer) {
1341: if (ref($currrules) eq 'HASH') {
1342: if ($currrules->{'_LC_internetdom'} ne '') {
1343: $rule_in_effect = $currrules->{'_LC_internetdom'};
1344: }
1345: }
1346: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1347: $uname,$udom);
1348: }
1349: } else {
1350: if ($perlvar{'lonBalancer'} eq 'yes') {
1351: $is_balancer = 1;
1352: $offloadto = &this_host_spares($dom_in_use);
1353: }
1354: }
1355: } else {
1356: if ($perlvar{'lonBalancer'} eq 'yes') {
1357: $is_balancer = 1;
1358: $offloadto = &this_host_spares($dom_in_use);
1359: }
1360: }
1361: if ($is_balancer) {
1362: my $lowest_load = 30000;
1363: if (ref($offloadto) eq 'HASH') {
1364: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1365: foreach my $try_server (@{$offloadto->{'primary'}}) {
1366: ($otherserver,$lowest_load) =
1367: &compare_server_load($try_server,$otherserver,$lowest_load);
1368: }
1369: }
1370: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1371:
1372: if (!$found_server) {
1373: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1374: foreach my $try_server (@{$offloadto->{'default'}}) {
1375: ($otherserver,$lowest_load) =
1376: &compare_server_load($try_server,$otherserver,$lowest_load);
1377: }
1378: }
1379: }
1380: } elsif (ref($offloadto) eq 'ARRAY') {
1381: if (@{$offloadto} == 1) {
1382: $otherserver = $offloadto->[0];
1383: } elsif (@{$offloadto} > 1) {
1384: foreach my $try_server (@{$offloadto}) {
1385: ($otherserver,$lowest_load) =
1386: &compare_server_load($try_server,$otherserver,$lowest_load);
1387: }
1388: }
1389: }
1390: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1391: $is_balancer = 0;
1392: if ($uname ne '' && $udom ne '') {
1393: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1394:
1395: &appenv({'user.loadbalexempt' => $lonhost,
1396: 'user.loadbalcheck.time' => time});
1397: }
1398: }
1399: }
1400: }
1401: return ($is_balancer,$otherserver);
1402: }
1403:
1404: sub check_balancer_result {
1405: my ($result,@hosts) = @_;
1406: my ($is_balancer,$currtargets,$currrules);
1407: if (ref($result) eq 'HASH') {
1408: if ($result->{'lonhost'} ne '') {
1409: my $currbalancer = $result->{'lonhost'};
1410: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1411: $is_balancer = 1;
1412: $currtargets = $result->{'targets'};
1413: $currrules = $result->{'rules'};
1414: }
1415: } else {
1416: foreach my $key (keys(%{$result})) {
1417: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1418: (ref($result->{$key}) eq 'HASH')) {
1419: $is_balancer = 1;
1420: $currrules = $result->{$key}{'rules'};
1421: $currtargets = $result->{$key}{'targets'};
1422: last;
1423: }
1424: }
1425: }
1426: }
1427: return ($is_balancer,$currtargets,$currrules);
1428: }
1429:
1430: sub get_loadbalancer_targets {
1431: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1432: my $offloadto;
1433: if ($rule_in_effect eq 'none') {
1434: return [$perlvar{'lonHostID'}];
1435: } elsif ($rule_in_effect eq '') {
1436: $offloadto = $currtargets;
1437: } else {
1438: if ($rule_in_effect eq 'homeserver') {
1439: my $homeserver = &homeserver($uname,$udom);
1440: if ($homeserver ne 'no_host') {
1441: $offloadto = [$homeserver];
1442: }
1443: } elsif ($rule_in_effect eq 'externalbalancer') {
1444: my %domconfig =
1445: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1446: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1447: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1448: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1449: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1450: }
1451: }
1452: } else {
1453: my %servers = &internet_dom_servers($udom);
1454: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1455: if (&hostname($remotebalancer) ne '') {
1456: $offloadto = [$remotebalancer];
1457: }
1458: }
1459: } elsif (&hostname($rule_in_effect) ne '') {
1460: $offloadto = [$rule_in_effect];
1461: }
1462: }
1463: return $offloadto;
1464: }
1465:
1466: sub internet_dom_servers {
1467: my ($dom) = @_;
1468: my (%uniqservers,%servers);
1469: my $primaryserver = &hostname(&domain($dom,'primary'));
1470: my @machinedoms = &machine_domains($primaryserver);
1471: foreach my $mdom (@machinedoms) {
1472: my %currservers = %servers;
1473: my %server = &get_servers($mdom);
1474: %servers = (%currservers,%server);
1475: }
1476: my %by_hostname;
1477: foreach my $id (keys(%servers)) {
1478: push(@{$by_hostname{$servers{$id}}},$id);
1479: }
1480: foreach my $hostname (sort(keys(%by_hostname))) {
1481: if (@{$by_hostname{$hostname}} > 1) {
1482: my $match = 0;
1483: foreach my $id (@{$by_hostname{$hostname}}) {
1484: if (&host_domain($id) eq $dom) {
1485: $uniqservers{$id} = $hostname;
1486: $match = 1;
1487: }
1488: }
1489: unless ($match) {
1490: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1491: }
1492: } else {
1493: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1494: }
1495: }
1496: return %uniqservers;
1497: }
1498:
1499: # ---------------------- Find the homebase for a user from domain's lib servers
1500:
1501: my %homecache;
1502: sub homeserver {
1503: my ($uname,$udom,$ignoreBadCache)=@_;
1504: my $index="$uname:$udom";
1505:
1506: if (exists($homecache{$index})) { return $homecache{$index}; }
1507:
1508: my %servers = &get_servers($udom,'library');
1509: foreach my $tryserver (keys(%servers)) {
1510: next if ($ignoreBadCache ne 'true' &&
1511: exists($badServerCache{$tryserver}));
1512:
1513: my $answer=reply("home:$udom:$uname",$tryserver);
1514: if ($answer eq 'found') {
1515: delete($badServerCache{$tryserver});
1516: return $homecache{$index}=$tryserver;
1517: } elsif ($answer eq 'no_host') {
1518: $badServerCache{$tryserver}=1;
1519: }
1520: }
1521: return 'no_host';
1522: }
1523:
1524: # ------------------------------------- Find the usernames behind a list of IDs
1525:
1526: sub idget {
1527: my ($udom,@ids)=@_;
1528: my %returnhash=();
1529:
1530: my %servers = &get_servers($udom,'library');
1531: foreach my $tryserver (keys(%servers)) {
1532: my $idlist=join('&',@ids);
1533: $idlist=~tr/A-Z/a-z/;
1534: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1535: my @answer=();
1536: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1537: @answer=split(/\&/,$reply);
1538: } ;
1539: my $i;
1540: for ($i=0;$i<=$#ids;$i++) {
1541: if ($answer[$i]) {
1542: $returnhash{$ids[$i]}=$answer[$i];
1543: }
1544: }
1545: }
1546: return %returnhash;
1547: }
1548:
1549: # ------------------------------------- Find the IDs behind a list of usernames
1550:
1551: sub idrget {
1552: my ($udom,@unames)=@_;
1553: my %returnhash=();
1554: foreach my $uname (@unames) {
1555: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1556: }
1557: return %returnhash;
1558: }
1559:
1560: # ------------------------------- Store away a list of names and associated IDs
1561:
1562: sub idput {
1563: my ($udom,%ids)=@_;
1564: my %servers=();
1565: foreach my $uname (keys(%ids)) {
1566: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1567: my $uhom=&homeserver($uname,$udom);
1568: if ($uhom ne 'no_host') {
1569: my $id=&escape($ids{$uname});
1570: $id=~tr/A-Z/a-z/;
1571: my $esc_unam=&escape($uname);
1572: if ($servers{$uhom}) {
1573: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1574: } else {
1575: $servers{$uhom}=$id.'='.$esc_unam;
1576: }
1577: }
1578: }
1579: foreach my $server (keys(%servers)) {
1580: &critical('idput:'.$udom.':'.$servers{$server},$server);
1581: }
1582: }
1583:
1584: # ---------------------------------------- Delete unwanted IDs from ids.db file
1585:
1586: sub iddel {
1587: my ($udom,$idshashref,$uhome)=@_;
1588: my %result=();
1589: unless (ref($idshashref) eq 'HASH') {
1590: return %result;
1591: }
1592: my %servers=();
1593: while (my ($id,$uname) = each(%{$idshashref})) {
1594: my $uhom;
1595: if ($uhome) {
1596: $uhom = $uhome;
1597: } else {
1598: $uhom=&homeserver($uname,$udom);
1599: }
1600: if ($uhom ne 'no_host') {
1601: if ($servers{$uhom}) {
1602: $servers{$uhom}.='&'.&escape($id);
1603: } else {
1604: $servers{$uhom}=&escape($id);
1605: }
1606: }
1607: }
1608: foreach my $server (keys(%servers)) {
1609: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1610: }
1611: return %result;
1612: }
1613:
1614: # ------------------------------dump from db file owned by domainconfig user
1615: sub dump_dom {
1616: my ($namespace, $udom, $regexp) = @_;
1617:
1618: $udom ||= $env{'user.domain'};
1619:
1620: return () unless $udom;
1621:
1622: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1623: }
1624:
1625: # ------------------------------------------ get items from domain db files
1626:
1627: sub get_dom {
1628: my ($namespace,$storearr,$udom,$uhome)=@_;
1629: my $items='';
1630: foreach my $item (@$storearr) {
1631: $items.=&escape($item).'&';
1632: }
1633: $items=~s/\&$//;
1634: if (!$udom) {
1635: $udom=$env{'user.domain'};
1636: if (defined(&domain($udom,'primary'))) {
1637: $uhome=&domain($udom,'primary');
1638: } else {
1639: undef($uhome);
1640: }
1641: } else {
1642: if (!$uhome) {
1643: if (defined(&domain($udom,'primary'))) {
1644: $uhome=&domain($udom,'primary');
1645: }
1646: }
1647: }
1648: if ($udom && $uhome && ($uhome ne 'no_host')) {
1649: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1650: my %returnhash;
1651: if ($rep eq '' || $rep =~ /^error: 2 /) {
1652: return %returnhash;
1653: }
1654: my @pairs=split(/\&/,$rep);
1655: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1656: return @pairs;
1657: }
1658: my $i=0;
1659: foreach my $item (@$storearr) {
1660: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1661: $i++;
1662: }
1663: return %returnhash;
1664: } else {
1665: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1666: }
1667: }
1668:
1669: # -------------------------------------------- put items in domain db files
1670:
1671: sub put_dom {
1672: my ($namespace,$storehash,$udom,$uhome)=@_;
1673: if (!$udom) {
1674: $udom=$env{'user.domain'};
1675: if (defined(&domain($udom,'primary'))) {
1676: $uhome=&domain($udom,'primary');
1677: } else {
1678: undef($uhome);
1679: }
1680: } else {
1681: if (!$uhome) {
1682: if (defined(&domain($udom,'primary'))) {
1683: $uhome=&domain($udom,'primary');
1684: }
1685: }
1686: }
1687: if ($udom && $uhome && ($uhome ne 'no_host')) {
1688: my $items='';
1689: foreach my $item (keys(%$storehash)) {
1690: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1691: }
1692: $items=~s/\&$//;
1693: return &reply("putdom:$udom:$namespace:$items",$uhome);
1694: } else {
1695: &logthis("put_dom failed - no homeserver and/or domain");
1696: }
1697: }
1698:
1699: # --------------------- newput for items in db file owned by domainconfig user
1700: sub newput_dom {
1701: my ($namespace,$storehash,$udom) = @_;
1702: my $result;
1703: if (!$udom) {
1704: $udom=$env{'user.domain'};
1705: }
1706: if ($udom) {
1707: my $uname = &get_domainconfiguser($udom);
1708: $result = &newput($namespace,$storehash,$udom,$uname);
1709: }
1710: return $result;
1711: }
1712:
1713: # --------------------- delete for items in db file owned by domainconfig user
1714: sub del_dom {
1715: my ($namespace,$storearr,$udom)=@_;
1716: if (ref($storearr) eq 'ARRAY') {
1717: if (!$udom) {
1718: $udom=$env{'user.domain'};
1719: }
1720: if ($udom) {
1721: my $uname = &get_domainconfiguser($udom);
1722: return &del($namespace,$storearr,$udom,$uname);
1723: }
1724: }
1725: }
1726:
1727: # ----------------------------------construct domainconfig user for a domain
1728: sub get_domainconfiguser {
1729: my ($udom) = @_;
1730: return $udom.'-domainconfig';
1731: }
1732:
1733: sub retrieve_inst_usertypes {
1734: my ($udom) = @_;
1735: my (%returnhash,@order);
1736: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1737: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1738: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1739: %returnhash = %{$domdefs{'inststatustypes'}};
1740: @order = @{$domdefs{'inststatusorder'}};
1741: } else {
1742: if (defined(&domain($udom,'primary'))) {
1743: my $uhome=&domain($udom,'primary');
1744: my $rep=&reply("inst_usertypes:$udom",$uhome);
1745: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1746: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1747: return (\%returnhash,\@order);
1748: }
1749: my ($hashitems,$orderitems) = split(/:/,$rep);
1750: my @pairs=split(/\&/,$hashitems);
1751: foreach my $item (@pairs) {
1752: my ($key,$value)=split(/=/,$item,2);
1753: $key = &unescape($key);
1754: next if ($key =~ /^error: 2 /);
1755: $returnhash{$key}=&thaw_unescape($value);
1756: }
1757: my @esc_order = split(/\&/,$orderitems);
1758: foreach my $item (@esc_order) {
1759: push(@order,&unescape($item));
1760: }
1761: } else {
1762: &logthis("get_dom failed - no primary domain server for $udom");
1763: }
1764: }
1765: return (\%returnhash,\@order);
1766: }
1767:
1768: sub is_domainimage {
1769: my ($url) = @_;
1770: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1771: if (&domain($1) ne '') {
1772: return '1';
1773: }
1774: }
1775: return;
1776: }
1777:
1778: sub inst_directory_query {
1779: my ($srch) = @_;
1780: my $udom = $srch->{'srchdomain'};
1781: my %results;
1782: my $homeserver = &domain($udom,'primary');
1783: my $outcome;
1784: if ($homeserver ne '') {
1785: my $queryid=&reply("querysend:instdirsearch:".
1786: &escape($srch->{'srchby'}).':'.
1787: &escape($srch->{'srchterm'}).':'.
1788: &escape($srch->{'srchtype'}),$homeserver);
1789: my $host=&hostname($homeserver);
1790: if ($queryid !~/^\Q$host\E\_/) {
1791: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1792: return;
1793: }
1794: my $response = &get_query_reply($queryid);
1795: my $maxtries = 5;
1796: my $tries = 1;
1797: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1798: $response = &get_query_reply($queryid);
1799: $tries ++;
1800: }
1801:
1802: if (!&error($response) && $response ne 'refused') {
1803: if ($response eq 'unavailable') {
1804: $outcome = $response;
1805: } else {
1806: $outcome = 'ok';
1807: my @matches = split(/\n/,$response);
1808: foreach my $match (@matches) {
1809: my ($key,$value) = split(/=/,$match);
1810: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1811: }
1812: }
1813: }
1814: }
1815: return ($outcome,%results);
1816: }
1817:
1818: sub usersearch {
1819: my ($srch) = @_;
1820: my $dom = $srch->{'srchdomain'};
1821: my %results;
1822: my %libserv = &all_library();
1823: my $query = 'usersearch';
1824: foreach my $tryserver (keys(%libserv)) {
1825: if (&host_domain($tryserver) eq $dom) {
1826: my $host=&hostname($tryserver);
1827: my $queryid=
1828: &reply("querysend:".&escape($query).':'.
1829: &escape($srch->{'srchby'}).':'.
1830: &escape($srch->{'srchtype'}).':'.
1831: &escape($srch->{'srchterm'}),$tryserver);
1832: if ($queryid !~/^\Q$host\E\_/) {
1833: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1834: next;
1835: }
1836: my $reply = &get_query_reply($queryid);
1837: my $maxtries = 1;
1838: my $tries = 1;
1839: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1840: $reply = &get_query_reply($queryid);
1841: $tries ++;
1842: }
1843: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1844: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1845: } else {
1846: my @matches;
1847: if ($reply =~ /\n/) {
1848: @matches = split(/\n/,$reply);
1849: } else {
1850: @matches = split(/\&/,$reply);
1851: }
1852: foreach my $match (@matches) {
1853: my ($uname,$udom,%userhash);
1854: foreach my $entry (split(/:/,$match)) {
1855: my ($key,$value) =
1856: map {&unescape($_);} split(/=/,$entry);
1857: $userhash{$key} = $value;
1858: if ($key eq 'username') {
1859: $uname = $value;
1860: } elsif ($key eq 'domain') {
1861: $udom = $value;
1862: }
1863: }
1864: $results{$uname.':'.$udom} = \%userhash;
1865: }
1866: }
1867: }
1868: }
1869: return %results;
1870: }
1871:
1872: sub get_instuser {
1873: my ($udom,$uname,$id) = @_;
1874: my $homeserver = &domain($udom,'primary');
1875: my ($outcome,%results);
1876: if ($homeserver ne '') {
1877: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1878: &escape($id).':'.&escape($udom),$homeserver);
1879: my $host=&hostname($homeserver);
1880: if ($queryid !~/^\Q$host\E\_/) {
1881: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1882: return;
1883: }
1884: my $response = &get_query_reply($queryid);
1885: my $maxtries = 5;
1886: my $tries = 1;
1887: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1888: $response = &get_query_reply($queryid);
1889: $tries ++;
1890: }
1891: if (!&error($response) && $response ne 'refused') {
1892: if ($response eq 'unavailable') {
1893: $outcome = $response;
1894: } else {
1895: $outcome = 'ok';
1896: my @matches = split(/\n/,$response);
1897: foreach my $match (@matches) {
1898: my ($key,$value) = split(/=/,$match);
1899: $results{&unescape($key)} = &thaw_unescape($value);
1900: }
1901: }
1902: }
1903: }
1904: my %userinfo;
1905: if (ref($results{$uname}) eq 'HASH') {
1906: %userinfo = %{$results{$uname}};
1907: }
1908: return ($outcome,%userinfo);
1909: }
1910:
1911: sub inst_rulecheck {
1912: my ($udom,$uname,$id,$item,$rules) = @_;
1913: my %returnhash;
1914: if ($udom ne '') {
1915: if (ref($rules) eq 'ARRAY') {
1916: @{$rules} = map {&escape($_);} (@{$rules});
1917: my $rulestr = join(':',@{$rules});
1918: my $homeserver=&domain($udom,'primary');
1919: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1920: my $response;
1921: if ($item eq 'username') {
1922: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1923: ':'.&escape($uname).':'.$rulestr,
1924: $homeserver));
1925: } elsif ($item eq 'id') {
1926: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1927: ':'.&escape($id).':'.$rulestr,
1928: $homeserver));
1929: } elsif ($item eq 'selfcreate') {
1930: $response=&unescape(&reply('instselfcreatecheck:'.
1931: &escape($udom).':'.&escape($uname).
1932: ':'.$rulestr,$homeserver));
1933: }
1934: if ($response ne 'refused') {
1935: my @pairs=split(/\&/,$response);
1936: foreach my $item (@pairs) {
1937: my ($key,$value)=split(/=/,$item,2);
1938: $key = &unescape($key);
1939: next if ($key =~ /^error: 2 /);
1940: $returnhash{$key}=&thaw_unescape($value);
1941: }
1942: }
1943: }
1944: }
1945: }
1946: return %returnhash;
1947: }
1948:
1949: sub inst_userrules {
1950: my ($udom,$check) = @_;
1951: my (%ruleshash,@ruleorder);
1952: if ($udom ne '') {
1953: my $homeserver=&domain($udom,'primary');
1954: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1955: my $response;
1956: if ($check eq 'id') {
1957: $response=&reply('instidrules:'.&escape($udom),
1958: $homeserver);
1959: } elsif ($check eq 'email') {
1960: $response=&reply('instemailrules:'.&escape($udom),
1961: $homeserver);
1962: } else {
1963: $response=&reply('instuserrules:'.&escape($udom),
1964: $homeserver);
1965: }
1966: if (($response ne 'refused') && ($response ne 'error') &&
1967: ($response ne 'unknown_cmd') &&
1968: ($response ne 'no_such_host')) {
1969: my ($hashitems,$orderitems) = split(/:/,$response);
1970: my @pairs=split(/\&/,$hashitems);
1971: foreach my $item (@pairs) {
1972: my ($key,$value)=split(/=/,$item,2);
1973: $key = &unescape($key);
1974: next if ($key =~ /^error: 2 /);
1975: $ruleshash{$key}=&thaw_unescape($value);
1976: }
1977: my @esc_order = split(/\&/,$orderitems);
1978: foreach my $item (@esc_order) {
1979: push(@ruleorder,&unescape($item));
1980: }
1981: }
1982: }
1983: }
1984: return (\%ruleshash,\@ruleorder);
1985: }
1986:
1987: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1988:
1989: sub get_domain_defaults {
1990: my ($domain,$ignore_cache) = @_;
1991: my $cachetime = 60*60*24;
1992: unless ($ignore_cache) {
1993: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1994: if (defined($cached)) {
1995: if (ref($result) eq 'HASH') {
1996: return %{$result};
1997: }
1998: }
1999: }
2000: my %domdefaults;
2001: my %domconfig =
2002: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2003: 'requestcourses','inststatus',
2004: 'coursedefaults','usersessions',
2005: 'requestauthor'],$domain);
2006: if (ref($domconfig{'defaults'}) eq 'HASH') {
2007: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2008: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2009: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2010: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2011: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2012: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2013: } else {
2014: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2015: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2016: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2017: }
2018: if (ref($domconfig{'quotas'}) eq 'HASH') {
2019: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2020: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2021: } else {
2022: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2023: }
2024: my @usertools = ('aboutme','blog','webdav','portfolio');
2025: foreach my $item (@usertools) {
2026: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2027: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2028: }
2029: }
2030: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2031: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2032: }
2033: }
2034: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2035: foreach my $item ('official','unofficial','community') {
2036: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2037: }
2038: }
2039: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2040: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2041: }
2042: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2043: foreach my $item ('inststatustypes','inststatusorder') {
2044: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2045: }
2046: }
2047: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2048: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2049: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2050: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2051: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
2052: }
2053: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2054: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2055: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
2056: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
2057: }
2058: }
2059: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2060: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2061: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2062: }
2063: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2064: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2065: }
2066: }
2067: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2068: return %domdefaults;
2069: }
2070:
2071: # --------------------------------------------------- Assign a key to a student
2072:
2073: sub assign_access_key {
2074: #
2075: # a valid key looks like uname:udom#comments
2076: # comments are being appended
2077: #
2078: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2079: $kdom=
2080: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2081: $knum=
2082: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2083: $cdom=
2084: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2085: $cnum=
2086: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2087: $udom=$env{'user.name'} unless (defined($udom));
2088: $uname=$env{'user.domain'} unless (defined($uname));
2089: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2090: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2091: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2092: # assigned to this person
2093: # - this should not happen,
2094: # unless something went wrong
2095: # the first time around
2096: # ready to assign
2097: $logentry=$1.'; '.$logentry;
2098: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2099: $kdom,$knum) eq 'ok') {
2100: # key now belongs to user
2101: my $envkey='key.'.$cdom.'_'.$cnum;
2102: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2103: &appenv({'environment.'.$envkey => $ckey});
2104: return 'ok';
2105: } else {
2106: return
2107: 'error: Count not permanently assign key, will need to be re-entered later.';
2108: }
2109: } else {
2110: return 'error: Could not assign key, try again later.';
2111: }
2112: } elsif (!$existing{$ckey}) {
2113: # the key does not exist
2114: return 'error: The key does not exist';
2115: } else {
2116: # the key is somebody else's
2117: return 'error: The key is already in use';
2118: }
2119: }
2120:
2121: # ------------------------------------------ put an additional comment on a key
2122:
2123: sub comment_access_key {
2124: #
2125: # a valid key looks like uname:udom#comments
2126: # comments are being appended
2127: #
2128: my ($ckey,$cdom,$cnum,$logentry)=@_;
2129: $cdom=
2130: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2131: $cnum=
2132: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2133: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2134: if ($existing{$ckey}) {
2135: $existing{$ckey}.='; '.$logentry;
2136: # ready to assign
2137: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2138: $cdom,$cnum) eq 'ok') {
2139: return 'ok';
2140: } else {
2141: return 'error: Count not store comment.';
2142: }
2143: } else {
2144: # the key does not exist
2145: return 'error: The key does not exist';
2146: }
2147: }
2148:
2149: # ------------------------------------------------------ Generate a set of keys
2150:
2151: sub generate_access_keys {
2152: my ($number,$cdom,$cnum,$logentry)=@_;
2153: $cdom=
2154: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2155: $cnum=
2156: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2157: unless (&allowed('mky',$cdom)) { return 0; }
2158: unless (($cdom) && ($cnum)) { return 0; }
2159: if ($number>10000) { return 0; }
2160: sleep(2); # make sure don't get same seed twice
2161: srand(time()^($$+($$<<15))); # from "Programming Perl"
2162: my $total=0;
2163: for (my $i=1;$i<=$number;$i++) {
2164: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2165: sprintf("%lx",int(100000*rand)).'-'.
2166: sprintf("%lx",int(100000*rand));
2167: $newkey=~s/1/g/g; # folks mix up 1 and l
2168: $newkey=~s/0/h/g; # and also 0 and O
2169: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2170: if ($existing{$newkey}) {
2171: $i--;
2172: } else {
2173: if (&put('accesskeys',
2174: { $newkey => '# generated '.localtime().
2175: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2176: '; '.$logentry },
2177: $cdom,$cnum) eq 'ok') {
2178: $total++;
2179: }
2180: }
2181: }
2182: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2183: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2184: return $total;
2185: }
2186:
2187: # ------------------------------------------------------- Validate an accesskey
2188:
2189: sub validate_access_key {
2190: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2191: $cdom=
2192: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2193: $cnum=
2194: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2195: $udom=$env{'user.domain'} unless (defined($udom));
2196: $uname=$env{'user.name'} unless (defined($uname));
2197: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2198: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2199: }
2200:
2201: # ------------------------------------- Find the section of student in a course
2202: sub devalidate_getsection_cache {
2203: my ($udom,$unam,$courseid)=@_;
2204: my $hashid="$udom:$unam:$courseid";
2205: &devalidate_cache_new('getsection',$hashid);
2206: }
2207:
2208: sub courseid_to_courseurl {
2209: my ($courseid) = @_;
2210: #already url style courseid
2211: return $courseid if ($courseid =~ m{^/});
2212:
2213: if (exists($env{'course.'.$courseid.'.num'})) {
2214: my $cnum = $env{'course.'.$courseid.'.num'};
2215: my $cdom = $env{'course.'.$courseid.'.domain'};
2216: return "/$cdom/$cnum";
2217: }
2218:
2219: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2220: if (exists($courseinfo{'num'})) {
2221: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2222: }
2223:
2224: return undef;
2225: }
2226:
2227: sub getsection {
2228: my ($udom,$unam,$courseid)=@_;
2229: my $cachetime=1800;
2230:
2231: my $hashid="$udom:$unam:$courseid";
2232: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2233: if (defined($cached)) { return $result; }
2234:
2235: my %Pending;
2236: my %Expired;
2237: #
2238: # Each role can either have not started yet (pending), be active,
2239: # or have expired.
2240: #
2241: # If there is an active role, we are done.
2242: #
2243: # If there is more than one role which has not started yet,
2244: # choose the one which will start sooner
2245: # If there is one role which has not started yet, return it.
2246: #
2247: # If there is more than one expired role, choose the one which ended last.
2248: # If there is a role which has expired, return it.
2249: #
2250: $courseid = &courseid_to_courseurl($courseid);
2251: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2252: foreach my $key (keys(%roleshash)) {
2253: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2254: my $section=$1;
2255: if ($key eq $courseid.'_st') { $section=''; }
2256: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2257: my $now=time;
2258: if (defined($end) && $end && ($now > $end)) {
2259: $Expired{$end}=$section;
2260: next;
2261: }
2262: if (defined($start) && $start && ($now < $start)) {
2263: $Pending{$start}=$section;
2264: next;
2265: }
2266: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2267: }
2268: #
2269: # Presumedly there will be few matching roles from the above
2270: # loop and the sorting time will be negligible.
2271: if (scalar(keys(%Pending))) {
2272: my ($time) = sort {$a <=> $b} keys(%Pending);
2273: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2274: }
2275: if (scalar(keys(%Expired))) {
2276: my @sorted = sort {$a <=> $b} keys(%Expired);
2277: my $time = pop(@sorted);
2278: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2279: }
2280: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2281: }
2282:
2283: sub save_cache {
2284: &purge_remembered();
2285: #&Apache::loncommon::validate_page();
2286: undef(%env);
2287: undef($env_loaded);
2288: }
2289:
2290: my $to_remember=-1;
2291: my %remembered;
2292: my %accessed;
2293: my $kicks=0;
2294: my $hits=0;
2295: sub make_key {
2296: my ($name,$id) = @_;
2297: if (length($id) > 65
2298: && length(&escape($id)) > 200) {
2299: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2300: }
2301: return &escape($name.':'.$id);
2302: }
2303:
2304: sub devalidate_cache_new {
2305: my ($name,$id,$debug) = @_;
2306: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2307: $id=&make_key($name,$id);
2308: $memcache->delete($id);
2309: delete($remembered{$id});
2310: delete($accessed{$id});
2311: }
2312:
2313: sub is_cached_new {
2314: my ($name,$id,$debug) = @_;
2315: $id=&make_key($name,$id);
2316: if (exists($remembered{$id})) {
2317: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2318: $accessed{$id}=[&gettimeofday()];
2319: $hits++;
2320: return ($remembered{$id},1);
2321: }
2322: my $value = $memcache->get($id);
2323: if (!(defined($value))) {
2324: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2325: return (undef,undef);
2326: }
2327: if ($value eq '__undef__') {
2328: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2329: $value=undef;
2330: }
2331: &make_room($id,$value,$debug);
2332: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2333: return ($value,1);
2334: }
2335:
2336: sub do_cache_new {
2337: my ($name,$id,$value,$time,$debug) = @_;
2338: $id=&make_key($name,$id);
2339: my $setvalue=$value;
2340: if (!defined($setvalue)) {
2341: $setvalue='__undef__';
2342: }
2343: if (!defined($time) ) {
2344: $time=600;
2345: }
2346: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2347: my $result = $memcache->set($id,$setvalue,$time);
2348: if (! $result) {
2349: &logthis("caching of id -> $id failed");
2350: $memcache->disconnect_all();
2351: }
2352: # need to make a copy of $value
2353: &make_room($id,$value,$debug);
2354: return $value;
2355: }
2356:
2357: sub make_room {
2358: my ($id,$value,$debug)=@_;
2359:
2360: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2361: : $value;
2362: if ($to_remember<0) { return; }
2363: $accessed{$id}=[&gettimeofday()];
2364: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2365: my $to_kick;
2366: my $max_time=0;
2367: foreach my $other (keys(%accessed)) {
2368: if (&tv_interval($accessed{$other}) > $max_time) {
2369: $to_kick=$other;
2370: $max_time=&tv_interval($accessed{$other});
2371: }
2372: }
2373: delete($remembered{$to_kick});
2374: delete($accessed{$to_kick});
2375: $kicks++;
2376: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2377: return;
2378: }
2379:
2380: sub purge_remembered {
2381: #&logthis("Tossing ".scalar(keys(%remembered)));
2382: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2383: undef(%remembered);
2384: undef(%accessed);
2385: }
2386: # ------------------------------------- Read an entry from a user's environment
2387:
2388: sub userenvironment {
2389: my ($udom,$unam,@what)=@_;
2390: my $items;
2391: foreach my $item (@what) {
2392: $items.=&escape($item).'&';
2393: }
2394: $items=~s/\&$//;
2395: my %returnhash=();
2396: my $uhome = &homeserver($unam,$udom);
2397: unless ($uhome eq 'no_host') {
2398: my @answer=split(/\&/,
2399: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2400: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2401: return %returnhash;
2402: }
2403: my $i;
2404: for ($i=0;$i<=$#what;$i++) {
2405: $returnhash{$what[$i]}=&unescape($answer[$i]);
2406: }
2407: }
2408: return %returnhash;
2409: }
2410:
2411: # ---------------------------------------------------------- Get a studentphoto
2412: sub studentphoto {
2413: my ($udom,$unam,$ext) = @_;
2414: my $home=&Apache::lonnet::homeserver($unam,$udom);
2415: if (defined($env{'request.course.id'})) {
2416: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2417: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2418: return(&retrievestudentphoto($udom,$unam,$ext));
2419: } else {
2420: my ($result,$perm_reqd)=
2421: &Apache::lonnet::auto_photo_permission($unam,$udom);
2422: if ($result eq 'ok') {
2423: if (!($perm_reqd eq 'yes')) {
2424: return(&retrievestudentphoto($udom,$unam,$ext));
2425: }
2426: }
2427: }
2428: }
2429: } else {
2430: my ($result,$perm_reqd) =
2431: &Apache::lonnet::auto_photo_permission($unam,$udom);
2432: if ($result eq 'ok') {
2433: if (!($perm_reqd eq 'yes')) {
2434: return(&retrievestudentphoto($udom,$unam,$ext));
2435: }
2436: }
2437: }
2438: return '/adm/lonKaputt/lonlogo_broken.gif';
2439: }
2440:
2441: sub retrievestudentphoto {
2442: my ($udom,$unam,$ext,$type) = @_;
2443: my $home=&Apache::lonnet::homeserver($unam,$udom);
2444: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2445: if ($ret eq 'ok') {
2446: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2447: if ($type eq 'thumbnail') {
2448: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2449: }
2450: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2451: return $tokenurl;
2452: } else {
2453: if ($type eq 'thumbnail') {
2454: return '/adm/lonKaputt/genericstudent_tn.gif';
2455: } else {
2456: return '/adm/lonKaputt/lonlogo_broken.gif';
2457: }
2458: }
2459: }
2460:
2461: # -------------------------------------------------------------------- New chat
2462:
2463: sub chatsend {
2464: my ($newentry,$anon,$group)=@_;
2465: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2466: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2467: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2468: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2469: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2470: &escape($newentry)).':'.$group,$chome);
2471: }
2472:
2473: # ------------------------------------------ Find current version of a resource
2474:
2475: sub getversion {
2476: my $fname=&clutter(shift);
2477: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2478: return ¤tversion(&filelocation('',$fname));
2479: }
2480:
2481: sub currentversion {
2482: my $fname=shift;
2483: my $author=$fname;
2484: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2485: my ($udom,$uname)=split(/\//,$author);
2486: my $home=&homeserver($uname,$udom);
2487: if ($home eq 'no_host') {
2488: return -1;
2489: }
2490: my $answer=&reply("currentversion:$fname",$home);
2491: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2492: return -1;
2493: }
2494: return $answer;
2495: }
2496:
2497: #
2498: # Return special version number of resource if set by override, empty otherwise
2499: #
2500: sub usedversion {
2501: my $fname=shift;
2502: unless ($fname) { $fname=$env{'request.uri'}; }
2503: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2504: if ($urlversion) { return $urlversion; }
2505: return '';
2506: }
2507:
2508: # ----------------------------- Subscribe to a resource, return URL if possible
2509:
2510: sub subscribe {
2511: my $fname=shift;
2512: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2513: $fname=~s/[\n\r]//g;
2514: my $author=$fname;
2515: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2516: my ($udom,$uname)=split(/\//,$author);
2517: my $home=homeserver($uname,$udom);
2518: if ($home eq 'no_host') {
2519: return 'not_found';
2520: }
2521: my $answer=reply("sub:$fname",$home);
2522: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2523: $answer.=' by '.$home;
2524: }
2525: return $answer;
2526: }
2527:
2528: # -------------------------------------------------------------- Replicate file
2529:
2530: sub repcopy {
2531: my $filename=shift;
2532: $filename=~s/\/+/\//g;
2533: my $londocroot = $perlvar{'lonDocRoot'};
2534: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2535: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
2536: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2537: $filename=~m{^/*(uploaded|editupload)/}) {
2538: return &repcopy_userfile($filename);
2539: }
2540: $filename=~s/[\n\r]//g;
2541: my $transname="$filename.in.transfer";
2542: # FIXME: this should flock
2543: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2544: my $remoteurl=subscribe($filename);
2545: if ($remoteurl =~ /^con_lost by/) {
2546: &logthis("Subscribe returned $remoteurl: $filename");
2547: return 'unavailable';
2548: } elsif ($remoteurl eq 'not_found') {
2549: #&logthis("Subscribe returned not_found: $filename");
2550: return 'not_found';
2551: } elsif ($remoteurl =~ /^rejected by/) {
2552: &logthis("Subscribe returned $remoteurl: $filename");
2553: return 'forbidden';
2554: } elsif ($remoteurl eq 'directory') {
2555: return 'ok';
2556: } else {
2557: my $author=$filename;
2558: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2559: my ($udom,$uname)=split(/\//,$author);
2560: my $home=homeserver($uname,$udom);
2561: unless ($home eq $perlvar{'lonHostID'}) {
2562: my @parts=split(/\//,$filename);
2563: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2564: if ($path ne "$londocroot/res") {
2565: &logthis("Malconfiguration for replication: $filename");
2566: return 'bad_request';
2567: }
2568: my $count;
2569: for ($count=5;$count<$#parts;$count++) {
2570: $path.="/$parts[$count]";
2571: if ((-e $path)!=1) {
2572: mkdir($path,0777);
2573: }
2574: }
2575: my $ua=new LWP::UserAgent;
2576: my $request=new HTTP::Request('GET',"$remoteurl");
2577: my $response=$ua->request($request,$transname);
2578: if ($response->is_error()) {
2579: unlink($transname);
2580: my $message=$response->status_line;
2581: &logthis("<font color=\"blue\">WARNING:"
2582: ." LWP get: $message: $filename</font>");
2583: return 'unavailable';
2584: } else {
2585: if ($remoteurl!~/\.meta$/) {
2586: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2587: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2588: if ($mresponse->is_error()) {
2589: unlink($filename.'.meta');
2590: &logthis(
2591: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2592: }
2593: }
2594: rename($transname,$filename);
2595: return 'ok';
2596: }
2597: }
2598: }
2599: }
2600:
2601: # ------------------------------------------------ Get server side include body
2602: sub ssi_body {
2603: my ($filelink,%form)=@_;
2604: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2605: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2606: }
2607: my $output='';
2608: my $response;
2609: if ($filelink=~/^https?\:/) {
2610: ($output,$response)=&externalssi($filelink);
2611: } else {
2612: $filelink .= $filelink=~/\?/ ? '&' : '?';
2613: $filelink .= 'inhibitmenu=yes';
2614: ($output,$response)=&ssi($filelink,%form);
2615: }
2616: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2617: $output=~s/^.*?\<body[^\>]*\>//si;
2618: $output=~s/\<\/body\s*\>.*?$//si;
2619: if (wantarray) {
2620: return ($output, $response);
2621: } else {
2622: return $output;
2623: }
2624: }
2625:
2626: # --------------------------------------------------------- Server Side Include
2627:
2628: sub absolute_url {
2629: my ($host_name) = @_;
2630: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2631: if ($host_name eq '') {
2632: $host_name = $ENV{'SERVER_NAME'};
2633: }
2634: return $protocol.$host_name;
2635: }
2636:
2637: #
2638: # Server side include.
2639: # Parameters:
2640: # fn Possibly encrypted resource name/id.
2641: # form Hash that describes how the rendering should be done
2642: # and other things.
2643: # Returns:
2644: # Scalar context: The content of the response.
2645: # Array context: 2 element list of the content and the full response object.
2646: #
2647: sub ssi {
2648:
2649: my ($fn,%form)=@_;
2650: my $ua=new LWP::UserAgent;
2651: my $request;
2652:
2653: $form{'no_update_last_known'}=1;
2654: &Apache::lonenc::check_encrypt(\$fn);
2655: if (%form) {
2656: $request=new HTTP::Request('POST',&absolute_url().$fn);
2657: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2658: } else {
2659: $request=new HTTP::Request('GET',&absolute_url().$fn);
2660: }
2661:
2662: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2663: my $response= $ua->request($request);
2664: my $content = $response->content;
2665:
2666:
2667: if (wantarray) {
2668: return ($content, $response);
2669: } else {
2670: return $content;
2671: }
2672: }
2673:
2674: sub externalssi {
2675: my ($url)=@_;
2676: my $ua=new LWP::UserAgent;
2677: my $request=new HTTP::Request('GET',$url);
2678: my $response=$ua->request($request);
2679: if (wantarray) {
2680: return ($response->content, $response);
2681: } else {
2682: return $response->content;
2683: }
2684: }
2685:
2686: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2687:
2688: sub allowuploaded {
2689: my ($srcurl,$url)=@_;
2690: $url=&clutter(&declutter($url));
2691: my $dir=$url;
2692: $dir=~s/\/[^\/]+$//;
2693: my %httpref=();
2694: my $httpurl=&hreflocation('',$url);
2695: $httpref{'httpref.'.$httpurl}=$srcurl;
2696: &Apache::lonnet::appenv(\%httpref);
2697: }
2698:
2699: #
2700: # Determine if the current user should be able to edit a particular resource,
2701: # when viewing in course context.
2702: # (a) When viewing resource used to determine if "Edit" item is included in
2703: # Functions.
2704: # (b) When displaying folder contents in course editor, used to determine if
2705: # "Edit" link will be displayed alongside resource.
2706: #
2707: # input: six args -- filename (decluttered), course number, course domain,
2708: # url, symb (if registered) and group (if this is a group
2709: # item -- e.g., bulletin board, group page etc.).
2710: # output: array of five scalars --
2711: # $cfile -- url for file editing if editable on current server
2712: # $home -- homeserver of resource (i.e., for author if published,
2713: # or course if uploaded.).
2714: # $switchserver -- 1 if server switch will be needed.
2715: # $forceedit -- 1 if icon/link should be to go to edit mode
2716: # $forceview -- 1 if icon/link should be to go to view mode
2717: #
2718:
2719: sub can_edit_resource {
2720: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2721: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2722: #
2723: # For aboutme pages user can only edit his/her own.
2724: #
2725: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2726: my ($sdom,$sname) = ($1,$2);
2727: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2728: $home = $env{'user.home'};
2729: $cfile = $resurl;
2730: if ($env{'form.forceedit'}) {
2731: $forceview = 1;
2732: } else {
2733: $forceedit = 1;
2734: }
2735: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2736: } else {
2737: return;
2738: }
2739: }
2740:
2741: if ($env{'request.course.id'}) {
2742: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2743: if ($group ne '') {
2744: # if this is a group homepage or group bulletin board, check group privs
2745: my $allowed = 0;
2746: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2747: if ((&allowed('mdg',$env{'request.course.id'}.
2748: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2749: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2750: $allowed = 1;
2751: }
2752: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2753: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2754: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2755: $allowed = 1;
2756: }
2757: }
2758: if ($allowed) {
2759: $home=&homeserver($cnum,$cdom);
2760: if ($env{'form.forceedit'}) {
2761: $forceview = 1;
2762: } else {
2763: $forceedit = 1;
2764: }
2765: $cfile = $resurl;
2766: } else {
2767: return;
2768: }
2769: } else {
2770: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2771: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2772: return;
2773: }
2774: } elsif (!$crsedit) {
2775: #
2776: # No edit allowed where CC has switched to student role.
2777: #
2778: return;
2779: }
2780: }
2781: }
2782:
2783: if ($file ne '') {
2784: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2785: if (&is_course_upload($file,$cnum,$cdom)) {
2786: $uploaded = 1;
2787: $incourse = 1;
2788: if ($file =~/\.(htm|html|css|js|txt)$/) {
2789: $cfile = &hreflocation('',$file);
2790: if ($env{'form.forceedit'}) {
2791: $forceview = 1;
2792: } else {
2793: $forceedit = 1;
2794: }
2795: }
2796: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2797: $incourse = 1;
2798: if ($env{'form.forceedit'}) {
2799: $forceview = 1;
2800: } else {
2801: $forceedit = 1;
2802: }
2803: $cfile = $resurl;
2804: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2805: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2806: $incourse = 1;
2807: if ($env{'form.forceedit'}) {
2808: $forceview = 1;
2809: } else {
2810: $forceedit = 1;
2811: }
2812: $cfile = $resurl;
2813: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2814: $incourse = 1;
2815: $cfile = $resurl.'/smpedit';
2816: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2817: $incourse = 1;
2818: if ($env{'form.forceedit'}) {
2819: $forceview = 1;
2820: } else {
2821: $forceedit = 1;
2822: }
2823: $cfile = $resurl;
2824: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2825: $incourse = 1;
2826: if ($env{'form.forceedit'}) {
2827: $forceview = 1;
2828: } else {
2829: $forceedit = 1;
2830: }
2831: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2832: }
2833: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2834: my $template = '/res/lib/templates/simpleproblem.problem';
2835: if (&is_on_map($template)) {
2836: $incourse = 1;
2837: $forceview = 1;
2838: $cfile = $template;
2839: }
2840: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2841: $incourse = 1;
2842: if ($env{'form.forceedit'}) {
2843: $forceview = 1;
2844: } else {
2845: $forceedit = 1;
2846: }
2847: $cfile = $resurl;
2848: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2849: $incourse = 1;
2850: $forceview = 1;
2851: if ($symb) {
2852: my ($map,$id,$res)=&decode_symb($symb);
2853: $env{'request.symb'} = $symb;
2854: $cfile = &clutter($res);
2855: } else {
2856: $cfile = $env{'form.suppurl'};
2857: $cfile =~ s{^http://}{};
2858: $cfile = '/adm/wrapper/ext/'.$cfile;
2859: }
2860: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2861: if ($env{'form.forceedit'}) {
2862: $forceview = 1;
2863: } else {
2864: $forceedit = 1;
2865: }
2866: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2867: }
2868: }
2869: if ($uploaded || $incourse) {
2870: $home=&homeserver($cnum,$cdom);
2871: } elsif ($file !~ m{/$}) {
2872: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2873: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2874: # Check that the user has permission to edit this resource
2875: my $setpriv = 1;
2876: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2877: if (defined($cfudom)) {
2878: $home=&homeserver($cfuname,$cfudom);
2879: $cfile=$file;
2880: }
2881: }
2882: if (($cfile ne '') && (!$incourse || $uploaded) &&
2883: (($home ne '') && ($home ne 'no_host'))) {
2884: my @ids=¤t_machine_ids();
2885: unless (grep(/^\Q$home\E$/,@ids)) {
2886: $switchserver=1;
2887: }
2888: }
2889: }
2890: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2891: }
2892:
2893: sub is_course_upload {
2894: my ($file,$cnum,$cdom) = @_;
2895: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2896: $uploadpath =~ s{^\/}{};
2897: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2898: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2899: return 1;
2900: }
2901: return;
2902: }
2903:
2904: sub in_course {
2905: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2906: if ($hideprivileged) {
2907: my $skipuser;
2908: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2909: my @possdoms = ($cdom);
2910: if ($coursehash{'checkforpriv'}) {
2911: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2912: }
2913: if (&privileged($uname,$udom,\@possdoms)) {
2914: $skipuser = 1;
2915: if ($coursehash{'nothideprivileged'}) {
2916: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2917: my $user;
2918: if ($item =~ /:/) {
2919: $user = $item;
2920: } else {
2921: $user = join(':',split(/[\@]/,$item));
2922: }
2923: if ($user eq $uname.':'.$udom) {
2924: undef($skipuser);
2925: last;
2926: }
2927: }
2928: }
2929: if ($skipuser) {
2930: return 0;
2931: }
2932: }
2933: }
2934: $type ||= 'any';
2935: if (!defined($cdom) || !defined($cnum)) {
2936: my $cid = $env{'request.course.id'};
2937: $cdom = $env{'course.'.$cid.'.domain'};
2938: $cnum = $env{'course.'.$cid.'.num'};
2939: }
2940: my $typesref;
2941: if (($type eq 'any') || ($type eq 'all')) {
2942: $typesref = ['active','previous','future'];
2943: } elsif ($type eq 'previous' || $type eq 'future') {
2944: $typesref = [$type];
2945: }
2946: my %roles = &get_my_roles($uname,$udom,'userroles',
2947: $typesref,undef,[$cdom]);
2948: my ($tmp) = keys(%roles);
2949: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2950: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2951: if (@course_roles > 0) {
2952: return 1;
2953: }
2954: return 0;
2955: }
2956:
2957: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2958: # input: action, courseID, current domain, intended
2959: # path to file, source of file, instruction to parse file for objects,
2960: # ref to hash for embedded objects,
2961: # ref to hash for codebase of java objects.
2962: # reference to scalar to accommodate mime type determined
2963: # from File::MMagic if $parser = parse.
2964: #
2965: # output: url to file (if action was uploaddoc),
2966: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2967: #
2968: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2969: # course.
2970: #
2971: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2972: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2973: # course's home server.
2974: #
2975: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2976: # be copied from $source (current location) to
2977: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2978: # and will then be copied to
2979: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2980: # course's home server.
2981: #
2982: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2983: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2984: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2985: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2986: # in course's home server.
2987: #
2988:
2989: sub process_coursefile {
2990: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2991: $mimetype)=@_;
2992: my $fetchresult;
2993: my $home=&homeserver($docuname,$docudom);
2994: if ($action eq 'propagate') {
2995: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2996: $home);
2997: } else {
2998: my $fpath = '';
2999: my $fname = $file;
3000: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3001: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3002: my $filepath = &build_filepath($fpath);
3003: if ($action eq 'copy') {
3004: if ($source eq '') {
3005: $fetchresult = 'no source file';
3006: return $fetchresult;
3007: } else {
3008: my $destination = $filepath.'/'.$fname;
3009: rename($source,$destination);
3010: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3011: $home);
3012: }
3013: } elsif ($action eq 'uploaddoc') {
3014: open(my $fh,'>'.$filepath.'/'.$fname);
3015: print $fh $env{'form.'.$source};
3016: close($fh);
3017: if ($parser eq 'parse') {
3018: my $mm = new File::MMagic;
3019: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3020: if ($type eq 'text/html') {
3021: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3022: unless ($parse_result eq 'ok') {
3023: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3024: }
3025: }
3026: if (ref($mimetype)) {
3027: $$mimetype = $type;
3028: }
3029: }
3030: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3031: $home);
3032: if ($fetchresult eq 'ok') {
3033: return '/uploaded/'.$fpath.'/'.$fname;
3034: } else {
3035: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3036: ' to host '.$home.': '.$fetchresult);
3037: return '/adm/notfound.html';
3038: }
3039: }
3040: }
3041: unless ( $fetchresult eq 'ok') {
3042: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3043: ' to host '.$home.': '.$fetchresult);
3044: }
3045: return $fetchresult;
3046: }
3047:
3048: sub build_filepath {
3049: my ($fpath) = @_;
3050: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3051: unless ($fpath eq '') {
3052: my @parts=split('/',$fpath);
3053: foreach my $part (@parts) {
3054: $filepath.= '/'.$part;
3055: if ((-e $filepath)!=1) {
3056: mkdir($filepath,0777);
3057: }
3058: }
3059: }
3060: return $filepath;
3061: }
3062:
3063: sub store_edited_file {
3064: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3065: my $file = $primary_url;
3066: $file =~ s#^/uploaded/$docudom/$docuname/##;
3067: my $fpath = '';
3068: my $fname = $file;
3069: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3070: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3071: my $filepath = &build_filepath($fpath);
3072: open(my $fh,'>'.$filepath.'/'.$fname);
3073: print $fh $content;
3074: close($fh);
3075: my $home=&homeserver($docuname,$docudom);
3076: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3077: $home);
3078: if ($$fetchresult eq 'ok') {
3079: return '/uploaded/'.$fpath.'/'.$fname;
3080: } else {
3081: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3082: ' to host '.$home.': '.$$fetchresult);
3083: return '/adm/notfound.html';
3084: }
3085: }
3086:
3087: sub clean_filename {
3088: my ($fname,$args)=@_;
3089: # Replace Windows backslashes by forward slashes
3090: $fname=~s/\\/\//g;
3091: if (!$args->{'keep_path'}) {
3092: # Get rid of everything but the actual filename
3093: $fname=~s/^.*\/([^\/]+)$/$1/;
3094: }
3095: # Replace spaces by underscores
3096: $fname=~s/\s+/\_/g;
3097: # Replace all other weird characters by nothing
3098: $fname=~s{[^/\w\.\-]}{}g;
3099: # Replace all .\d. sequences with _\d. so they no longer look like version
3100: # numbers
3101: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3102: return $fname;
3103: }
3104: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3105: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3106: # image with the same aspect ratio as the original, but with dimensions which do
3107: # not exceed $resizewidth and $resizeheight.
3108:
3109: sub resizeImage {
3110: my ($img_path,$resizewidth,$resizeheight) = @_;
3111: my $ima = Image::Magick->new;
3112: my $resized;
3113: if (-e $img_path) {
3114: $ima->Read($img_path);
3115: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3116: my $width = $ima->Get('width');
3117: my $height = $ima->Get('height');
3118: if ($width > $resizewidth) {
3119: my $factor = $width/$resizewidth;
3120: my $newheight = $height/$factor;
3121: $ima->Scale(width=>$resizewidth,height=>$newheight);
3122: $resized = 1;
3123: }
3124: }
3125: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3126: my $width = $ima->Get('width');
3127: my $height = $ima->Get('height');
3128: if ($height > $resizeheight) {
3129: my $factor = $height/$resizeheight;
3130: my $newwidth = $width/$factor;
3131: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3132: $resized = 1;
3133: }
3134: }
3135: if ($resized) {
3136: $ima->Write($img_path);
3137: }
3138: }
3139: return;
3140: }
3141:
3142: # --------------- Take an uploaded file and put it into the userfiles directory
3143: # input: $formname - the contents of the file are in $env{"form.$formname"}
3144: # the desired filename is in $env{"form.$formname.filename"}
3145: # $context - possible values: coursedoc, existingfile, overwrite,
3146: # canceloverwrite, or ''.
3147: # if 'coursedoc': upload to the current course
3148: # if 'existingfile': write file to tmp/overwrites directory
3149: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3150: # $context is passed as argument to &finishuserfileupload
3151: # $subdir - directory in userfile to store the file into
3152: # $parser - instruction to parse file for objects ($parser = parse)
3153: # $allfiles - reference to hash for embedded objects
3154: # $codebase - reference to hash for codebase of java objects
3155: # $desuname - username for permanent storage of uploaded file
3156: # $dsetudom - domain for permanaent storage of uploaded file
3157: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3158: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3159: # $resizewidth - width (pixels) to which to resize uploaded image
3160: # $resizeheight - height (pixels) to which to resize uploaded image
3161: # $mimetype - reference to scalar to accommodate mime type determined
3162: # from File::MMagic.
3163: #
3164: # output: url of file in userspace, or error: <message>
3165: # or /adm/notfound.html if failure to upload occurse
3166:
3167: sub userfileupload {
3168: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3169: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3170: if (!defined($subdir)) { $subdir='unknown'; }
3171: my $fname=$env{'form.'.$formname.'.filename'};
3172: $fname=&clean_filename($fname);
3173: # See if there is anything left
3174: unless ($fname) { return 'error: no uploaded file'; }
3175: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3176: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3177: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3178: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3179: my $now = time;
3180: my $filepath;
3181: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3182: $filepath = 'tmp/helprequests/'.$now;
3183: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3184: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3185: '_'.$env{'user.domain'}.'/pending';
3186: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3187: my ($docuname,$docudom);
3188: if ($destudom) {
3189: $docudom = $destudom;
3190: } else {
3191: $docudom = $env{'user.domain'};
3192: }
3193: if ($destuname) {
3194: $docuname = $destuname;
3195: } else {
3196: $docuname = $env{'user.name'};
3197: }
3198: if (exists($env{'form.group'})) {
3199: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3200: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3201: }
3202: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3203: if ($context eq 'canceloverwrite') {
3204: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3205: if (-e $tempfile) {
3206: my @info = stat($tempfile);
3207: if ($info[9] eq $env{'form.timestamp'}) {
3208: unlink($tempfile);
3209: }
3210: }
3211: return;
3212: }
3213: }
3214: # Create the directory if not present
3215: my @parts=split(/\//,$filepath);
3216: my $fullpath = $perlvar{'lonDaemons'};
3217: for (my $i=0;$i<@parts;$i++) {
3218: $fullpath .= '/'.$parts[$i];
3219: if ((-e $fullpath)!=1) {
3220: mkdir($fullpath,0777);
3221: }
3222: }
3223: open(my $fh,'>'.$fullpath.'/'.$fname);
3224: print $fh $env{'form.'.$formname};
3225: close($fh);
3226: if ($context eq 'existingfile') {
3227: my @info = stat($fullpath.'/'.$fname);
3228: return ($fullpath.'/'.$fname,$info[9]);
3229: } else {
3230: return $fullpath.'/'.$fname;
3231: }
3232: }
3233: if ($subdir eq 'scantron') {
3234: $fname = 'scantron_orig_'.$fname;
3235: } else {
3236: $fname="$subdir/$fname";
3237: }
3238: if ($context eq 'coursedoc') {
3239: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3240: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3241: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3242: return &finishuserfileupload($docuname,$docudom,
3243: $formname,$fname,$parser,$allfiles,
3244: $codebase,$thumbwidth,$thumbheight,
3245: $resizewidth,$resizeheight,$context,$mimetype);
3246: } else {
3247: if ($env{'form.folder'}) {
3248: $fname=$env{'form.folder'}.'/'.$fname;
3249: }
3250: return &process_coursefile('uploaddoc',$docuname,$docudom,
3251: $fname,$formname,$parser,
3252: $allfiles,$codebase,$mimetype);
3253: }
3254: } elsif (defined($destuname)) {
3255: my $docuname=$destuname;
3256: my $docudom=$destudom;
3257: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3258: $parser,$allfiles,$codebase,
3259: $thumbwidth,$thumbheight,
3260: $resizewidth,$resizeheight,$context,$mimetype);
3261: } else {
3262: my $docuname=$env{'user.name'};
3263: my $docudom=$env{'user.domain'};
3264: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3265: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3266: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3267: }
3268: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3269: $parser,$allfiles,$codebase,
3270: $thumbwidth,$thumbheight,
3271: $resizewidth,$resizeheight,$context,$mimetype);
3272: }
3273: }
3274:
3275: sub finishuserfileupload {
3276: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3277: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3278: my $path=$docudom.'/'.$docuname.'/';
3279: my $filepath=$perlvar{'lonDocRoot'};
3280:
3281: my ($fnamepath,$file,$fetchthumb);
3282: $file=$fname;
3283: if ($fname=~m|/|) {
3284: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3285: $path.=$fnamepath.'/';
3286: }
3287: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3288: my $count;
3289: for ($count=4;$count<=$#parts;$count++) {
3290: $filepath.="/$parts[$count]";
3291: if ((-e $filepath)!=1) {
3292: mkdir($filepath,0777);
3293: }
3294: }
3295:
3296: # Save the file
3297: {
3298: if (!open(FH,'>'.$filepath.'/'.$file)) {
3299: &logthis('Failed to create '.$filepath.'/'.$file);
3300: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3301: return '/adm/notfound.html';
3302: }
3303: if ($context eq 'overwrite') {
3304: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3305: my $target = $filepath.'/'.$file;
3306: if (-e $source) {
3307: my @info = stat($source);
3308: if ($info[9] eq $env{'form.timestamp'}) {
3309: unless (&File::Copy::move($source,$target)) {
3310: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3311: return "Moving from $source failed";
3312: }
3313: } else {
3314: return "Temporary file: $source had unexpected date/time for last modification";
3315: }
3316: } else {
3317: return "Temporary file: $source missing";
3318: }
3319: } elsif (!print FH ($env{'form.'.$formname})) {
3320: &logthis('Failed to write to '.$filepath.'/'.$file);
3321: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3322: return '/adm/notfound.html';
3323: }
3324: close(FH);
3325: if ($resizewidth && $resizeheight) {
3326: my $mm = new File::MMagic;
3327: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3328: if ($mime_type =~ m{^image/}) {
3329: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3330: }
3331: }
3332: }
3333: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3334: if (ref($mimetype)) {
3335: if ($$mimetype eq '') {
3336: my $mm = new File::MMagic;
3337: my $type = $mm->checktype_filename($filepath.'/'.$file);
3338: $$mimetype = $type;
3339: }
3340: }
3341: }
3342: if ($parser eq 'parse') {
3343: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3344: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3345: $allfiles,$codebase);
3346: unless ($parse_result eq 'ok') {
3347: &logthis('Failed to parse '.$filepath.$file.
3348: ' for embedded media: '.$parse_result);
3349: }
3350: }
3351: }
3352: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3353: my $input = $filepath.'/'.$file;
3354: my $output = $filepath.'/'.'tn-'.$file;
3355: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3356: system("convert -sample $thumbsize $input $output");
3357: if (-e $filepath.'/'.'tn-'.$file) {
3358: $fetchthumb = 1;
3359: }
3360: }
3361:
3362: # Notify homeserver to grep it
3363: #
3364: my $docuhome=&homeserver($docuname,$docudom);
3365: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3366: if ($fetchresult eq 'ok') {
3367: if ($fetchthumb) {
3368: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3369: if ($thumbresult ne 'ok') {
3370: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3371: $docuhome.': '.$thumbresult);
3372: }
3373: }
3374: #
3375: # Return the URL to it
3376: return '/uploaded/'.$path.$file;
3377: } else {
3378: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3379: ': '.$fetchresult);
3380: return '/adm/notfound.html';
3381: }
3382: }
3383:
3384: sub extract_embedded_items {
3385: my ($fullpath,$allfiles,$codebase,$content) = @_;
3386: my @state = ();
3387: my (%lastids,%related,%shockwave,%flashvars);
3388: my %javafiles = (
3389: codebase => '',
3390: code => '',
3391: archive => ''
3392: );
3393: my %mediafiles = (
3394: src => '',
3395: movie => '',
3396: );
3397: my $p;
3398: if ($content) {
3399: $p = HTML::LCParser->new($content);
3400: } else {
3401: $p = HTML::LCParser->new($fullpath);
3402: }
3403: while (my $t=$p->get_token()) {
3404: if ($t->[0] eq 'S') {
3405: my ($tagname, $attr) = ($t->[1],$t->[2]);
3406: push(@state, $tagname);
3407: if (lc($tagname) eq 'allow') {
3408: &add_filetype($allfiles,$attr->{'src'},'src');
3409: }
3410: if (lc($tagname) eq 'img') {
3411: &add_filetype($allfiles,$attr->{'src'},'src');
3412: }
3413: if (lc($tagname) eq 'a') {
3414: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3415: &add_filetype($allfiles,$attr->{'href'},'href');
3416: }
3417: }
3418: if (lc($tagname) eq 'script') {
3419: my $src;
3420: if ($attr->{'archive'} =~ /\.jar$/i) {
3421: &add_filetype($allfiles,$attr->{'archive'},'archive');
3422: } else {
3423: if ($attr->{'src'} ne '') {
3424: $src = $attr->{'src'};
3425: &add_filetype($allfiles,$src,'src');
3426: }
3427: }
3428: my $text = $p->get_trimmed_text();
3429: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3430: my @swfargs = split(/,/,$1);
3431: foreach my $item (@swfargs) {
3432: $item =~ s/["']//g;
3433: $item =~ s/^\s+//;
3434: $item =~ s/\s+$//;
3435: }
3436: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3437: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3438: push(@{$related{$swfargs[0]}},$swfargs[2]);
3439: } else {
3440: $related{$swfargs[0]} = [$swfargs[2]];
3441: }
3442: }
3443: }
3444: }
3445: if (lc($tagname) eq 'link') {
3446: if (lc($attr->{'rel'}) eq 'stylesheet') {
3447: &add_filetype($allfiles,$attr->{'href'},'href');
3448: }
3449: }
3450: if (lc($tagname) eq 'object' ||
3451: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3452: foreach my $item (keys(%javafiles)) {
3453: $javafiles{$item} = '';
3454: }
3455: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3456: $lastids{lc($tagname)} = $attr->{'id'};
3457: }
3458: }
3459: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3460: my $name = lc($attr->{'name'});
3461: foreach my $item (keys(%javafiles)) {
3462: if ($name eq $item) {
3463: $javafiles{$item} = $attr->{'value'};
3464: last;
3465: }
3466: }
3467: my $pathfrom;
3468: foreach my $item (keys(%mediafiles)) {
3469: if ($name eq $item) {
3470: $pathfrom = $attr->{'value'};
3471: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3472: &add_filetype($allfiles,$pathfrom,$name);
3473: last;
3474: }
3475: }
3476: if ($name eq 'flashvars') {
3477: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3478: }
3479: if ($pathfrom ne '') {
3480: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3481: $pathfrom);
3482: }
3483: }
3484: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3485: foreach my $item (keys(%javafiles)) {
3486: if ($attr->{$item}) {
3487: $javafiles{$item} = $attr->{$item};
3488: last;
3489: }
3490: }
3491: foreach my $item (keys(%mediafiles)) {
3492: if ($attr->{$item}) {
3493: &add_filetype($allfiles,$attr->{$item},$item);
3494: last;
3495: }
3496: }
3497: if (lc($tagname) eq 'embed') {
3498: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3499: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3500: $attr->{'src'});
3501: }
3502: }
3503: }
3504: if ($t->[4] =~ m{/>$}) {
3505: pop(@state);
3506: }
3507: } elsif ($t->[0] eq 'E') {
3508: my ($tagname) = ($t->[1]);
3509: if ($javafiles{'codebase'} ne '') {
3510: $javafiles{'codebase'} .= '/';
3511: }
3512: if (lc($tagname) eq 'applet' ||
3513: lc($tagname) eq 'object' ||
3514: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3515: ) {
3516: foreach my $item (keys(%javafiles)) {
3517: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3518: my $file=$javafiles{'codebase'}.$javafiles{$item};
3519: &add_filetype($allfiles,$file,$item);
3520: }
3521: }
3522: }
3523: pop @state;
3524: }
3525: }
3526: foreach my $id (sort(keys(%flashvars))) {
3527: if ($shockwave{$id} ne '') {
3528: my @pairs = split(/\&/,$flashvars{$id});
3529: foreach my $pair (@pairs) {
3530: my ($key,$value) = split(/\=/,$pair);
3531: if ($key eq 'thumb') {
3532: &add_filetype($allfiles,$value,$key);
3533: } elsif ($key eq 'content') {
3534: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3535: my ($ext) = ($value =~ /\.([^.]+)$/);
3536: if ($ext ne '') {
3537: &add_filetype($allfiles,$path.$value,$ext);
3538: }
3539: }
3540: }
3541: }
3542: }
3543: return 'ok';
3544: }
3545:
3546: sub add_filetype {
3547: my ($allfiles,$file,$type)=@_;
3548: if (exists($allfiles->{$file})) {
3549: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3550: push(@{$allfiles->{$file}}, &escape($type));
3551: }
3552: } else {
3553: @{$allfiles->{$file}} = (&escape($type));
3554: }
3555: }
3556:
3557: sub embedded_dependency {
3558: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3559: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3560: if (($identifier ne '') &&
3561: (ref($related->{$identifier}) eq 'ARRAY') &&
3562: ($pathfrom ne '')) {
3563: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3564: foreach my $dep (@{$related->{$identifier}}) {
3565: &add_filetype($allfiles,$path.$dep,'object');
3566: }
3567: }
3568: }
3569: return;
3570: }
3571:
3572: sub removeuploadedurl {
3573: my ($url)=@_;
3574: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3575: return &removeuserfile($uname,$udom,$fname);
3576: }
3577:
3578: sub removeuserfile {
3579: my ($docuname,$docudom,$fname)=@_;
3580: my $home=&homeserver($docuname,$docudom);
3581: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3582: if ($result eq 'ok') {
3583: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3584: my $metafile = $fname.'.meta';
3585: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3586: my $url = "/uploaded/$docudom/$docuname/$fname";
3587: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3588: my $sqlresult =
3589: &update_portfolio_table($docuname,$docudom,$file,
3590: 'portfolio_metadata',$group,
3591: 'delete');
3592: }
3593: }
3594: return $result;
3595: }
3596:
3597: sub mkdiruserfile {
3598: my ($docuname,$docudom,$dir)=@_;
3599: my $home=&homeserver($docuname,$docudom);
3600: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3601: }
3602:
3603: sub renameuserfile {
3604: my ($docuname,$docudom,$old,$new)=@_;
3605: my $home=&homeserver($docuname,$docudom);
3606: my $result = &reply("renameuserfile:$docudom:$docuname:".
3607: &escape("$old").':'.&escape("$new"),$home);
3608: if ($result eq 'ok') {
3609: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3610: my $oldmeta = $old.'.meta';
3611: my $newmeta = $new.'.meta';
3612: my $metaresult =
3613: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3614: my $url = "/uploaded/$docudom/$docuname/$old";
3615: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3616: my $sqlresult =
3617: &update_portfolio_table($docuname,$docudom,$file,
3618: 'portfolio_metadata',$group,
3619: 'delete');
3620: }
3621: }
3622: return $result;
3623: }
3624:
3625: # ------------------------------------------------------------------------- Log
3626:
3627: sub log {
3628: my ($dom,$nam,$hom,$what)=@_;
3629: return critical("log:$dom:$nam:$what",$hom);
3630: }
3631:
3632: # ------------------------------------------------------------------ Course Log
3633: #
3634: # This routine flushes several buffers of non-mission-critical nature
3635: #
3636:
3637: sub flushcourselogs {
3638: &logthis('Flushing log buffers');
3639: #
3640: # course logs
3641: # This is a log of all transactions in a course, which can be used
3642: # for data mining purposes
3643: #
3644: # It also collects the courseid database, which lists last transaction
3645: # times and course titles for all courseids
3646: #
3647: my %courseidbuffer=();
3648: foreach my $crsid (keys(%courselogs)) {
3649: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3650: &escape($courselogs{$crsid}),
3651: $coursehombuf{$crsid}) eq 'ok') {
3652: delete $courselogs{$crsid};
3653: } else {
3654: &logthis('Failed to flush log buffer for '.$crsid);
3655: if (length($courselogs{$crsid})>40000) {
3656: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3657: " exceeded maximum size, deleting.</font>");
3658: delete $courselogs{$crsid};
3659: }
3660: }
3661: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3662: 'description' => $coursedescrbuf{$crsid},
3663: 'inst_code' => $courseinstcodebuf{$crsid},
3664: 'type' => $coursetypebuf{$crsid},
3665: 'owner' => $courseownerbuf{$crsid},
3666: };
3667: }
3668: #
3669: # Write course id database (reverse lookup) to homeserver of courses
3670: # Is used in pickcourse
3671: #
3672: foreach my $crs_home (keys(%courseidbuffer)) {
3673: my $response = &courseidput(&host_domain($crs_home),
3674: $courseidbuffer{$crs_home},
3675: $crs_home,'timeonly');
3676: }
3677: #
3678: # File accesses
3679: # Writes to the dynamic metadata of resources to get hit counts, etc.
3680: #
3681: foreach my $entry (keys(%accesshash)) {
3682: if ($entry =~ /___count$/) {
3683: my ($dom,$name);
3684: ($dom,$name,undef)=
3685: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3686: if (! defined($dom) || $dom eq '' ||
3687: ! defined($name) || $name eq '') {
3688: my $cid = $env{'request.course.id'};
3689: $dom = $env{'request.'.$cid.'.domain'};
3690: $name = $env{'request.'.$cid.'.num'};
3691: }
3692: my $value = $accesshash{$entry};
3693: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3694: my %temphash=($url => $value);
3695: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3696: if ($result eq 'ok') {
3697: delete $accesshash{$entry};
3698: }
3699: } else {
3700: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3701: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3702: my %temphash=($entry => $accesshash{$entry});
3703: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3704: delete $accesshash{$entry};
3705: }
3706: }
3707: }
3708: #
3709: # Roles
3710: # Reverse lookup of user roles for course faculty/staff and co-authorship
3711: #
3712: foreach my $entry (keys(%userrolehash)) {
3713: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3714: split(/\:/,$entry);
3715: if (&Apache::lonnet::put('nohist_userroles',
3716: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3717: $rudom,$runame) eq 'ok') {
3718: delete $userrolehash{$entry};
3719: }
3720: }
3721: #
3722: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3723: #
3724: my %domrolebuffer = ();
3725: foreach my $entry (keys(%domainrolehash)) {
3726: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3727: if ($domrolebuffer{$rudom}) {
3728: $domrolebuffer{$rudom}.='&'.&escape($entry).
3729: '='.&escape($domainrolehash{$entry});
3730: } else {
3731: $domrolebuffer{$rudom}.=&escape($entry).
3732: '='.&escape($domainrolehash{$entry});
3733: }
3734: delete $domainrolehash{$entry};
3735: }
3736: foreach my $dom (keys(%domrolebuffer)) {
3737: my %servers = &get_servers($dom,'library');
3738: foreach my $tryserver (keys(%servers)) {
3739: unless (&reply('domroleput:'.$dom.':'.
3740: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3741: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3742: }
3743: }
3744: }
3745: $dumpcount++;
3746: }
3747:
3748: sub courselog {
3749: my $what=shift;
3750: $what=time.':'.$what;
3751: unless ($env{'request.course.id'}) { return ''; }
3752: $coursedombuf{$env{'request.course.id'}}=
3753: $env{'course.'.$env{'request.course.id'}.'.domain'};
3754: $coursenumbuf{$env{'request.course.id'}}=
3755: $env{'course.'.$env{'request.course.id'}.'.num'};
3756: $coursehombuf{$env{'request.course.id'}}=
3757: $env{'course.'.$env{'request.course.id'}.'.home'};
3758: $coursedescrbuf{$env{'request.course.id'}}=
3759: $env{'course.'.$env{'request.course.id'}.'.description'};
3760: $courseinstcodebuf{$env{'request.course.id'}}=
3761: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3762: $courseownerbuf{$env{'request.course.id'}}=
3763: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3764: $coursetypebuf{$env{'request.course.id'}}=
3765: $env{'course.'.$env{'request.course.id'}.'.type'};
3766: if (defined $courselogs{$env{'request.course.id'}}) {
3767: $courselogs{$env{'request.course.id'}}.='&'.$what;
3768: } else {
3769: $courselogs{$env{'request.course.id'}}.=$what;
3770: }
3771: if (length($courselogs{$env{'request.course.id'}})>4048) {
3772: &flushcourselogs();
3773: }
3774: }
3775:
3776: sub courseacclog {
3777: my $fnsymb=shift;
3778: unless ($env{'request.course.id'}) { return ''; }
3779: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3780: if ($fnsymb=~/$LONCAPA::assess_re/) {
3781: $what.=':POST';
3782: # FIXME: Probably ought to escape things....
3783: foreach my $key (keys(%env)) {
3784: if ($key=~/^form\.(.*)/) {
3785: my $formitem = $1;
3786: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3787: $what.=':'.$formitem.'='.$env{$key};
3788: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3789: $what.=':'.$formitem.'='.$env{$key};
3790: }
3791: }
3792: }
3793: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3794: # FIXME: We should not be depending on a form parameter that someone
3795: # editing lonsearchcat.pm might change in the future.
3796: if ($env{'form.phase'} eq 'course_search') {
3797: $what.= ':POST';
3798: # FIXME: Probably ought to escape things....
3799: foreach my $element ('courseexp','crsfulltext','crsrelated',
3800: 'crsdiscuss') {
3801: $what.=':'.$element.'='.$env{'form.'.$element};
3802: }
3803: }
3804: }
3805: &courselog($what);
3806: }
3807:
3808: sub countacc {
3809: my $url=&declutter(shift);
3810: return if (! defined($url) || $url eq '');
3811: unless ($env{'request.course.id'}) { return ''; }
3812: #
3813: # Mark that this url was used in this course
3814: #
3815: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3816: #
3817: # Increase the access count for this resource in this child process
3818: #
3819: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3820: $accesshash{$key}++;
3821: }
3822:
3823: sub linklog {
3824: my ($from,$to)=@_;
3825: $from=&declutter($from);
3826: $to=&declutter($to);
3827: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3828: $accesshash{$to.'___'.$from.'___goto'}=1;
3829: }
3830:
3831: sub statslog {
3832: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3833: if ($users<2) { return; }
3834: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3835: 'course' => $env{'request.course.id'},
3836: 'sections' => '"all"',
3837: 'num_students' => $users,
3838: 'part' => $part,
3839: 'symb' => $symb,
3840: 'mean_tries' => $av_attempts,
3841: 'deg_of_diff' => $degdiff});
3842: foreach my $key (keys(%dynstore)) {
3843: $accesshash{$key}=$dynstore{$key};
3844: }
3845: }
3846:
3847: sub userrolelog {
3848: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3849: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
3850: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3851: $userrolehash
3852: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3853: =$tend.':'.$tstart;
3854: }
3855: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
3856: $userrolehash
3857: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3858: =$tend.':'.$tstart;
3859: }
3860: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
3861: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3862: $domainrolehash
3863: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3864: = $tend.':'.$tstart;
3865: }
3866: }
3867:
3868: sub courserolelog {
3869: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3870: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3871: my $cdom = $1;
3872: my $cnum = $2;
3873: my $sec = $3;
3874: my $namespace = 'rolelog';
3875: my %storehash = (
3876: role => $trole,
3877: start => $tstart,
3878: end => $tend,
3879: selfenroll => $selfenroll,
3880: context => $context,
3881: );
3882: if ($trole eq 'gr') {
3883: $namespace = 'groupslog';
3884: $storehash{'group'} = $sec;
3885: } else {
3886: $storehash{'section'} = $sec;
3887: }
3888: &write_log('course',$namespace,\%storehash,$delflag,$username,
3889: $domain,$cnum,$cdom);
3890: if (($trole ne 'st') || ($sec ne '')) {
3891: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3892: }
3893: }
3894: return;
3895: }
3896:
3897: sub domainrolelog {
3898: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3899: if ($area =~ m{^/($match_domain)/$}) {
3900: my $cdom = $1;
3901: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3902: my $namespace = 'rolelog';
3903: my %storehash = (
3904: role => $trole,
3905: start => $tstart,
3906: end => $tend,
3907: context => $context,
3908: );
3909: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3910: $domain,$domconfiguser,$cdom);
3911: }
3912: return;
3913:
3914: }
3915:
3916: sub coauthorrolelog {
3917: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3918: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3919: my $audom = $1;
3920: my $auname = $2;
3921: my $namespace = 'rolelog';
3922: my %storehash = (
3923: role => $trole,
3924: start => $tstart,
3925: end => $tend,
3926: context => $context,
3927: );
3928: &write_log('author',$namespace,\%storehash,$delflag,$username,
3929: $domain,$auname,$audom);
3930: }
3931: return;
3932: }
3933:
3934: sub get_course_adv_roles {
3935: my ($cid,$codes) = @_;
3936: $cid=$env{'request.course.id'} unless (defined($cid));
3937: my %coursehash=&coursedescription($cid);
3938: my $crstype = &Apache::loncommon::course_type($cid);
3939: my %nothide=();
3940: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3941: if ($user !~ /:/) {
3942: $nothide{join(':',split(/[\@]/,$user))}=1;
3943: } else {
3944: $nothide{$user}=1;
3945: }
3946: }
3947: my @possdoms = ($coursehash{'domain'});
3948: if ($coursehash{'checkforpriv'}) {
3949: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3950: }
3951: my %returnhash=();
3952: my %dumphash=
3953: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3954: my $now=time;
3955: my %privileged;
3956: foreach my $entry (keys(%dumphash)) {
3957: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3958: if (($tstart) && ($tstart<0)) { next; }
3959: if (($tend) && ($tend<$now)) { next; }
3960: if (($tstart) && ($now<$tstart)) { next; }
3961: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3962: if ($username eq '' || $domain eq '') { next; }
3963: if ((&privileged($username,$domain,\@possdoms)) &&
3964: (!$nothide{$username.':'.$domain})) { next; }
3965: if ($role eq 'cr') { next; }
3966: if ($codes) {
3967: if ($section) { $role .= ':'.$section; }
3968: if ($returnhash{$role}) {
3969: $returnhash{$role}.=','.$username.':'.$domain;
3970: } else {
3971: $returnhash{$role}=$username.':'.$domain;
3972: }
3973: } else {
3974: my $key=&plaintext($role,$crstype);
3975: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3976: if ($returnhash{$key}) {
3977: $returnhash{$key}.=','.$username.':'.$domain;
3978: } else {
3979: $returnhash{$key}=$username.':'.$domain;
3980: }
3981: }
3982: }
3983: return %returnhash;
3984: }
3985:
3986: sub get_my_roles {
3987: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3988: unless (defined($uname)) { $uname=$env{'user.name'}; }
3989: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3990: my (%dumphash,%nothide);
3991: if ($context eq 'userroles') {
3992: %dumphash = &dump('roles',$udom,$uname);
3993: } else {
3994: %dumphash = &dump('nohist_userroles',$udom,$uname);
3995: if ($hidepriv) {
3996: my %coursehash=&coursedescription($udom.'_'.$uname);
3997: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3998: if ($user !~ /:/) {
3999: $nothide{join(':',split(/[\@]/,$user))} = 1;
4000: } else {
4001: $nothide{$user} = 1;
4002: }
4003: }
4004: }
4005: }
4006: my %returnhash=();
4007: my $now=time;
4008: my %privileged;
4009: foreach my $entry (keys(%dumphash)) {
4010: my ($role,$tend,$tstart);
4011: if ($context eq 'userroles') {
4012: next if ($entry =~ /^rolesdef/);
4013: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4014: } else {
4015: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4016: }
4017: if (($tstart) && ($tstart<0)) { next; }
4018: my $status = 'active';
4019: if (($tend) && ($tend<=$now)) {
4020: $status = 'previous';
4021: }
4022: if (($tstart) && ($now<$tstart)) {
4023: $status = 'future';
4024: }
4025: if (ref($types) eq 'ARRAY') {
4026: if (!grep(/^\Q$status\E$/,@{$types})) {
4027: next;
4028: }
4029: } else {
4030: if ($status ne 'active') {
4031: next;
4032: }
4033: }
4034: my ($rolecode,$username,$domain,$section,$area);
4035: if ($context eq 'userroles') {
4036: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4037: (undef,$domain,$username,$section) = split(/\//,$area);
4038: } else {
4039: ($role,$username,$domain,$section) = split(/\:/,$entry);
4040: }
4041: if (ref($roledoms) eq 'ARRAY') {
4042: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4043: next;
4044: }
4045: }
4046: if (ref($roles) eq 'ARRAY') {
4047: if (!grep(/^\Q$role\E$/,@{$roles})) {
4048: if ($role =~ /^cr\//) {
4049: if (!grep(/^cr$/,@{$roles})) {
4050: next;
4051: }
4052: } elsif ($role =~ /^gr\//) {
4053: if (!grep(/^gr$/,@{$roles})) {
4054: next;
4055: }
4056: } else {
4057: next;
4058: }
4059: }
4060: }
4061: if ($hidepriv) {
4062: my @privroles = ('dc','su');
4063: if ($context eq 'userroles') {
4064: next if (grep(/^\Q$role\E$/,@privroles));
4065: } else {
4066: my $possdoms = [$domain];
4067: if (ref($roledoms) eq 'ARRAY') {
4068: push(@{$possdoms},@{$roledoms});
4069: }
4070: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4071: if (!$nothide{$username.':'.$domain}) {
4072: next;
4073: }
4074: }
4075: }
4076: }
4077: if ($withsec) {
4078: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4079: $tstart.':'.$tend;
4080: } else {
4081: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4082: }
4083: }
4084: return %returnhash;
4085: }
4086:
4087: # ----------------------------------------------------- Frontpage Announcements
4088: #
4089: #
4090:
4091: sub postannounce {
4092: my ($server,$text)=@_;
4093: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
4094: unless ($text=~/\w/) { $text=''; }
4095: return &reply('setannounce:'.&escape($text),$server);
4096: }
4097:
4098: sub getannounce {
4099:
4100: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
4101: my $announcement='';
4102: while (my $line = <$fh>) { $announcement .= $line; }
4103: close($fh);
4104: if ($announcement=~/\w/) {
4105: return
4106: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
4107: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
4108: } else {
4109: return '';
4110: }
4111: } else {
4112: return '';
4113: }
4114: }
4115:
4116: # ---------------------------------------------------------- Course ID routines
4117: # Deal with domain's nohist_courseid.db files
4118: #
4119:
4120: sub courseidput {
4121: my ($domain,$storehash,$coursehome,$caller) = @_;
4122: return unless (ref($storehash) eq 'HASH');
4123: my $outcome;
4124: if ($caller eq 'timeonly') {
4125: my $cids = '';
4126: foreach my $item (keys(%$storehash)) {
4127: $cids.=&escape($item).'&';
4128: }
4129: $cids=~s/\&$//;
4130: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4131: $coursehome);
4132: } else {
4133: my $items = '';
4134: foreach my $item (keys(%$storehash)) {
4135: $items.= &escape($item).'='.
4136: &freeze_escape($$storehash{$item}).'&';
4137: }
4138: $items=~s/\&$//;
4139: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4140: $coursehome);
4141: }
4142: if ($outcome eq 'unknown_cmd') {
4143: my $what;
4144: foreach my $cid (keys(%$storehash)) {
4145: $what .= &escape($cid).'=';
4146: foreach my $item ('description','inst_code','owner','type') {
4147: $what .= &escape($storehash->{$cid}{$item}).':';
4148: }
4149: $what =~ s/\:$/&/;
4150: }
4151: $what =~ s/\&$//;
4152: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4153: } else {
4154: return $outcome;
4155: }
4156: }
4157:
4158: sub courseiddump {
4159: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
4160: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
4161: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
4162: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
4163: my $as_hash = 1;
4164: my %returnhash;
4165: if (!$domfilter) { $domfilter=''; }
4166: my %libserv = &all_library();
4167: foreach my $tryserver (keys(%libserv)) {
4168: if ( ( $hostidflag == 1
4169: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4170: || (!defined($hostidflag)) ) {
4171:
4172: if (($domfilter eq '') ||
4173: (&host_domain($tryserver) eq $domfilter)) {
4174: my $rep;
4175: if (grep { $_ eq $tryserver } current_machine_ids()) {
4176: $rep = LONCAPA::Lond::dump_course_id_handler(
4177: join(":", (&host_domain($tryserver), $sincefilter,
4178: &escape($descfilter), &escape($instcodefilter),
4179: &escape($ownerfilter), &escape($coursefilter),
4180: &escape($typefilter), &escape($regexp_ok),
4181: $as_hash, &escape($selfenrollonly),
4182: &escape($catfilter), $showhidden, $caller,
4183: &escape($cloner), &escape($cc_clone), $cloneonly,
4184: &escape($createdbefore), &escape($createdafter),
4185: &escape($creationcontext), $domcloner)));
4186: } else {
4187: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4188: $sincefilter.':'.&escape($descfilter).':'.
4189: &escape($instcodefilter).':'.&escape($ownerfilter).
4190: ':'.&escape($coursefilter).':'.&escape($typefilter).
4191: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4192: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4193: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4194: &escape($cc_clone).':'.$cloneonly.':'.
4195: &escape($createdbefore).':'.&escape($createdafter).':'.
4196: &escape($creationcontext).':'.$domcloner,
4197: $tryserver);
4198: }
4199:
4200: my @pairs=split(/\&/,$rep);
4201: foreach my $item (@pairs) {
4202: my ($key,$value)=split(/\=/,$item,2);
4203: $key = &unescape($key);
4204: next if ($key =~ /^error: 2 /);
4205: my $result = &thaw_unescape($value);
4206: if (ref($result) eq 'HASH') {
4207: $returnhash{$key}=$result;
4208: } else {
4209: my @responses = split(/:/,$value);
4210: my @items = ('description','inst_code','owner','type');
4211: for (my $i=0; $i<@responses; $i++) {
4212: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
4213: }
4214: }
4215: }
4216: }
4217: }
4218: }
4219: return %returnhash;
4220: }
4221:
4222: sub courselastaccess {
4223: my ($cdom,$cnum,$hostidref) = @_;
4224: my %returnhash;
4225: if ($cdom && $cnum) {
4226: my $chome = &homeserver($cnum,$cdom);
4227: if ($chome ne 'no_host') {
4228: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4229: &extract_lastaccess(\%returnhash,$rep);
4230: }
4231: } else {
4232: if (!$cdom) { $cdom=''; }
4233: my %libserv = &all_library();
4234: foreach my $tryserver (keys(%libserv)) {
4235: if (ref($hostidref) eq 'ARRAY') {
4236: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4237: }
4238: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4239: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4240: &extract_lastaccess(\%returnhash,$rep);
4241: }
4242: }
4243: }
4244: return %returnhash;
4245: }
4246:
4247: sub extract_lastaccess {
4248: my ($returnhash,$rep) = @_;
4249: if (ref($returnhash) eq 'HASH') {
4250: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4251: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4252: $rep eq '') {
4253: my @pairs=split(/\&/,$rep);
4254: foreach my $item (@pairs) {
4255: my ($key,$value)=split(/\=/,$item,2);
4256: $key = &unescape($key);
4257: next if ($key =~ /^error: 2 /);
4258: $returnhash->{$key} = &thaw_unescape($value);
4259: }
4260: }
4261: }
4262: return;
4263: }
4264:
4265: # ---------------------------------------------------------- DC e-mail
4266:
4267: sub dcmailput {
4268: my ($domain,$msgid,$message,$server)=@_;
4269: my $status = &Apache::lonnet::critical(
4270: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4271: &escape($message),$server);
4272: return $status;
4273: }
4274:
4275: sub dcmaildump {
4276: my ($dom,$startdate,$enddate,$senders) = @_;
4277: my %returnhash=();
4278:
4279: if (defined(&domain($dom,'primary'))) {
4280: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4281: &escape($enddate).':';
4282: my @esc_senders=map { &escape($_)} @$senders;
4283: $cmd.=&escape(join('&',@esc_senders));
4284: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
4285: my ($key,$value) = split(/\=/,$line,2);
4286: if (($key) && ($value)) {
4287: $returnhash{&unescape($key)} = &unescape($value);
4288: }
4289: }
4290: }
4291: return %returnhash;
4292: }
4293: # ---------------------------------------------------------- Domain roles
4294:
4295: sub get_domain_roles {
4296: my ($dom,$roles,$startdate,$enddate)=@_;
4297: if ((!defined($startdate)) || ($startdate eq '')) {
4298: $startdate = '.';
4299: }
4300: if ((!defined($enddate)) || ($enddate eq '')) {
4301: $enddate = '.';
4302: }
4303: my $rolelist;
4304: if (ref($roles) eq 'ARRAY') {
4305: $rolelist = join('&',@{$roles});
4306: }
4307: my %personnel = ();
4308:
4309: my %servers = &get_servers($dom,'library');
4310: foreach my $tryserver (keys(%servers)) {
4311: %{$personnel{$tryserver}}=();
4312: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4313: &escape($startdate).':'.
4314: &escape($enddate).':'.
4315: &escape($rolelist), $tryserver))) {
4316: my ($key,$value) = split(/\=/,$line,2);
4317: if (($key) && ($value)) {
4318: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4319: }
4320: }
4321: }
4322: return %personnel;
4323: }
4324:
4325: # ----------------------------------------------------------- Interval timing
4326:
4327: {
4328: # Caches needed for speedup of navmaps
4329: # We don't want to cache this for very long at all (5 seconds at most)
4330: #
4331: # The user for whom we cache
4332: my $cachedkey='';
4333: # The cached times for this user
4334: my %cachedtimes=();
4335: # When this was last done
4336: my $cachedtime=();
4337:
4338: sub load_all_first_access {
4339: my ($uname,$udom)=@_;
4340: if (($cachedkey eq $uname.':'.$udom) &&
4341: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
4342: return;
4343: }
4344: $cachedtime=time;
4345: $cachedkey=$uname.':'.$udom;
4346: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
4347: }
4348:
4349: sub get_first_access {
4350: my ($type,$argsymb,$argmap)=@_;
4351: my ($symb,$courseid,$udom,$uname)=&whichuser();
4352: if ($argsymb) { $symb=$argsymb; }
4353: my ($map,$id,$res)=&decode_symb($symb);
4354: if ($argmap) { $map = $argmap; }
4355: if ($type eq 'course') {
4356: $res='course';
4357: } elsif ($type eq 'map') {
4358: $res=&symbread($map);
4359: } else {
4360: $res=$symb;
4361: }
4362: &load_all_first_access($uname,$udom);
4363: return $cachedtimes{"$courseid\0$res"};
4364: }
4365:
4366: sub set_first_access {
4367: my ($type,$interval)=@_;
4368: my ($symb,$courseid,$udom,$uname)=&whichuser();
4369: my ($map,$id,$res)=&decode_symb($symb);
4370: if ($type eq 'course') {
4371: $res='course';
4372: } elsif ($type eq 'map') {
4373: $res=&symbread($map);
4374: } else {
4375: $res=$symb;
4376: }
4377: $cachedkey='';
4378: my $firstaccess=&get_first_access($type,$symb,$map);
4379: if (!$firstaccess) {
4380: my $start = time;
4381: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4382: $udom,$uname);
4383: if ($putres eq 'ok') {
4384: &put('timerinterval',{"$courseid\0$res"=>$interval},
4385: $udom,$uname);
4386: &appenv(
4387: {
4388: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4389: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4390: }
4391: );
4392: }
4393: return $putres;
4394: }
4395: return 'already_set';
4396: }
4397: }
4398: # --------------------------------------------- Set Expire Date for Spreadsheet
4399:
4400: sub expirespread {
4401: my ($uname,$udom,$stype,$usymb)=@_;
4402: my $cid=$env{'request.course.id'};
4403: if ($cid) {
4404: my $now=time;
4405: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
4406: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4407: $env{'course.'.$cid.'.num'}.
4408: ':nohist_expirationdates:'.
4409: &escape($key).'='.$now,
4410: $env{'course.'.$cid.'.home'})
4411: }
4412: return 'ok';
4413: }
4414:
4415: # ----------------------------------------------------- Devalidate Spreadsheets
4416:
4417: sub devalidate {
4418: my ($symb,$uname,$udom)=@_;
4419: my $cid=$env{'request.course.id'};
4420: if ($cid) {
4421: # delete the stored spreadsheets for
4422: # - the student level sheet of this user in course's homespace
4423: # - the assessment level sheet for this resource
4424: # for this user in user's homespace
4425: # - current conditional state info
4426: my $key=$uname.':'.$udom.':';
4427: my $status=
4428: &del('nohist_calculatedsheets',
4429: [$key.'studentcalc:'],
4430: $env{'course.'.$cid.'.domain'},
4431: $env{'course.'.$cid.'.num'})
4432: .' '.
4433: &del('nohist_calculatedsheets_'.$cid,
4434: [$key.'assesscalc:'.$symb],$udom,$uname);
4435: unless ($status eq 'ok ok') {
4436: &logthis('Could not devalidate spreadsheet '.
4437: $uname.' at '.$udom.' for '.
4438: $symb.': '.$status);
4439: }
4440: &delenv('user.state.'.$cid);
4441: }
4442: }
4443:
4444: sub get_scalar {
4445: my ($string,$end) = @_;
4446: my $value;
4447: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4448: $value = $1;
4449: } elsif ($$string =~ s/^([^&]*?)&//) {
4450: $value = $1;
4451: }
4452: return &unescape($value);
4453: }
4454:
4455: sub array2str {
4456: my (@array) = @_;
4457: my $result=&arrayref2str(\@array);
4458: $result=~s/^__ARRAY_REF__//;
4459: $result=~s/__END_ARRAY_REF__$//;
4460: return $result;
4461: }
4462:
4463: sub arrayref2str {
4464: my ($arrayref) = @_;
4465: my $result='__ARRAY_REF__';
4466: foreach my $elem (@$arrayref) {
4467: if(ref($elem) eq 'ARRAY') {
4468: $result.=&arrayref2str($elem).'&';
4469: } elsif(ref($elem) eq 'HASH') {
4470: $result.=&hashref2str($elem).'&';
4471: } elsif(ref($elem)) {
4472: #print("Got a ref of ".(ref($elem))." skipping.");
4473: } else {
4474: $result.=&escape($elem).'&';
4475: }
4476: }
4477: $result=~s/\&$//;
4478: $result .= '__END_ARRAY_REF__';
4479: return $result;
4480: }
4481:
4482: sub hash2str {
4483: my (%hash) = @_;
4484: my $result=&hashref2str(\%hash);
4485: $result=~s/^__HASH_REF__//;
4486: $result=~s/__END_HASH_REF__$//;
4487: return $result;
4488: }
4489:
4490: sub hashref2str {
4491: my ($hashref)=@_;
4492: my $result='__HASH_REF__';
4493: foreach my $key (sort(keys(%$hashref))) {
4494: if (ref($key) eq 'ARRAY') {
4495: $result.=&arrayref2str($key).'=';
4496: } elsif (ref($key) eq 'HASH') {
4497: $result.=&hashref2str($key).'=';
4498: } elsif (ref($key)) {
4499: $result.='=';
4500: #print("Got a ref of ".(ref($key))." skipping.");
4501: } else {
4502: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4503: }
4504:
4505: if(ref($hashref->{$key}) eq 'ARRAY') {
4506: $result.=&arrayref2str($hashref->{$key}).'&';
4507: } elsif(ref($hashref->{$key}) eq 'HASH') {
4508: $result.=&hashref2str($hashref->{$key}).'&';
4509: } elsif(ref($hashref->{$key})) {
4510: $result.='&';
4511: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4512: } else {
4513: $result.=&escape($hashref->{$key}).'&';
4514: }
4515: }
4516: $result=~s/\&$//;
4517: $result .= '__END_HASH_REF__';
4518: return $result;
4519: }
4520:
4521: sub str2hash {
4522: my ($string)=@_;
4523: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4524: return %$hash;
4525: }
4526:
4527: sub str2hashref {
4528: my ($string) = @_;
4529:
4530: my %hash;
4531:
4532: if($string !~ /^__HASH_REF__/) {
4533: if (! ($string eq '' || !defined($string))) {
4534: $hash{'error'}='Not hash reference';
4535: }
4536: return (\%hash, $string);
4537: }
4538:
4539: $string =~ s/^__HASH_REF__//;
4540:
4541: while($string !~ /^__END_HASH_REF__/) {
4542: #key
4543: my $key='';
4544: if($string =~ /^__HASH_REF__/) {
4545: ($key, $string)=&str2hashref($string);
4546: if(defined($key->{'error'})) {
4547: $hash{'error'}='Bad data';
4548: return (\%hash, $string);
4549: }
4550: } elsif($string =~ /^__ARRAY_REF__/) {
4551: ($key, $string)=&str2arrayref($string);
4552: if($key->[0] eq 'Array reference error') {
4553: $hash{'error'}='Bad data';
4554: return (\%hash, $string);
4555: }
4556: } else {
4557: $string =~ s/^(.*?)=//;
4558: $key=&unescape($1);
4559: }
4560: $string =~ s/^=//;
4561:
4562: #value
4563: my $value='';
4564: if($string =~ /^__HASH_REF__/) {
4565: ($value, $string)=&str2hashref($string);
4566: if(defined($value->{'error'})) {
4567: $hash{'error'}='Bad data';
4568: return (\%hash, $string);
4569: }
4570: } elsif($string =~ /^__ARRAY_REF__/) {
4571: ($value, $string)=&str2arrayref($string);
4572: if($value->[0] eq 'Array reference error') {
4573: $hash{'error'}='Bad data';
4574: return (\%hash, $string);
4575: }
4576: } else {
4577: $value=&get_scalar(\$string,'__END_HASH_REF__');
4578: }
4579: $string =~ s/^&//;
4580:
4581: $hash{$key}=$value;
4582: }
4583:
4584: $string =~ s/^__END_HASH_REF__//;
4585:
4586: return (\%hash, $string);
4587: }
4588:
4589: sub str2array {
4590: my ($string)=@_;
4591: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4592: return @$array;
4593: }
4594:
4595: sub str2arrayref {
4596: my ($string) = @_;
4597: my @array;
4598:
4599: if($string !~ /^__ARRAY_REF__/) {
4600: if (! ($string eq '' || !defined($string))) {
4601: $array[0]='Array reference error';
4602: }
4603: return (\@array, $string);
4604: }
4605:
4606: $string =~ s/^__ARRAY_REF__//;
4607:
4608: while($string !~ /^__END_ARRAY_REF__/) {
4609: my $value='';
4610: if($string =~ /^__HASH_REF__/) {
4611: ($value, $string)=&str2hashref($string);
4612: if(defined($value->{'error'})) {
4613: $array[0] ='Array reference error';
4614: return (\@array, $string);
4615: }
4616: } elsif($string =~ /^__ARRAY_REF__/) {
4617: ($value, $string)=&str2arrayref($string);
4618: if($value->[0] eq 'Array reference error') {
4619: $array[0] ='Array reference error';
4620: return (\@array, $string);
4621: }
4622: } else {
4623: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4624: }
4625: $string =~ s/^&//;
4626:
4627: push(@array, $value);
4628: }
4629:
4630: $string =~ s/^__END_ARRAY_REF__//;
4631:
4632: return (\@array, $string);
4633: }
4634:
4635: # -------------------------------------------------------------------Temp Store
4636:
4637: sub tmpreset {
4638: my ($symb,$namespace,$domain,$stuname) = @_;
4639: if (!$symb) {
4640: $symb=&symbread();
4641: if (!$symb) { $symb= $env{'request.url'}; }
4642: }
4643: $symb=escape($symb);
4644:
4645: if (!$namespace) { $namespace=$env{'request.state'}; }
4646: $namespace=~s/\//\_/g;
4647: $namespace=~s/\W//g;
4648:
4649: if (!$domain) { $domain=$env{'user.domain'}; }
4650: if (!$stuname) { $stuname=$env{'user.name'}; }
4651: if ($domain eq 'public' && $stuname eq 'public') {
4652: $stuname=$ENV{'REMOTE_ADDR'};
4653: }
4654: my $path=LONCAPA::tempdir();
4655: my %hash;
4656: if (tie(%hash,'GDBM_File',
4657: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4658: &GDBM_WRCREAT(),0640)) {
4659: foreach my $key (keys(%hash)) {
4660: if ($key=~ /:$symb/) {
4661: delete($hash{$key});
4662: }
4663: }
4664: }
4665: }
4666:
4667: sub tmpstore {
4668: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4669:
4670: if (!$symb) {
4671: $symb=&symbread();
4672: if (!$symb) { $symb= $env{'request.url'}; }
4673: }
4674: $symb=escape($symb);
4675:
4676: if (!$namespace) {
4677: # I don't think we would ever want to store this for a course.
4678: # it seems this will only be used if we don't have a course.
4679: #$namespace=$env{'request.course.id'};
4680: #if (!$namespace) {
4681: $namespace=$env{'request.state'};
4682: #}
4683: }
4684: $namespace=~s/\//\_/g;
4685: $namespace=~s/\W//g;
4686: if (!$domain) { $domain=$env{'user.domain'}; }
4687: if (!$stuname) { $stuname=$env{'user.name'}; }
4688: if ($domain eq 'public' && $stuname eq 'public') {
4689: $stuname=$ENV{'REMOTE_ADDR'};
4690: }
4691: my $now=time;
4692: my %hash;
4693: my $path=LONCAPA::tempdir();
4694: if (tie(%hash,'GDBM_File',
4695: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4696: &GDBM_WRCREAT(),0640)) {
4697: $hash{"version:$symb"}++;
4698: my $version=$hash{"version:$symb"};
4699: my $allkeys='';
4700: foreach my $key (keys(%$storehash)) {
4701: $allkeys.=$key.':';
4702: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4703: }
4704: $hash{"$version:$symb:timestamp"}=$now;
4705: $allkeys.='timestamp';
4706: $hash{"$version:keys:$symb"}=$allkeys;
4707: if (untie(%hash)) {
4708: return 'ok';
4709: } else {
4710: return "error:$!";
4711: }
4712: } else {
4713: return "error:$!";
4714: }
4715: }
4716:
4717: # -----------------------------------------------------------------Temp Restore
4718:
4719: sub tmprestore {
4720: my ($symb,$namespace,$domain,$stuname) = @_;
4721:
4722: if (!$symb) {
4723: $symb=&symbread();
4724: if (!$symb) { $symb= $env{'request.url'}; }
4725: }
4726: $symb=escape($symb);
4727:
4728: if (!$namespace) { $namespace=$env{'request.state'}; }
4729:
4730: if (!$domain) { $domain=$env{'user.domain'}; }
4731: if (!$stuname) { $stuname=$env{'user.name'}; }
4732: if ($domain eq 'public' && $stuname eq 'public') {
4733: $stuname=$ENV{'REMOTE_ADDR'};
4734: }
4735: my %returnhash;
4736: $namespace=~s/\//\_/g;
4737: $namespace=~s/\W//g;
4738: my %hash;
4739: my $path=LONCAPA::tempdir();
4740: if (tie(%hash,'GDBM_File',
4741: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4742: &GDBM_READER(),0640)) {
4743: my $version=$hash{"version:$symb"};
4744: $returnhash{'version'}=$version;
4745: my $scope;
4746: for ($scope=1;$scope<=$version;$scope++) {
4747: my $vkeys=$hash{"$scope:keys:$symb"};
4748: my @keys=split(/:/,$vkeys);
4749: my $key;
4750: $returnhash{"$scope:keys"}=$vkeys;
4751: foreach $key (@keys) {
4752: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4753: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4754: }
4755: }
4756: if (!(untie(%hash))) {
4757: return "error:$!";
4758: }
4759: } else {
4760: return "error:$!";
4761: }
4762: return %returnhash;
4763: }
4764:
4765: # ----------------------------------------------------------------------- Store
4766:
4767: sub store {
4768: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4769: my $home='';
4770:
4771: if ($stuname) { $home=&homeserver($stuname,$domain); }
4772:
4773: $symb=&symbclean($symb);
4774: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4775:
4776: if (!$domain) { $domain=$env{'user.domain'}; }
4777: if (!$stuname) { $stuname=$env{'user.name'}; }
4778:
4779: &devalidate($symb,$stuname,$domain);
4780:
4781: $symb=escape($symb);
4782: if (!$namespace) {
4783: unless ($namespace=$env{'request.course.id'}) {
4784: return '';
4785: }
4786: }
4787: if (!$home) { $home=$env{'user.home'}; }
4788:
4789: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4790: $$storehash{'host'}=$perlvar{'lonHostID'};
4791:
4792: my $namevalue='';
4793: foreach my $key (keys(%$storehash)) {
4794: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4795: }
4796: $namevalue=~s/\&$//;
4797: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4798: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4799: }
4800:
4801: # -------------------------------------------------------------- Critical Store
4802:
4803: sub cstore {
4804: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4805: my $home='';
4806:
4807: if ($stuname) { $home=&homeserver($stuname,$domain); }
4808:
4809: $symb=&symbclean($symb);
4810: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4811:
4812: if (!$domain) { $domain=$env{'user.domain'}; }
4813: if (!$stuname) { $stuname=$env{'user.name'}; }
4814:
4815: &devalidate($symb,$stuname,$domain);
4816:
4817: $symb=escape($symb);
4818: if (!$namespace) {
4819: unless ($namespace=$env{'request.course.id'}) {
4820: return '';
4821: }
4822: }
4823: if (!$home) { $home=$env{'user.home'}; }
4824:
4825: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4826: $$storehash{'host'}=$perlvar{'lonHostID'};
4827:
4828: my $namevalue='';
4829: foreach my $key (keys(%$storehash)) {
4830: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4831: }
4832: $namevalue=~s/\&$//;
4833: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4834: return critical
4835: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4836: }
4837:
4838: # --------------------------------------------------------------------- Restore
4839:
4840: sub restore {
4841: my ($symb,$namespace,$domain,$stuname) = @_;
4842: my $home='';
4843:
4844: if ($stuname) { $home=&homeserver($stuname,$domain); }
4845:
4846: if (!$symb) {
4847: return if ($namespace eq 'courserequests');
4848: unless ($symb=escape(&symbread())) { return ''; }
4849: } else {
4850: unless ($namespace eq 'courserequests') {
4851: $symb=&escape(&symbclean($symb));
4852: }
4853: }
4854: if (!$namespace) {
4855: unless ($namespace=$env{'request.course.id'}) {
4856: return '';
4857: }
4858: }
4859: if (!$domain) { $domain=$env{'user.domain'}; }
4860: if (!$stuname) { $stuname=$env{'user.name'}; }
4861: if (!$home) { $home=$env{'user.home'}; }
4862: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4863:
4864: my %returnhash=();
4865: foreach my $line (split(/\&/,$answer)) {
4866: my ($name,$value)=split(/\=/,$line);
4867: $returnhash{&unescape($name)}=&thaw_unescape($value);
4868: }
4869: my $version;
4870: for ($version=1;$version<=$returnhash{'version'};$version++) {
4871: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4872: $returnhash{$item}=$returnhash{$version.':'.$item};
4873: }
4874: }
4875: return %returnhash;
4876: }
4877:
4878: # ---------------------------------------------------------- Course Description
4879: #
4880: #
4881:
4882: sub coursedescription {
4883: my ($courseid,$args)=@_;
4884: $courseid=~s/^\///;
4885: $courseid=~s/\_/\//g;
4886: my ($cdomain,$cnum)=split(/\//,$courseid);
4887: my $chome=&homeserver($cnum,$cdomain);
4888: my $normalid=$cdomain.'_'.$cnum;
4889: # need to always cache even if we get errors otherwise we keep
4890: # trying and trying and trying to get the course description.
4891: my %envhash=();
4892: my %returnhash=();
4893:
4894: my $expiretime=600;
4895: if ($env{'request.course.id'} eq $normalid) {
4896: $expiretime=120;
4897: }
4898:
4899: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4900: if (!$args->{'freshen_cache'}
4901: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4902: foreach my $key (keys(%env)) {
4903: next if ($key !~ /^\Q$prefix\E(.*)/);
4904: my ($setting) = $1;
4905: $returnhash{$setting} = $env{$key};
4906: }
4907: return %returnhash;
4908: }
4909:
4910: # get the data again
4911:
4912: if (!$args->{'one_time'}) {
4913: $envhash{'course.'.$normalid.'.last_cache'}=time;
4914: }
4915:
4916: if ($chome ne 'no_host') {
4917: %returnhash=&dump('environment',$cdomain,$cnum);
4918: if (!exists($returnhash{'con_lost'})) {
4919: my $username = $env{'user.name'}; # Defult username
4920: if(defined $args->{'user'}) {
4921: $username = $args->{'user'};
4922: }
4923: $returnhash{'home'}= $chome;
4924: $returnhash{'domain'} = $cdomain;
4925: $returnhash{'num'} = $cnum;
4926: if (!defined($returnhash{'type'})) {
4927: $returnhash{'type'} = 'Course';
4928: }
4929: while (my ($name,$value) = each %returnhash) {
4930: $envhash{'course.'.$normalid.'.'.$name}=$value;
4931: }
4932: $returnhash{'url'}=&clutter($returnhash{'url'});
4933: $returnhash{'fn'}=LONCAPA::tempdir() .
4934: $username.'_'.$cdomain.'_'.$cnum;
4935: $envhash{'course.'.$normalid.'.home'}=$chome;
4936: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4937: $envhash{'course.'.$normalid.'.num'}=$cnum;
4938: }
4939: }
4940: if (!$args->{'one_time'}) {
4941: &appenv(\%envhash);
4942: }
4943: return %returnhash;
4944: }
4945:
4946: sub update_released_required {
4947: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4948: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4949: $cid = $env{'request.course.id'};
4950: $cdom = $env{'course.'.$cid.'.domain'};
4951: $cnum = $env{'course.'.$cid.'.num'};
4952: $chome = $env{'course.'.$cid.'.home'};
4953: }
4954: if ($needsrelease) {
4955: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4956: my $needsupdate;
4957: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4958: $needsupdate = 1;
4959: } else {
4960: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4961: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4962: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4963: $needsupdate = 1;
4964: }
4965: }
4966: if ($needsupdate) {
4967: my %needshash = (
4968: 'internal.releaserequired' => $needsrelease,
4969: );
4970: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4971: if ($putresult eq 'ok') {
4972: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4973: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4974: if (ref($crsinfo{$cid}) eq 'HASH') {
4975: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4976: &courseidput($cdom,\%crsinfo,$chome,'notime');
4977: }
4978: }
4979: }
4980: }
4981: return;
4982: }
4983:
4984: # -------------------------------------------------See if a user is privileged
4985:
4986: sub privileged {
4987: my ($username,$domain,$possdomains,$possroles)=@_;
4988: my $now = time;
4989: my $roles;
4990: if (ref($possroles) eq 'ARRAY') {
4991: $roles = $possroles;
4992: } else {
4993: $roles = ['dc','su'];
4994: }
4995: if (ref($possdomains) eq 'ARRAY') {
4996: my %privileged = &privileged_by_domain($possdomains,$roles);
4997: foreach my $dom (@{$possdomains}) {
4998: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
4999: (ref($privileged{$dom}) eq 'HASH')) {
5000: foreach my $role (@{$roles}) {
5001: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5002: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5003: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5004: return 1 unless (($end && $end < $now) ||
5005: ($start && $start > $now));
5006: }
5007: }
5008: }
5009: }
5010: }
5011: } else {
5012: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5013: my $now = time;
5014:
5015: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
5016: my ($trole, $tend, $tstart) = split(/_/, $role);
5017: if (grep(/^\Q$trole\E$/,@{$roles})) {
5018: return 1 unless ($tend && $tend < $now)
5019: or ($tstart && $tstart > $now);
5020: }
5021: }
5022: }
5023: return 0;
5024: }
5025:
5026: sub privileged_by_domain {
5027: my ($domains,$roles) = @_;
5028: my %privileged = ();
5029: my $cachetime = 60*60*24;
5030: my $now = time;
5031: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5032: return %privileged;
5033: }
5034: foreach my $dom (@{$domains}) {
5035: next if (ref($privileged{$dom}) eq 'HASH');
5036: my $needroles;
5037: foreach my $role (@{$roles}) {
5038: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5039: if (defined($cached)) {
5040: if (ref($result) eq 'HASH') {
5041: $privileged{$dom}{$role} = $result;
5042: }
5043: } else {
5044: $needroles = 1;
5045: }
5046: }
5047: if ($needroles) {
5048: my %dompersonnel = &get_domain_roles($dom,$roles);
5049: $privileged{$dom} = {};
5050: foreach my $server (keys(%dompersonnel)) {
5051: if (ref($dompersonnel{$server}) eq 'HASH') {
5052: foreach my $item (keys(%{$dompersonnel{$server}})) {
5053: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5054: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5055: next if ($end && $end < $now);
5056: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5057: $dompersonnel{$server}{$item};
5058: }
5059: }
5060: }
5061: if (ref($privileged{$dom}) eq 'HASH') {
5062: foreach my $role (@{$roles}) {
5063: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5064: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5065: } else {
5066: my %hash = ();
5067: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5068: }
5069: }
5070: }
5071: }
5072: }
5073: return %privileged;
5074: }
5075:
5076: # -------------------------------------------------------- Get user privileges
5077:
5078: sub rolesinit {
5079: my ($domain, $username) = @_;
5080: my %userroles = ('user.login.time' => time);
5081: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5082:
5083: # firstaccess and timerinterval are related to timed maps/resources.
5084: # also, blocking can be triggered by an activating timer
5085: # it's saved in the user's %env.
5086: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5087: my %timerinterval = &dump('timerinterval', $domain, $username);
5088: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5089: %timerintchk, %timerintenv);
5090:
5091: foreach my $key (keys(%firstaccess)) {
5092: my ($cid, $rest) = split(/\0/, $key);
5093: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5094: }
5095:
5096: foreach my $key (keys(%timerinterval)) {
5097: my ($cid,$rest) = split(/\0/,$key);
5098: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5099: }
5100:
5101: my %allroles=();
5102: my %allgroups=();
5103:
5104: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5105: my $role = $rolesdump{$area};
5106: $area =~ s/\_\w\w$//;
5107:
5108: my ($trole, $tend, $tstart, $group_privs);
5109:
5110: if ($role =~ /^cr/) {
5111: # Custom role, defined by a user
5112: # e.g., user.role.cr/msu/smith/mynewrole
5113: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5114: $trole = $1;
5115: ($tend, $tstart) = split('_', $2);
5116: } else {
5117: $trole = $role;
5118: }
5119: } elsif ($role =~ m|^gr/|) {
5120: # Role of member in a group, defined within a course/community
5121: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5122: ($trole, $tend, $tstart) = split(/_/, $role);
5123: next if $tstart eq '-1';
5124: ($trole, $group_privs) = split(/\//, $trole);
5125: $group_privs = &unescape($group_privs);
5126: } else {
5127: # Just a normal role, defined in roles.tab
5128: ($trole, $tend, $tstart) = split(/_/,$role);
5129: }
5130:
5131: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5132: $username);
5133: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5134:
5135: # role expired or not available yet?
5136: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5137: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5138:
5139: next if $area eq '' or $trole eq '';
5140:
5141: my $spec = "$trole.$area";
5142: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5143:
5144: if ($trole =~ /^cr\//) {
5145: # Custom role, defined by a user
5146: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5147: } elsif ($trole eq 'gr') {
5148: # Role of a member in a group, defined within a course/community
5149: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5150: next;
5151: } else {
5152: # Normal role, defined in roles.tab
5153: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5154: }
5155:
5156: my $cid = $tdomain.'_'.$trest;
5157: unless ($firstaccchk{$cid}) {
5158: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5159: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5160: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5161: $coursetimerstarts{$cid}{$item};
5162: }
5163: }
5164: $firstaccchk{$cid} = 1;
5165: }
5166: unless ($timerintchk{$cid}) {
5167: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5168: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5169: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5170: $coursetimerintervals{$cid}{$item};
5171: }
5172: }
5173: $timerintchk{$cid} = 1;
5174: }
5175: }
5176:
5177: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5178: \%allroles, \%allgroups);
5179: $env{'user.adv'} = $userroles{'user.adv'};
5180:
5181: return (\%userroles,\%firstaccenv,\%timerintenv);
5182: }
5183:
5184: sub set_arearole {
5185: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5186: unless ($nolog) {
5187: # log the associated role with the area
5188: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5189: }
5190: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
5191: }
5192:
5193: sub custom_roleprivs {
5194: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5195: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5196: my $homsvr=homeserver($rauthor,$rdomain);
5197: if (&hostname($homsvr) ne '') {
5198: my ($rdummy,$roledef)=
5199: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5200: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5201: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5202: if (defined($syspriv)) {
5203: if ($trest =~ /^$match_community$/) {
5204: $syspriv =~ s/bre\&S//;
5205: }
5206: $$allroles{'cm./'}.=':'.$syspriv;
5207: $$allroles{$spec.'./'}.=':'.$syspriv;
5208: }
5209: if ($tdomain ne '') {
5210: if (defined($dompriv)) {
5211: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5212: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5213: }
5214: if (($trest ne '') && (defined($coursepriv))) {
5215: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5216: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5217: }
5218: }
5219: }
5220: }
5221: }
5222:
5223: sub group_roleprivs {
5224: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5225: my $access = 1;
5226: my $now = time;
5227: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5228: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5229: if ($access) {
5230: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
5231: $$allgroups{$course}{$group} .=':'.$group_privs;
5232: }
5233: }
5234:
5235: sub standard_roleprivs {
5236: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5237: if (defined($pr{$trole.':s'})) {
5238: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5239: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5240: }
5241: if ($tdomain ne '') {
5242: if (defined($pr{$trole.':d'})) {
5243: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5244: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5245: }
5246: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5247: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5248: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5249: }
5250: }
5251: }
5252:
5253: sub set_userprivs {
5254: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
5255: my $author=0;
5256: my $adv=0;
5257: my %grouproles = ();
5258: if (keys(%{$allgroups}) > 0) {
5259: my @groupkeys;
5260: foreach my $role (keys(%{$allroles})) {
5261: push(@groupkeys,$role);
5262: }
5263: if (ref($groups_roles) eq 'HASH') {
5264: foreach my $key (keys(%{$groups_roles})) {
5265: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5266: push(@groupkeys,$key);
5267: }
5268: }
5269: }
5270: if (@groupkeys > 0) {
5271: foreach my $role (@groupkeys) {
5272: my ($trole,$area,$sec,$extendedarea);
5273: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5274: $trole = $1;
5275: $area = $2;
5276: $sec = $3;
5277: $extendedarea = $area.$sec;
5278: if (exists($$allgroups{$area})) {
5279: foreach my $group (keys(%{$$allgroups{$area}})) {
5280: my $spec = $trole.'.'.$extendedarea;
5281: $grouproles{$spec.'.'.$area.'/'.$group} =
5282: $$allgroups{$area}{$group};
5283: }
5284: }
5285: }
5286: }
5287: }
5288: }
5289: foreach my $group (keys(%grouproles)) {
5290: $$allroles{$group} = $grouproles{$group};
5291: }
5292: foreach my $role (keys(%{$allroles})) {
5293: my %thesepriv;
5294: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
5295: foreach my $item (split(/:/,$$allroles{$role})) {
5296: if ($item ne '') {
5297: my ($privilege,$restrictions)=split(/&/,$item);
5298: if ($restrictions eq '') {
5299: $thesepriv{$privilege}='F';
5300: } elsif ($thesepriv{$privilege} ne 'F') {
5301: $thesepriv{$privilege}.=$restrictions;
5302: }
5303: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5304: }
5305: }
5306: my $thesestr='';
5307: foreach my $priv (sort(keys(%thesepriv))) {
5308: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5309: }
5310: $userroles->{'user.priv.'.$role} = $thesestr;
5311: }
5312: return ($author,$adv);
5313: }
5314:
5315: sub role_status {
5316: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
5317: my @pwhere = ();
5318: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5319: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5320: unless (!defined($$role) || $$role eq '') {
5321: $$where=join('.',@pwhere);
5322: $$trolecode=$$role.'.'.$$where;
5323: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5324: $$tstatus='is';
5325: if ($$tstart && $$tstart>$update) {
5326: $$tstatus='future';
5327: if ($$tstart<$now) {
5328: if ($$tstart && $$tstart>$refresh) {
5329: if (($$where ne '') && ($$role ne '')) {
5330: my (%allroles,%allgroups,$group_privs,
5331: %groups_roles,@rolecodes);
5332: my %userroles = (
5333: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5334: );
5335: @rolecodes = ('cm');
5336: my $spec=$$role.'.'.$$where;
5337: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5338: if ($$role =~ /^cr\//) {
5339: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
5340: push(@rolecodes,'cr');
5341: } elsif ($$role eq 'gr') {
5342: push(@rolecodes,$$role);
5343: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5344: $env{'user.name'});
5345: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
5346: (undef,my $group_privs) = split(/\//,$trole);
5347: $group_privs = &unescape($group_privs);
5348: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
5349: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
5350: &get_groups_roles($tdomain,$trest,
5351: \%course_roles,\@rolecodes,
5352: \%groups_roles);
5353: } else {
5354: push(@rolecodes,$$role);
5355: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5356: }
5357: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5358: &appenv(\%userroles,\@rolecodes);
5359: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5360: }
5361: }
5362: $$tstatus = 'is';
5363: }
5364: }
5365: if ($$tend) {
5366: if ($$tend<$update) {
5367: $$tstatus='expired';
5368: } elsif ($$tend<$now) {
5369: $$tstatus='will_not';
5370: }
5371: }
5372: }
5373: }
5374: }
5375:
5376: sub get_groups_roles {
5377: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5378: return unless((ref($cdom_courseroles) eq 'HASH') &&
5379: (ref($rolecodes) eq 'ARRAY') &&
5380: (ref($groups_roles) eq 'HASH'));
5381: if (keys(%{$cdom_courseroles}) > 0) {
5382: my ($cnum) = ($rest =~ /^($match_courseid)/);
5383: if ($cdom ne '' && $cnum ne '') {
5384: foreach my $key (keys(%{$cdom_courseroles})) {
5385: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5386: my $crsrole = $1;
5387: my $crssec = $2;
5388: if ($crsrole =~ /^cr/) {
5389: unless (grep(/^cr$/,@{$rolecodes})) {
5390: push(@{$rolecodes},'cr');
5391: }
5392: } else {
5393: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5394: push(@{$rolecodes},$crsrole);
5395: }
5396: }
5397: my $rolekey = "$crsrole./$cdom/$cnum";
5398: if ($crssec ne '') {
5399: $rolekey .= "/$crssec";
5400: }
5401: $rolekey .= './';
5402: $groups_roles->{$rolekey} = $rolecodes;
5403: }
5404: }
5405: }
5406: }
5407: return;
5408: }
5409:
5410: sub delete_env_groupprivs {
5411: my ($where,$courseroles,$possroles) = @_;
5412: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5413: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5414: unless (ref($courseroles->{$udom}) eq 'HASH') {
5415: %{$courseroles->{$udom}} =
5416: &get_my_roles('','','userroles',['active'],
5417: $possroles,[$udom],1);
5418: }
5419: if (ref($courseroles->{$udom}) eq 'HASH') {
5420: foreach my $item (keys(%{$courseroles->{$udom}})) {
5421: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5422: my $area = '/'.$cdom.'/'.$cnum;
5423: my $privkey = "user.priv.$crsrole.$area";
5424: if ($crssec ne '') {
5425: $privkey .= '/'.$crssec;
5426: }
5427: $privkey .= ".$area/$group";
5428: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5429: }
5430: }
5431: return;
5432: }
5433:
5434: sub check_adhoc_privs {
5435: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
5436: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
5437: my $setprivs;
5438: if ($env{$cckey}) {
5439: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
5440: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
5441: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
5442: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5443: $setprivs = 1;
5444: }
5445: } else {
5446: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5447: $setprivs = 1;
5448: }
5449: return $setprivs;
5450: }
5451:
5452: sub set_adhoc_privileges {
5453: # role can be cc or ca
5454: my ($dcdom,$pickedcourse,$role,$caller) = @_;
5455: my $area = '/'.$dcdom.'/'.$pickedcourse;
5456: my $spec = $role.'.'.$area;
5457: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5458: $env{'user.name'},1);
5459: my %ccrole = ();
5460: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5461: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5462: &appenv(\%userroles,[$role,'cm']);
5463: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5464: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5465: &appenv( {'request.role' => $spec,
5466: 'request.role.domain' => $dcdom,
5467: 'request.course.sec' => ''
5468: }
5469: );
5470: my $tadv=0;
5471: if (&allowed('adv') eq 'F') { $tadv=1; }
5472: &appenv({'request.role.adv' => $tadv});
5473: }
5474: }
5475:
5476: # --------------------------------------------------------------- get interface
5477:
5478: sub get {
5479: my ($namespace,$storearr,$udomain,$uname)=@_;
5480: my $items='';
5481: foreach my $item (@$storearr) {
5482: $items.=&escape($item).'&';
5483: }
5484: $items=~s/\&$//;
5485: if (!$udomain) { $udomain=$env{'user.domain'}; }
5486: if (!$uname) { $uname=$env{'user.name'}; }
5487: my $uhome=&homeserver($uname,$udomain);
5488:
5489: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
5490: my @pairs=split(/\&/,$rep);
5491: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5492: return @pairs;
5493: }
5494: my %returnhash=();
5495: my $i=0;
5496: foreach my $item (@$storearr) {
5497: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5498: $i++;
5499: }
5500: return %returnhash;
5501: }
5502:
5503: # --------------------------------------------------------------- del interface
5504:
5505: sub del {
5506: my ($namespace,$storearr,$udomain,$uname)=@_;
5507: my $items='';
5508: foreach my $item (@$storearr) {
5509: $items.=&escape($item).'&';
5510: }
5511:
5512: $items=~s/\&$//;
5513: if (!$udomain) { $udomain=$env{'user.domain'}; }
5514: if (!$uname) { $uname=$env{'user.name'}; }
5515: my $uhome=&homeserver($uname,$udomain);
5516: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
5517: }
5518:
5519: # -------------------------------------------------------------- dump interface
5520:
5521: sub unserialize {
5522: my ($rep, $escapedkeys) = @_;
5523:
5524: return {} if $rep =~ /^error/;
5525:
5526: my %returnhash=();
5527: foreach my $item (split /\&/, $rep) {
5528: my ($key, $value) = split(/=/, $item, 2);
5529: $key = unescape($key) unless $escapedkeys;
5530: next if $key =~ /^error: 2 /;
5531: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5532: }
5533: #return %returnhash;
5534: return \%returnhash;
5535: }
5536:
5537: # see Lond::dump_with_regexp
5538: # if $escapedkeys hash keys won't get unescaped.
5539: sub dump {
5540: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
5541: if (!$udomain) { $udomain=$env{'user.domain'}; }
5542: if (!$uname) { $uname=$env{'user.name'}; }
5543: my $uhome=&homeserver($uname,$udomain);
5544:
5545: my $reply;
5546: if (grep { $_ eq $uhome } current_machine_ids()) {
5547: # user is hosted on this machine
5548: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
5549: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
5550: return %{unserialize($reply, $escapedkeys)};
5551: }
5552: if ($regexp) {
5553: $regexp=&escape($regexp);
5554: } else {
5555: $regexp='.';
5556: }
5557: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5558: my @pairs=split(/\&/,$rep);
5559: my %returnhash=();
5560: if (!($rep =~ /^error/ )) {
5561: foreach my $item (@pairs) {
5562: my ($key,$value)=split(/=/,$item,2);
5563: $key = unescape($key) unless $escapedkeys;
5564: #$key = &unescape($key);
5565: next if ($key =~ /^error: 2 /);
5566: $returnhash{$key}=&thaw_unescape($value);
5567: }
5568: }
5569: return %returnhash;
5570: }
5571:
5572:
5573: # --------------------------------------------------------- dumpstore interface
5574:
5575: sub dumpstore {
5576: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5577: # same as dump but keys must be escaped. They may contain colon separated
5578: # lists of values that may themself contain colons (e.g. symbs).
5579: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
5580: }
5581:
5582: # -------------------------------------------------------------- keys interface
5583:
5584: sub getkeys {
5585: my ($namespace,$udomain,$uname)=@_;
5586: if (!$udomain) { $udomain=$env{'user.domain'}; }
5587: if (!$uname) { $uname=$env{'user.name'}; }
5588: my $uhome=&homeserver($uname,$udomain);
5589: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5590: my @keyarray=();
5591: foreach my $key (split(/\&/,$rep)) {
5592: next if ($key =~ /^error: 2 /);
5593: push(@keyarray,&unescape($key));
5594: }
5595: return @keyarray;
5596: }
5597:
5598: # --------------------------------------------------------------- currentdump
5599: sub currentdump {
5600: my ($courseid,$sdom,$sname)=@_;
5601: $courseid = $env{'request.course.id'} if (! defined($courseid));
5602: $sdom = $env{'user.domain'} if (! defined($sdom));
5603: $sname = $env{'user.name'} if (! defined($sname));
5604: my $uhome = &homeserver($sname,$sdom);
5605: my $rep;
5606:
5607: if (grep { $_ eq $uhome } current_machine_ids()) {
5608: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5609: $courseid)));
5610: } else {
5611: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5612: }
5613:
5614: return if ($rep =~ /^(error:|no_such_host)/);
5615: #
5616: my %returnhash=();
5617: #
5618: if ($rep eq "unknown_cmd") {
5619: # an old lond will not know currentdump
5620: # Do a dump and make it look like a currentdump
5621: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5622: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5623: my %hash = @tmp;
5624: @tmp=();
5625: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5626: } else {
5627: my @pairs=split(/\&/,$rep);
5628: foreach my $pair (@pairs) {
5629: my ($key,$value)=split(/=/,$pair,2);
5630: my ($symb,$param) = split(/:/,$key);
5631: $returnhash{&unescape($symb)}->{&unescape($param)} =
5632: &thaw_unescape($value);
5633: }
5634: }
5635: return %returnhash;
5636: }
5637:
5638: sub convert_dump_to_currentdump{
5639: my %hash = %{shift()};
5640: my %returnhash;
5641: # Code ripped from lond, essentially. The only difference
5642: # here is the unescaping done by lonnet::dump(). Conceivably
5643: # we might run in to problems with parameter names =~ /^v\./
5644: while (my ($key,$value) = each(%hash)) {
5645: my ($v,$symb,$param) = split(/:/,$key);
5646: $symb = &unescape($symb);
5647: $param = &unescape($param);
5648: next if ($v eq 'version' || $symb eq 'keys');
5649: next if (exists($returnhash{$symb}) &&
5650: exists($returnhash{$symb}->{$param}) &&
5651: $returnhash{$symb}->{'v.'.$param} > $v);
5652: $returnhash{$symb}->{$param}=$value;
5653: $returnhash{$symb}->{'v.'.$param}=$v;
5654: }
5655: #
5656: # Remove all of the keys in the hashes which keep track of
5657: # the version of the parameter.
5658: while (my ($symb,$param_hash) = each(%returnhash)) {
5659: # use a foreach because we are going to delete from the hash.
5660: foreach my $key (keys(%$param_hash)) {
5661: delete($param_hash->{$key}) if ($key =~ /^v\./);
5662: }
5663: }
5664: return \%returnhash;
5665: }
5666:
5667: # ------------------------------------------------------ critical inc interface
5668:
5669: sub cinc {
5670: return &inc(@_,'critical');
5671: }
5672:
5673: # --------------------------------------------------------------- inc interface
5674:
5675: sub inc {
5676: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5677: if (!$udomain) { $udomain=$env{'user.domain'}; }
5678: if (!$uname) { $uname=$env{'user.name'}; }
5679: my $uhome=&homeserver($uname,$udomain);
5680: my $items='';
5681: if (! ref($store)) {
5682: # got a single value, so use that instead
5683: $items = &escape($store).'=&';
5684: } elsif (ref($store) eq 'SCALAR') {
5685: $items = &escape($$store).'=&';
5686: } elsif (ref($store) eq 'ARRAY') {
5687: $items = join('=&',map {&escape($_);} @{$store});
5688: } elsif (ref($store) eq 'HASH') {
5689: while (my($key,$value) = each(%{$store})) {
5690: $items.= &escape($key).'='.&escape($value).'&';
5691: }
5692: }
5693: $items=~s/\&$//;
5694: if ($critical) {
5695: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5696: } else {
5697: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5698: }
5699: }
5700:
5701: # --------------------------------------------------------------- put interface
5702:
5703: sub put {
5704: my ($namespace,$storehash,$udomain,$uname)=@_;
5705: if (!$udomain) { $udomain=$env{'user.domain'}; }
5706: if (!$uname) { $uname=$env{'user.name'}; }
5707: my $uhome=&homeserver($uname,$udomain);
5708: my $items='';
5709: foreach my $item (keys(%$storehash)) {
5710: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5711: }
5712: $items=~s/\&$//;
5713: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5714: }
5715:
5716: # ------------------------------------------------------------ newput interface
5717:
5718: sub newput {
5719: my ($namespace,$storehash,$udomain,$uname)=@_;
5720: if (!$udomain) { $udomain=$env{'user.domain'}; }
5721: if (!$uname) { $uname=$env{'user.name'}; }
5722: my $uhome=&homeserver($uname,$udomain);
5723: my $items='';
5724: foreach my $key (keys(%$storehash)) {
5725: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5726: }
5727: $items=~s/\&$//;
5728: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5729: }
5730:
5731: # --------------------------------------------------------- putstore interface
5732:
5733: sub putstore {
5734: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5735: if (!$udomain) { $udomain=$env{'user.domain'}; }
5736: if (!$uname) { $uname=$env{'user.name'}; }
5737: my $uhome=&homeserver($uname,$udomain);
5738: my $items='';
5739: foreach my $key (keys(%$storehash)) {
5740: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5741: }
5742: $items=~s/\&$//;
5743: my $esc_symb=&escape($symb);
5744: my $esc_v=&escape($version);
5745: my $reply =
5746: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5747: $uhome);
5748: if ($reply eq 'unknown_cmd') {
5749: # gfall back to way things use to be done
5750: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5751: $uname);
5752: }
5753: return $reply;
5754: }
5755:
5756: sub old_putstore {
5757: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5758: if (!$udomain) { $udomain=$env{'user.domain'}; }
5759: if (!$uname) { $uname=$env{'user.name'}; }
5760: my $uhome=&homeserver($uname,$udomain);
5761: my %newstorehash;
5762: foreach my $item (keys(%$storehash)) {
5763: my $key = $version.':'.&escape($symb).':'.$item;
5764: $newstorehash{$key} = $storehash->{$item};
5765: }
5766: my $items='';
5767: my %allitems = ();
5768: foreach my $item (keys(%newstorehash)) {
5769: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5770: my $key = $1.':keys:'.$2;
5771: $allitems{$key} .= $3.':';
5772: }
5773: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5774: }
5775: foreach my $item (keys(%allitems)) {
5776: $allitems{$item} =~ s/\:$//;
5777: $items.= $item.'='.$allitems{$item}.'&';
5778: }
5779: $items=~s/\&$//;
5780: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5781: }
5782:
5783: # ------------------------------------------------------ critical put interface
5784:
5785: sub cput {
5786: my ($namespace,$storehash,$udomain,$uname)=@_;
5787: if (!$udomain) { $udomain=$env{'user.domain'}; }
5788: if (!$uname) { $uname=$env{'user.name'}; }
5789: my $uhome=&homeserver($uname,$udomain);
5790: my $items='';
5791: foreach my $item (keys(%$storehash)) {
5792: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5793: }
5794: $items=~s/\&$//;
5795: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5796: }
5797:
5798: # -------------------------------------------------------------- eget interface
5799:
5800: sub eget {
5801: my ($namespace,$storearr,$udomain,$uname)=@_;
5802: my $items='';
5803: foreach my $item (@$storearr) {
5804: $items.=&escape($item).'&';
5805: }
5806: $items=~s/\&$//;
5807: if (!$udomain) { $udomain=$env{'user.domain'}; }
5808: if (!$uname) { $uname=$env{'user.name'}; }
5809: my $uhome=&homeserver($uname,$udomain);
5810: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5811: my @pairs=split(/\&/,$rep);
5812: my %returnhash=();
5813: my $i=0;
5814: foreach my $item (@$storearr) {
5815: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5816: $i++;
5817: }
5818: return %returnhash;
5819: }
5820:
5821: # ------------------------------------------------------------ tmpput interface
5822: sub tmpput {
5823: my ($storehash,$server,$context)=@_;
5824: my $items='';
5825: foreach my $item (keys(%$storehash)) {
5826: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5827: }
5828: $items=~s/\&$//;
5829: if (defined($context)) {
5830: $items .= ':'.&escape($context);
5831: }
5832: return &reply("tmpput:$items",$server);
5833: }
5834:
5835: # ------------------------------------------------------------ tmpget interface
5836: sub tmpget {
5837: my ($token,$server)=@_;
5838: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5839: my $rep=&reply("tmpget:$token",$server);
5840: my %returnhash;
5841: foreach my $item (split(/\&/,$rep)) {
5842: my ($key,$value)=split(/=/,$item);
5843: next if ($key =~ /^error: 2 /);
5844: $returnhash{&unescape($key)}=&thaw_unescape($value);
5845: }
5846: return %returnhash;
5847: }
5848:
5849: # ------------------------------------------------------------ tmpdel interface
5850: sub tmpdel {
5851: my ($token,$server)=@_;
5852: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5853: return &reply("tmpdel:$token",$server);
5854: }
5855:
5856: # ------------------------------------------------------------ get_timebased_id
5857:
5858: sub get_timebased_id {
5859: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5860: $maxtries) = @_;
5861: my ($newid,$error,$dellock);
5862: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5863: return ('','ok','invalid call to get suffix');
5864: }
5865:
5866: # set defaults for any optional args for which values were not supplied
5867: if ($who eq '') {
5868: $who = $env{'user.name'}.':'.$env{'user.domain'};
5869: }
5870: if (!$locktries) {
5871: $locktries = 3;
5872: }
5873: if (!$maxtries) {
5874: $maxtries = 10;
5875: }
5876:
5877: if (($cdom eq '') || ($cnum eq '')) {
5878: if ($env{'request.course.id'}) {
5879: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5880: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5881: }
5882: if (($cdom eq '') || ($cnum eq '')) {
5883: return ('','ok','call to get suffix not in course context');
5884: }
5885: }
5886:
5887: # construct locking item
5888: my $lockhash = {
5889: $prefix."\0".'locked_'.$keyid => $who,
5890: };
5891: my $tries = 0;
5892:
5893: # attempt to get lock on nohist_$namespace file
5894: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5895: while (($gotlock ne 'ok') && $tries <$locktries) {
5896: $tries ++;
5897: sleep 1;
5898: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5899: }
5900:
5901: # attempt to get unique identifier, based on current timestamp
5902: if ($gotlock eq 'ok') {
5903: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5904: my $id = time;
5905: $newid = $id;
5906: my $idtries = 0;
5907: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5908: if ($idtype eq 'concat') {
5909: $newid = $id.$idtries;
5910: } else {
5911: $newid ++;
5912: }
5913: $idtries ++;
5914: }
5915: if (!exists($inuse{$prefix."\0".$newid})) {
5916: my %new_item = (
5917: $prefix."\0".$newid => $who,
5918: );
5919: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5920: $cdom,$cnum);
5921: if ($putresult ne 'ok') {
5922: undef($newid);
5923: $error = 'error saving new item: '.$putresult;
5924: }
5925: } else {
5926: $error = ('error: no unique suffix available for the new item ');
5927: }
5928: # remove lock
5929: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5930: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5931: } else {
5932: $error = "error: could not obtain lockfile\n";
5933: $dellock = 'ok';
5934: }
5935: return ($newid,$dellock,$error);
5936: }
5937:
5938: # -------------------------------------------------- portfolio access checking
5939:
5940: sub portfolio_access {
5941: my ($requrl) = @_;
5942: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5943: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5944: if ($result) {
5945: my %setters;
5946: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5947: my ($startblock,$endblock) =
5948: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5949: if ($startblock && $endblock) {
5950: return 'B';
5951: }
5952: } else {
5953: my ($startblock,$endblock) =
5954: &Apache::loncommon::blockcheck(\%setters,'port');
5955: if ($startblock && $endblock) {
5956: return 'B';
5957: }
5958: }
5959: }
5960: if ($result eq 'ok') {
5961: return 'F';
5962: } elsif ($result =~ /^[^:]+:guest_/) {
5963: return 'A';
5964: }
5965: return '';
5966: }
5967:
5968: sub get_portfolio_access {
5969: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5970:
5971: if (!ref($access_hash)) {
5972: my $current_perms = &get_portfile_permissions($udom,$unum);
5973: my %access_controls = &get_access_controls($current_perms,$group,
5974: $file_name);
5975: $access_hash = $access_controls{$file_name};
5976: }
5977:
5978: my ($public,$guest,@domains,@users,@courses,@groups);
5979: my $now = time;
5980: if (ref($access_hash) eq 'HASH') {
5981: foreach my $key (keys(%{$access_hash})) {
5982: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5983: if ($start > $now) {
5984: next;
5985: }
5986: if ($end && $end<$now) {
5987: next;
5988: }
5989: if ($scope eq 'public') {
5990: $public = $key;
5991: last;
5992: } elsif ($scope eq 'guest') {
5993: $guest = $key;
5994: } elsif ($scope eq 'domains') {
5995: push(@domains,$key);
5996: } elsif ($scope eq 'users') {
5997: push(@users,$key);
5998: } elsif ($scope eq 'course') {
5999: push(@courses,$key);
6000: } elsif ($scope eq 'group') {
6001: push(@groups,$key);
6002: }
6003: }
6004: if ($public) {
6005: return 'ok';
6006: }
6007: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6008: if ($guest) {
6009: return $guest;
6010: }
6011: } else {
6012: if (@domains > 0) {
6013: foreach my $domkey (@domains) {
6014: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6015: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6016: return 'ok';
6017: }
6018: }
6019: }
6020: }
6021: if (@users > 0) {
6022: foreach my $userkey (@users) {
6023: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6024: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6025: if (ref($item) eq 'HASH') {
6026: if (($item->{'uname'} eq $env{'user.name'}) &&
6027: ($item->{'udom'} eq $env{'user.domain'})) {
6028: return 'ok';
6029: }
6030: }
6031: }
6032: }
6033: }
6034: }
6035: my %roleshash;
6036: my @courses_and_groups = @courses;
6037: push(@courses_and_groups,@groups);
6038: if (@courses_and_groups > 0) {
6039: my (%allgroups,%allroles);
6040: my ($start,$end,$role,$sec,$group);
6041: foreach my $envkey (%env) {
6042: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
6043: my $cid = $2.'_'.$3;
6044: if ($1 eq 'gr') {
6045: $group = $4;
6046: $allgroups{$cid}{$group} = $env{$envkey};
6047: } else {
6048: if ($4 eq '') {
6049: $sec = 'none';
6050: } else {
6051: $sec = $4;
6052: }
6053: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6054: }
6055: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
6056: my $cid = $2.'_'.$3;
6057: if ($4 eq '') {
6058: $sec = 'none';
6059: } else {
6060: $sec = $4;
6061: }
6062: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6063: }
6064: }
6065: if (keys(%allroles) == 0) {
6066: return;
6067: }
6068: foreach my $key (@courses_and_groups) {
6069: my %content = %{$$access_hash{$key}};
6070: my $cnum = $content{'number'};
6071: my $cdom = $content{'domain'};
6072: my $cid = $cdom.'_'.$cnum;
6073: if (!exists($allroles{$cid})) {
6074: next;
6075: }
6076: foreach my $role_id (keys(%{$content{'roles'}})) {
6077: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6078: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6079: my @status = @{$content{'roles'}{$role_id}{'access'}};
6080: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6081: foreach my $role (keys(%{$allroles{$cid}})) {
6082: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6083: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6084: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6085: if (grep/^all$/,@sections) {
6086: return 'ok';
6087: } else {
6088: if (grep/^$sec$/,@sections) {
6089: return 'ok';
6090: }
6091: }
6092: }
6093: }
6094: if (keys(%{$allgroups{$cid}}) == 0) {
6095: if (grep/^none$/,@groups) {
6096: return 'ok';
6097: }
6098: } else {
6099: if (grep/^all$/,@groups) {
6100: return 'ok';
6101: }
6102: foreach my $group (keys(%{$allgroups{$cid}})) {
6103: if (grep/^$group$/,@groups) {
6104: return 'ok';
6105: }
6106: }
6107: }
6108: }
6109: }
6110: }
6111: }
6112: }
6113: if ($guest) {
6114: return $guest;
6115: }
6116: }
6117: }
6118: return;
6119: }
6120:
6121: sub course_group_datechecker {
6122: my ($dates,$now,$status) = @_;
6123: my ($start,$end) = split(/\./,$dates);
6124: if (!$start && !$end) {
6125: return 'ok';
6126: }
6127: if (grep/^active$/,@{$status}) {
6128: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6129: return 'ok';
6130: }
6131: }
6132: if (grep/^previous$/,@{$status}) {
6133: if ($end > $now ) {
6134: return 'ok';
6135: }
6136: }
6137: if (grep/^future$/,@{$status}) {
6138: if ($start > $now) {
6139: return 'ok';
6140: }
6141: }
6142: return;
6143: }
6144:
6145: sub parse_portfolio_url {
6146: my ($url) = @_;
6147:
6148: my ($type,$udom,$unum,$group,$file_name);
6149:
6150: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
6151: $type = 1;
6152: $udom = $1;
6153: $unum = $2;
6154: $file_name = $3;
6155: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
6156: $type = 2;
6157: $udom = $1;
6158: $unum = $2;
6159: $group = $3;
6160: $file_name = $3.'/'.$4;
6161: }
6162: if (wantarray) {
6163: return ($type,$udom,$unum,$file_name,$group);
6164: }
6165: return $type;
6166: }
6167:
6168: sub is_portfolio_url {
6169: my ($url) = @_;
6170: return scalar(&parse_portfolio_url($url));
6171: }
6172:
6173: sub is_portfolio_file {
6174: my ($file) = @_;
6175: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
6176: return 1;
6177: }
6178: return;
6179: }
6180:
6181: sub usertools_access {
6182: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
6183: my ($access,%tools);
6184: if ($context eq '') {
6185: $context = 'tools';
6186: }
6187: if ($context eq 'requestcourses') {
6188: %tools = (
6189: official => 1,
6190: unofficial => 1,
6191: community => 1,
6192: );
6193: } elsif ($context eq 'requestauthor') {
6194: %tools = (
6195: requestauthor => 1,
6196: );
6197: } else {
6198: %tools = (
6199: aboutme => 1,
6200: blog => 1,
6201: webdav => 1,
6202: portfolio => 1,
6203: );
6204: }
6205: return if (!defined($tools{$tool}));
6206:
6207: if ((!defined($udom)) || (!defined($uname))) {
6208: $udom = $env{'user.domain'};
6209: $uname = $env{'user.name'};
6210: }
6211:
6212: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6213: if ($action ne 'reload') {
6214: if ($context eq 'requestcourses') {
6215: return $env{'environment.canrequest.'.$tool};
6216: } elsif ($context eq 'requestauthor') {
6217: return $env{'environment.canrequest.author'};
6218: } else {
6219: return $env{'environment.availabletools.'.$tool};
6220: }
6221: }
6222: }
6223:
6224: my ($toolstatus,$inststatus,$envkey);
6225: if ($context eq 'requestauthor') {
6226: $envkey = $context;
6227: } else {
6228: $envkey = $context.'.'.$tool;
6229: }
6230:
6231: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6232: ($action ne 'reload')) {
6233: $toolstatus = $env{'environment.'.$envkey};
6234: $inststatus = $env{'environment.inststatus'};
6235: } else {
6236: if (ref($userenvref) eq 'HASH') {
6237: $toolstatus = $userenvref->{$envkey};
6238: $inststatus = $userenvref->{'inststatus'};
6239: } else {
6240: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6241: $toolstatus = $userenv{$envkey};
6242: $inststatus = $userenv{'inststatus'};
6243: }
6244: }
6245:
6246: if ($toolstatus ne '') {
6247: if ($toolstatus) {
6248: $access = 1;
6249: } else {
6250: $access = 0;
6251: }
6252: return $access;
6253: }
6254:
6255: my ($is_adv,%domdef);
6256: if (ref($is_advref) eq 'HASH') {
6257: $is_adv = $is_advref->{'is_adv'};
6258: } else {
6259: $is_adv = &is_advanced_user($udom,$uname);
6260: }
6261: if (ref($domdefref) eq 'HASH') {
6262: %domdef = %{$domdefref};
6263: } else {
6264: %domdef = &get_domain_defaults($udom);
6265: }
6266: if (ref($domdef{$tool}) eq 'HASH') {
6267: if ($is_adv) {
6268: if ($domdef{$tool}{'_LC_adv'} ne '') {
6269: if ($domdef{$tool}{'_LC_adv'}) {
6270: $access = 1;
6271: } else {
6272: $access = 0;
6273: }
6274: return $access;
6275: }
6276: }
6277: if ($inststatus ne '') {
6278: my ($hasaccess,$hasnoaccess);
6279: foreach my $affiliation (split(/:/,$inststatus)) {
6280: if ($domdef{$tool}{$affiliation} ne '') {
6281: if ($domdef{$tool}{$affiliation}) {
6282: $hasaccess = 1;
6283: } else {
6284: $hasnoaccess = 1;
6285: }
6286: }
6287: }
6288: if ($hasaccess || $hasnoaccess) {
6289: if ($hasaccess) {
6290: $access = 1;
6291: } elsif ($hasnoaccess) {
6292: $access = 0;
6293: }
6294: return $access;
6295: }
6296: } else {
6297: if ($domdef{$tool}{'default'} ne '') {
6298: if ($domdef{$tool}{'default'}) {
6299: $access = 1;
6300: } elsif ($domdef{$tool}{'default'} == 0) {
6301: $access = 0;
6302: }
6303: return $access;
6304: }
6305: }
6306: } else {
6307: if (($context eq 'tools') && ($tool ne 'webdav')) {
6308: $access = 1;
6309: } else {
6310: $access = 0;
6311: }
6312: return $access;
6313: }
6314: }
6315:
6316: sub is_course_owner {
6317: my ($cdom,$cnum,$udom,$uname) = @_;
6318: if (($udom eq '') || ($uname eq '')) {
6319: $udom = $env{'user.domain'};
6320: $uname = $env{'user.name'};
6321: }
6322: unless (($udom eq '') || ($uname eq '')) {
6323: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6324: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6325: return 1;
6326: } else {
6327: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6328: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6329: return 1;
6330: }
6331: }
6332: }
6333: }
6334: return;
6335: }
6336:
6337: sub is_advanced_user {
6338: my ($udom,$uname) = @_;
6339: if ($udom ne '' && $uname ne '') {
6340: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6341: if (wantarray) {
6342: return ($env{'user.adv'},$env{'user.author'});
6343: } else {
6344: return $env{'user.adv'};
6345: }
6346: }
6347: }
6348: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6349: my %allroles;
6350: my ($is_adv,$is_author);
6351: foreach my $role (keys(%roleshash)) {
6352: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6353: my $area = '/'.$tdomain.'/'.$trest;
6354: if ($sec ne '') {
6355: $area .= '/'.$sec;
6356: }
6357: if (($area ne '') && ($trole ne '')) {
6358: my $spec=$trole.'.'.$area;
6359: if ($trole =~ /^cr\//) {
6360: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6361: } elsif ($trole ne 'gr') {
6362: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6363: }
6364: if ($trole eq 'au') {
6365: $is_author = 1;
6366: }
6367: }
6368: }
6369: foreach my $role (keys(%allroles)) {
6370: last if ($is_adv);
6371: foreach my $item (split(/:/,$allroles{$role})) {
6372: if ($item ne '') {
6373: my ($privilege,$restrictions)=split(/&/,$item);
6374: if ($privilege eq 'adv') {
6375: $is_adv = 1;
6376: last;
6377: }
6378: }
6379: }
6380: }
6381: if (wantarray) {
6382: return ($is_adv,$is_author);
6383: }
6384: return $is_adv;
6385: }
6386:
6387: sub check_can_request {
6388: my ($dom,$can_request,$request_domains) = @_;
6389: my $canreq = 0;
6390: my ($types,$typename) = &Apache::loncommon::course_types();
6391: my @options = ('approval','validate','autolimit');
6392: my $optregex = join('|',@options);
6393: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6394: foreach my $type (@{$types}) {
6395: if (&usertools_access($env{'user.name'},
6396: $env{'user.domain'},
6397: $type,undef,'requestcourses')) {
6398: $canreq ++;
6399: if (ref($request_domains) eq 'HASH') {
6400: push(@{$request_domains->{$type}},$env{'user.domain'});
6401: }
6402: if ($dom eq $env{'user.domain'}) {
6403: $can_request->{$type} = 1;
6404: }
6405: }
6406: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6407: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6408: if (@curr > 0) {
6409: foreach my $item (@curr) {
6410: if (ref($request_domains) eq 'HASH') {
6411: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6412: if ($otherdom ne '') {
6413: if (ref($request_domains->{$type}) eq 'ARRAY') {
6414: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6415: push(@{$request_domains->{$type}},$otherdom);
6416: }
6417: } else {
6418: push(@{$request_domains->{$type}},$otherdom);
6419: }
6420: }
6421: }
6422: }
6423: unless($dom eq $env{'user.domain'}) {
6424: $canreq ++;
6425: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6426: $can_request->{$type} = 1;
6427: }
6428: }
6429: }
6430: }
6431: }
6432: }
6433: return $canreq;
6434: }
6435:
6436: # ---------------------------------------------- Custom access rule evaluation
6437:
6438: sub customaccess {
6439: my ($priv,$uri)=@_;
6440: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
6441: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
6442: $udom = &LONCAPA::clean_domain($udom);
6443: $ucrs = &LONCAPA::clean_username($ucrs);
6444: my $access=0;
6445: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
6446: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6447: if ($type eq 'user') {
6448: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6449: my ($tdom,$tuname)=split(m{/},$scope);
6450: if ($tdom) {
6451: if ($tdom ne $env{'user.domain'}) { next; }
6452: }
6453: if ($tuname) {
6454: if ($tuname ne $env{'user.name'}) { next; }
6455: }
6456: $access=($effect eq 'allow');
6457: last;
6458: }
6459: } else {
6460: if ($role) {
6461: if ($role ne $urole) { next; }
6462: }
6463: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6464: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6465: if ($tdom) {
6466: if ($tdom ne $udom) { next; }
6467: }
6468: if ($tcrs) {
6469: if ($tcrs ne $ucrs) { next; }
6470: }
6471: if ($tsec) {
6472: if ($tsec ne $usec) { next; }
6473: }
6474: $access=($effect eq 'allow');
6475: last;
6476: }
6477: if ($realm eq '' && $role eq '') {
6478: $access=($effect eq 'allow');
6479: }
6480: }
6481: }
6482: return $access;
6483: }
6484:
6485: # ------------------------------------------------- Check for a user privilege
6486:
6487: sub allowed {
6488: my ($priv,$uri,$symb,$role)=@_;
6489: my $ver_orguri=$uri;
6490: $uri=&deversion($uri);
6491: my $orguri=$uri;
6492: $uri=&declutter($uri);
6493:
6494: if ($priv eq 'evb') {
6495: # Evade communication block restrictions for specified role in a course
6496: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6497: return $1;
6498: } else {
6499: return;
6500: }
6501: }
6502:
6503: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
6504: # Free bre access to adm and meta resources
6505: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
6506: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6507: && ($priv eq 'bre')) {
6508: return 'F';
6509: }
6510:
6511: # Free bre access to user's own portfolio contents
6512: my ($space,$domain,$name,@dir)=split('/',$uri);
6513: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
6514: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
6515: my %setters;
6516: my ($startblock,$endblock) =
6517: &Apache::loncommon::blockcheck(\%setters,'port');
6518: if ($startblock && $endblock) {
6519: return 'B';
6520: } else {
6521: return 'F';
6522: }
6523: }
6524:
6525: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
6526: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6527: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6528: if (exists($env{'request.course.id'})) {
6529: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6530: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6531: if (($domain eq $cdom) && ($name eq $cnum)) {
6532: my $courseprivid=$env{'request.course.id'};
6533: $courseprivid=~s/\_/\//;
6534: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6535: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6536: return $1;
6537: } else {
6538: if ($env{'request.course.sec'}) {
6539: $courseprivid.='/'.$env{'request.course.sec'};
6540: }
6541: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6542: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6543: return $2;
6544: }
6545: }
6546: }
6547: }
6548: }
6549:
6550: # Free bre to public access
6551:
6552: if ($priv eq 'bre') {
6553: my $copyright=&metadata($uri,'copyright');
6554: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
6555: return 'F';
6556: }
6557: if ($copyright eq 'priv') {
6558: $uri=~/([^\/]+)\/([^\/]+)\//;
6559: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
6560: return '';
6561: }
6562: }
6563: if ($copyright eq 'domain') {
6564: $uri=~/([^\/]+)\/([^\/]+)\//;
6565: unless (($env{'user.domain'} eq $1) ||
6566: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
6567: return '';
6568: }
6569: }
6570: if ($env{'request.role'}=~ /li\.\//) {
6571: # Library role, so allow browsing of resources in this domain.
6572: return 'F';
6573: }
6574: if ($copyright eq 'custom') {
6575: unless (&customaccess($priv,$uri)) { return ''; }
6576: }
6577: }
6578: # Domain coordinator is trying to create a course
6579: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
6580: # uri is the requested domain in this case.
6581: # comparison to 'request.role.domain' shows if the user has selected
6582: # a role of dc for the domain in question.
6583: return 'F' if ($uri eq $env{'request.role.domain'});
6584: }
6585:
6586: my $thisallowed='';
6587: my $statecond=0;
6588: my $courseprivid='';
6589:
6590: my $ownaccess;
6591: # Community Coordinator or Assistant Co-author browsing resource space.
6592: if (($priv eq 'bro') && ($env{'user.author'})) {
6593: if ($uri eq '') {
6594: $ownaccess = 1;
6595: } else {
6596: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6597: my $udom = $env{'user.domain'};
6598: my $uname = $env{'user.name'};
6599: if ($uri =~ m{^\Q$udom\E/?$}) {
6600: $ownaccess = 1;
6601: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
6602: unless ($uri =~ m{\.\./}) {
6603: $ownaccess = 1;
6604: }
6605: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6606: my $now = time;
6607: if ($uri =~ m{^([^/]+)/?$}) {
6608: my $adom = $1;
6609: foreach my $key (keys(%env)) {
6610: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
6611: my ($start,$end) = split('.',$env{$key});
6612: if (($now >= $start) && (!$end || $end < $now)) {
6613: $ownaccess = 1;
6614: last;
6615: }
6616: }
6617: }
6618: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6619: my $adom = $1;
6620: my $aname = $2;
6621: foreach my $role ('ca','aa') {
6622: if ($env{"user.role.$role./$adom/$aname"}) {
6623: my ($start,$end) =
6624: split('.',$env{"user.role.$role./$adom/$aname"});
6625: if (($now >= $start) && (!$end || $end < $now)) {
6626: $ownaccess = 1;
6627: last;
6628: }
6629: }
6630: }
6631: }
6632: }
6633: }
6634: }
6635: }
6636:
6637: # Course
6638:
6639: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6640: unless (($priv eq 'bro') && (!$ownaccess)) {
6641: $thisallowed.=$1;
6642: }
6643: }
6644:
6645: # Domain
6646:
6647: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6648: =~/\Q$priv\E\&([^\:]*)/) {
6649: unless (($priv eq 'bro') && (!$ownaccess)) {
6650: $thisallowed.=$1;
6651: }
6652: }
6653:
6654: # User who is not author or co-author might still be able to edit
6655: # resource of an author in the domain (e.g., if Domain Coordinator).
6656: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6657: (&allowed('mdc',$env{'request.course.id'}))) {
6658: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6659: $thisallowed.=$1;
6660: }
6661: }
6662:
6663: # Course: uri itself is a course
6664: my $courseuri=$uri;
6665: $courseuri=~s/\_(\d)/\/$1/;
6666: $courseuri=~s/^([^\/])/\/$1/;
6667:
6668: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6669: =~/\Q$priv\E\&([^\:]*)/) {
6670: unless (($priv eq 'bro') && (!$ownaccess)) {
6671: $thisallowed.=$1;
6672: }
6673: }
6674:
6675: # URI is an uploaded document for this course, default permissions don't matter
6676: # not allowing 'edit' access (editupload) to uploaded course docs
6677: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6678: $thisallowed='';
6679: my ($match)=&is_on_map($uri);
6680: if ($match) {
6681: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6682: =~/\Q$priv\E\&([^\:]*)/) {
6683: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6684: if (@blockers > 0) {
6685: $thisallowed = 'B';
6686: } else {
6687: $thisallowed.=$1;
6688: }
6689: }
6690: } else {
6691: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6692: if ($refuri) {
6693: if ($refuri =~ m|^/adm/|) {
6694: $thisallowed='F';
6695: } else {
6696: $refuri=&declutter($refuri);
6697: my ($match) = &is_on_map($refuri);
6698: if ($match) {
6699: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6700: if (@blockers > 0) {
6701: $thisallowed = 'B';
6702: } else {
6703: $thisallowed='F';
6704: }
6705: }
6706: }
6707: }
6708: }
6709: }
6710:
6711: if ($priv eq 'bre'
6712: && $thisallowed ne 'F'
6713: && $thisallowed ne '2'
6714: && &is_portfolio_url($uri)) {
6715: $thisallowed = &portfolio_access($uri);
6716: }
6717:
6718: # Full access at system, domain or course-wide level? Exit.
6719: if ($thisallowed=~/F/) {
6720: return 'F';
6721: }
6722:
6723: # If this is generating or modifying users, exit with special codes
6724:
6725: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6726: if (($priv eq 'cca') || ($priv eq 'caa')) {
6727: my ($audom,$auname)=split('/',$uri);
6728: # no author name given, so this just checks on the general right to make a co-author in this domain
6729: unless ($auname) { return $thisallowed; }
6730: # an author name is given, so we are about to actually make a co-author for a certain account
6731: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6732: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6733: ($audom ne $env{'request.role.domain'}))) { return ''; }
6734: }
6735: return $thisallowed;
6736: }
6737: #
6738: # Gathered so far: system, domain and course wide privileges
6739: #
6740: # Course: See if uri or referer is an individual resource that is part of
6741: # the course
6742:
6743: if ($env{'request.course.id'}) {
6744:
6745: $courseprivid=$env{'request.course.id'};
6746: if ($env{'request.course.sec'}) {
6747: $courseprivid.='/'.$env{'request.course.sec'};
6748: }
6749: $courseprivid=~s/\_/\//;
6750: my $checkreferer=1;
6751: my ($match,$cond)=&is_on_map($uri);
6752: if ($match) {
6753: $statecond=$cond;
6754: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6755: =~/\Q$priv\E\&([^\:]*)/) {
6756: my $value = $1;
6757: if ($priv eq 'bre') {
6758: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6759: if (@blockers > 0) {
6760: $thisallowed = 'B';
6761: } else {
6762: $thisallowed.=$value;
6763: }
6764: } else {
6765: $thisallowed.=$value;
6766: }
6767: $checkreferer=0;
6768: }
6769: }
6770:
6771: if ($checkreferer) {
6772: my $refuri=$env{'httpref.'.$orguri};
6773: unless ($refuri) {
6774: foreach my $key (keys(%env)) {
6775: if ($key=~/^httpref\..*\*/) {
6776: my $pattern=$key;
6777: $pattern=~s/^httpref\.\/res\///;
6778: $pattern=~s/\*/\[\^\/\]\+/g;
6779: $pattern=~s/\//\\\//g;
6780: if ($orguri=~/$pattern/) {
6781: $refuri=$env{$key};
6782: }
6783: }
6784: }
6785: }
6786:
6787: if ($refuri) {
6788: $refuri=&declutter($refuri);
6789: my ($match,$cond)=&is_on_map($refuri);
6790: if ($match) {
6791: my $refstatecond=$cond;
6792: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6793: =~/\Q$priv\E\&([^\:]*)/) {
6794: my $value = $1;
6795: if ($priv eq 'bre') {
6796: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6797: if (@blockers > 0) {
6798: $thisallowed = 'B';
6799: } else {
6800: $thisallowed.=$value;
6801: }
6802: } else {
6803: $thisallowed.=$value;
6804: }
6805: $uri=$refuri;
6806: $statecond=$refstatecond;
6807: }
6808: }
6809: }
6810: }
6811: }
6812:
6813: #
6814: # Gathered now: all privileges that could apply, and condition number
6815: #
6816: #
6817: # Full or no access?
6818: #
6819:
6820: if ($thisallowed=~/F/) {
6821: return 'F';
6822: }
6823:
6824: unless ($thisallowed) {
6825: return '';
6826: }
6827:
6828: # Restrictions exist, deal with them
6829: #
6830: # C:according to course preferences
6831: # R:according to resource settings
6832: # L:unless locked
6833: # X:according to user session state
6834: #
6835:
6836: # Possibly locked functionality, check all courses
6837: # Locks might take effect only after 10 minutes cache expiration for other
6838: # courses, and 2 minutes for current course
6839:
6840: my $envkey;
6841: if ($thisallowed=~/L/) {
6842: foreach $envkey (keys(%env)) {
6843: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6844: my $courseid=$2;
6845: my $roleid=$1.'.'.$2;
6846: $courseid=~s/^\///;
6847: my $expiretime=600;
6848: if ($env{'request.role'} eq $roleid) {
6849: $expiretime=120;
6850: }
6851: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6852: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6853: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6854: &coursedescription($courseid,{'freshen_cache' => 1});
6855: }
6856: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6857: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6858: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6859: &log($env{'user.domain'},$env{'user.name'},
6860: $env{'user.home'},
6861: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6862: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6863: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6864: return '';
6865: }
6866: }
6867: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6868: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6869: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6870: &log($env{'user.domain'},$env{'user.name'},
6871: $env{'user.home'},
6872: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6873: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6874: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6875: return '';
6876: }
6877: }
6878: }
6879: }
6880: }
6881:
6882: #
6883: # Rest of the restrictions depend on selected course
6884: #
6885:
6886: unless ($env{'request.course.id'}) {
6887: if ($thisallowed eq 'A') {
6888: return 'A';
6889: } elsif ($thisallowed eq 'B') {
6890: return 'B';
6891: } else {
6892: return '1';
6893: }
6894: }
6895:
6896: #
6897: # Now user is definitely in a course
6898: #
6899:
6900:
6901: # Course preferences
6902:
6903: if ($thisallowed=~/C/) {
6904: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6905: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6906: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6907: =~/\Q$rolecode\E/) {
6908: if (($priv ne 'pch') && ($priv ne 'plc')) {
6909: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6910: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6911: $env{'request.course.id'});
6912: }
6913: return '';
6914: }
6915:
6916: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6917: =~/\Q$unamedom\E/) {
6918: if (($priv ne 'pch') && ($priv ne 'plc')) {
6919: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6920: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6921: $env{'request.course.id'});
6922: }
6923: return '';
6924: }
6925: }
6926:
6927: # Resource preferences
6928:
6929: if ($thisallowed=~/R/) {
6930: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6931: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6932: if (($priv ne 'pch') && ($priv ne 'plc')) {
6933: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6934: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6935: }
6936: return '';
6937: }
6938: }
6939:
6940: # Restricted by state or randomout?
6941:
6942: if ($thisallowed=~/X/) {
6943: if ($env{'acc.randomout'}) {
6944: if (!$symb) { $symb=&symbread($uri,1); }
6945: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6946: return '';
6947: }
6948: }
6949: if (&condval($statecond)) {
6950: return '2';
6951: } else {
6952: return '';
6953: }
6954: }
6955:
6956: if ($thisallowed eq 'A') {
6957: return 'A';
6958: } elsif ($thisallowed eq 'B') {
6959: return 'B';
6960: }
6961: return 'F';
6962: }
6963:
6964: # ------------------------------------------- Check construction space access
6965:
6966: sub constructaccess {
6967: my ($url,$setpriv)=@_;
6968:
6969: # We do not allow editing of previous versions of files
6970: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6971:
6972: # Get username and domain from URL
6973: my ($ownername,$ownerdomain,$ownerhome);
6974:
6975: ($ownerdomain,$ownername) =
6976: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6977:
6978: # The URL does not really point to any authorspace, forget it
6979: unless (($ownername) && ($ownerdomain)) { return ''; }
6980:
6981: # Now we need to see if the user has access to the authorspace of
6982: # $ownername at $ownerdomain
6983:
6984: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
6985: # Real author for this?
6986: $ownerhome = $env{'user.home'};
6987: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
6988: return ($ownername,$ownerdomain,$ownerhome);
6989: }
6990: } else {
6991: # Co-author for this?
6992: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
6993: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
6994: $ownerhome = &homeserver($ownername,$ownerdomain);
6995: return ($ownername,$ownerdomain,$ownerhome);
6996: }
6997: }
6998:
6999: # We don't have any access right now. If we are not possibly going to do anything about this,
7000: # we might as well leave
7001: unless ($setpriv) { return ''; }
7002:
7003: # Backdoor access?
7004: my $allowed=&allowed('eco',$ownerdomain);
7005: # Nope
7006: unless ($allowed) { return ''; }
7007: # Looks like we may have access, but could be locked by the owner of the construction space
7008: if ($allowed eq 'U') {
7009: my %blocked=&get('environment',['domcoord.author'],
7010: $ownerdomain,$ownername);
7011: # Is blocked by owner
7012: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7013: }
7014: if (($allowed eq 'F') || ($allowed eq 'U')) {
7015: # Grant temporary access
7016: my $then=$env{'user.login.time'};
7017: my $update=$env{'user.update.time'};
7018: if (!$update) { $update = $then; }
7019: my $refresh=$env{'user.refresh.time'};
7020: if (!$refresh) { $refresh = $update; }
7021: my $now = time;
7022: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7023: $now,'ca','constructaccess');
7024: $ownerhome = &homeserver($ownername,$ownerdomain);
7025: return($ownername,$ownerdomain,$ownerhome);
7026: }
7027: # No business here
7028: return '';
7029: }
7030:
7031: sub get_comm_blocks {
7032: my ($cdom,$cnum) = @_;
7033: if ($cdom eq '' || $cnum eq '') {
7034: return unless ($env{'request.course.id'});
7035: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7036: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7037: }
7038: my %commblocks;
7039: my $hashid=$cdom.'_'.$cnum;
7040: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7041: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7042: %commblocks = %{$blocksref};
7043: } else {
7044: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7045: my $cachetime = 600;
7046: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7047: }
7048: return %commblocks;
7049: }
7050:
7051: sub has_comm_blocking {
7052: my ($priv,$symb,$uri,$blocks) = @_;
7053: return unless ($env{'request.course.id'});
7054: return unless ($priv eq 'bre');
7055: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7056: my %commblocks;
7057: if (ref($blocks) eq 'HASH') {
7058: %commblocks = %{$blocks};
7059: } else {
7060: %commblocks = &get_comm_blocks();
7061: }
7062: return unless (keys(%commblocks) > 0);
7063: if (!$symb) { $symb=&symbread($uri,1); }
7064: my ($map,$resid,undef)=&decode_symb($symb);
7065: my %tocheck = (
7066: maps => $map,
7067: resources => $symb,
7068: );
7069: my @blockers;
7070: my $now = time;
7071: my $navmap = Apache::lonnavmaps::navmap->new();
7072: foreach my $block (keys(%commblocks)) {
7073: if ($block =~ /^(\d+)____(\d+)$/) {
7074: my ($start,$end) = ($1,$2);
7075: if ($start <= $now && $end >= $now) {
7076: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7077: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7078: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7079: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7080: unless (grep(/^\Q$block\E$/,@blockers)) {
7081: push(@blockers,$block);
7082: }
7083: }
7084: }
7085: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7086: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7087: unless (grep(/^\Q$block\E$/,@blockers)) {
7088: push(@blockers,$block);
7089: }
7090: }
7091: }
7092: }
7093: }
7094: }
7095: } elsif ($block =~ /^firstaccess____(.+)$/) {
7096: my $item = $1;
7097: my @to_test;
7098: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7099: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7100: my $check_interval;
7101: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7102: my @interval;
7103: my $type = 'map';
7104: if ($item eq 'course') {
7105: $type = 'course';
7106: @interval=&EXT("resource.0.interval");
7107: } else {
7108: if ($item =~ /___\d+___/) {
7109: $type = 'resource';
7110: @interval=&EXT("resource.0.interval",$item);
7111: if (ref($navmap)) {
7112: my $res = $navmap->getBySymb($item);
7113: push(@to_test,$res);
7114: }
7115: } else {
7116: my $mapsymb = &symbread($item,1);
7117: if ($mapsymb) {
7118: if (ref($navmap)) {
7119: my $mapres = $navmap->getBySymb($mapsymb);
7120: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7121: foreach my $res (@to_test) {
7122: my $symb = $res->symb();
7123: next if ($symb eq $mapsymb);
7124: if ($symb ne '') {
7125: @interval=&EXT("resource.0.interval",$symb);
7126: last;
7127: }
7128: }
7129: }
7130: }
7131: }
7132: }
7133: if ($interval[0] =~ /\d+/) {
7134: my $first_access;
7135: if ($type eq 'resource') {
7136: $first_access=&get_first_access($interval[1],$item);
7137: } elsif ($type eq 'map') {
7138: $first_access=&get_first_access($interval[1],undef,$item);
7139: } else {
7140: $first_access=&get_first_access($interval[1]);
7141: }
7142: if ($first_access) {
7143: my $timesup = $first_access+$interval[0];
7144: if ($timesup > $now) {
7145: foreach my $res (@to_test) {
7146: if ($res->is_problem()) {
7147: if ($res->completable()) {
7148: unless (grep(/^\Q$block\E$/,@blockers)) {
7149: push(@blockers,$block);
7150: }
7151: last;
7152: }
7153: }
7154: }
7155: }
7156: }
7157: }
7158: }
7159: }
7160: }
7161: }
7162: }
7163: return @blockers;
7164: }
7165:
7166: sub check_docs_block {
7167: my ($docsblock,$tocheck) =@_;
7168: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7169: return;
7170: }
7171: if (ref($docsblock->{'maps'}) eq 'HASH') {
7172: if ($tocheck->{'maps'}) {
7173: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7174: return 1;
7175: }
7176: }
7177: }
7178: if (ref($docsblock->{'resources'}) eq 'HASH') {
7179: if ($tocheck->{'resources'}) {
7180: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7181: return 1;
7182: }
7183: }
7184: }
7185: return;
7186: }
7187:
7188: #
7189: # Removes the versino from a URI and
7190: # splits it in to its filename and path to the filename.
7191: # Seems like File::Basename could have done this more clearly.
7192: # Parameters:
7193: # $uri - input URI
7194: # Returns:
7195: # Two element list consisting of
7196: # $pathname - the URI up to and excluding the trailing /
7197: # $filename - The part of the URI following the last /
7198: # NOTE:
7199: # Another realization of this is simply:
7200: # use File::Basename;
7201: # ...
7202: # $uri = shift;
7203: # $filename = basename($uri);
7204: # $path = dirname($uri);
7205: # return ($filename, $path);
7206: #
7207: # The implementation below is probably faster however.
7208: #
7209: sub split_uri_for_cond {
7210: my $uri=&deversion(&declutter(shift));
7211: my @uriparts=split(/\//,$uri);
7212: my $filename=pop(@uriparts);
7213: my $pathname=join('/',@uriparts);
7214: return ($pathname,$filename);
7215: }
7216: # --------------------------------------------------- Is a resource on the map?
7217:
7218: sub is_on_map {
7219: my ($pathname,$filename) = &split_uri_for_cond(shift);
7220: #Trying to find the conditional for the file
7221: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
7222: /\&\Q$filename\E\:([\d\|]+)\&/);
7223: if ($match) {
7224: return (1,$1);
7225: } else {
7226: return (0,0);
7227: }
7228: }
7229:
7230: # --------------------------------------------------------- Get symb from alias
7231:
7232: sub get_symb_from_alias {
7233: my $symb=shift;
7234: my ($map,$resid,$url)=&decode_symb($symb);
7235: # Already is a symb
7236: if ($url) { return $symb; }
7237: # Must be an alias
7238: my $aliassymb='';
7239: my %bighash;
7240: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7241: &GDBM_READER(),0640)) {
7242: my $rid=$bighash{'mapalias_'.$symb};
7243: if ($rid) {
7244: my ($mapid,$resid)=split(/\./,$rid);
7245: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7246: $resid,$bighash{'src_'.$rid});
7247: }
7248: untie %bighash;
7249: }
7250: return $aliassymb;
7251: }
7252:
7253: # ----------------------------------------------------------------- Define Role
7254:
7255: sub definerole {
7256: if (allowed('mcr','/')) {
7257: my ($rolename,$sysrole,$domrole,$courole)=@_;
7258: foreach my $role (split(':',$sysrole)) {
7259: my ($crole,$cqual)=split(/\&/,$role);
7260: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7261: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7262: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7263: return "refused:s:$crole&$cqual";
7264: }
7265: }
7266: }
7267: foreach my $role (split(':',$domrole)) {
7268: my ($crole,$cqual)=split(/\&/,$role);
7269: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7270: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7271: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
7272: return "refused:d:$crole&$cqual";
7273: }
7274: }
7275: }
7276: foreach my $role (split(':',$courole)) {
7277: my ($crole,$cqual)=split(/\&/,$role);
7278: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7279: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7280: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7281: return "refused:c:$crole&$cqual";
7282: }
7283: }
7284: }
7285: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7286: "$env{'user.domain'}:$env{'user.name'}:".
7287: "rolesdef_$rolename=".
7288: escape($sysrole.'_'.$domrole.'_'.$courole);
7289: return reply($command,$env{'user.home'});
7290: } else {
7291: return 'refused';
7292: }
7293: }
7294:
7295: # ---------------- Make a metadata query against the network of library servers
7296:
7297: sub metadata_query {
7298: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
7299: my %rhash;
7300: my %libserv = &all_library();
7301: my @server_list = (defined($server_array) ? @$server_array
7302: : keys(%libserv) );
7303: for my $server (@server_list) {
7304: my $domains = '';
7305: if (ref($domains_hash) eq 'HASH') {
7306: $domains = $domains_hash->{$server};
7307: }
7308: unless ($custom or $customshow) {
7309: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
7310: $rhash{$server}=$reply;
7311: }
7312: else {
7313: my $reply=&reply("querysend:".&escape($query).':'.
7314: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
7315: $server);
7316: $rhash{$server}=$reply;
7317: }
7318: }
7319: return \%rhash;
7320: }
7321:
7322: # ----------------------------------------- Send log queries and wait for reply
7323:
7324: sub log_query {
7325: my ($uname,$udom,$query,%filters)=@_;
7326: my $uhome=&homeserver($uname,$udom);
7327: if ($uhome eq 'no_host') { return 'error: no_host'; }
7328: my $uhost=&hostname($uhome);
7329: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
7330: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7331: $uhome);
7332: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
7333: return get_query_reply($queryid);
7334: }
7335:
7336: # -------------------------- Update MySQL table for portfolio file
7337:
7338: sub update_portfolio_table {
7339: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
7340: if ($group ne '') {
7341: $file_name =~s /^\Q$group\E//;
7342: }
7343: my $homeserver = &homeserver($uname,$udom);
7344: my $queryid=
7345: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7346: ':'.&escape($file_name).':'.$action,$homeserver);
7347: my $reply = &get_query_reply($queryid);
7348: return $reply;
7349: }
7350:
7351: # -------------------------- Update MySQL allusers table
7352:
7353: sub update_allusers_table {
7354: my ($uname,$udom,$names) = @_;
7355: my $homeserver = &homeserver($uname,$udom);
7356: my $queryid=
7357: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7358: 'lastname='.&escape($names->{'lastname'}).'%%'.
7359: 'firstname='.&escape($names->{'firstname'}).'%%'.
7360: 'middlename='.&escape($names->{'middlename'}).'%%'.
7361: 'generation='.&escape($names->{'generation'}).'%%'.
7362: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7363: 'id='.&escape($names->{'id'}),$homeserver);
7364: return;
7365: }
7366:
7367: # ------- Request retrieval of institutional classlists for course(s)
7368:
7369: sub fetch_enrollment_query {
7370: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
7371: my $homeserver;
7372: my $maxtries = 1;
7373: if ($context eq 'automated') {
7374: $homeserver = $perlvar{'lonHostID'};
7375: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
7376: } else {
7377: $homeserver = &homeserver($cnum,$dom);
7378: }
7379: my $host=&hostname($homeserver);
7380: my $cmd = '';
7381: foreach my $affiliate (keys(%{$affiliatesref})) {
7382: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7383: }
7384: $cmd =~ s/%%$//;
7385: $cmd = &escape($cmd);
7386: my $query = 'fetchenrollment';
7387: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
7388: unless ($queryid=~/^\Q$host\E\_/) {
7389: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7390: return 'error: '.$queryid;
7391: }
7392: my $reply = &get_query_reply($queryid);
7393: my $tries = 1;
7394: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7395: $reply = &get_query_reply($queryid);
7396: $tries ++;
7397: }
7398: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7399: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7400: } else {
7401: my @responses = split(/:/,$reply);
7402: if ($homeserver eq $perlvar{'lonHostID'}) {
7403: foreach my $line (@responses) {
7404: my ($key,$value) = split(/=/,$line,2);
7405: $$replyref{$key} = $value;
7406: }
7407: } else {
7408: my $pathname = LONCAPA::tempdir();
7409: foreach my $line (@responses) {
7410: my ($key,$value) = split(/=/,$line);
7411: $$replyref{$key} = $value;
7412: if ($value > 0) {
7413: foreach my $item (@{$$affiliatesref{$key}}) {
7414: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
7415: my $destname = $pathname.'/'.$filename;
7416: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
7417: if ($xml_classlist =~ /^error/) {
7418: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7419: } else {
7420: if ( open(FILE,">$destname") ) {
7421: print FILE &unescape($xml_classlist);
7422: close(FILE);
7423: } else {
7424: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
7425: }
7426: }
7427: }
7428: }
7429: }
7430: }
7431: return 'ok';
7432: }
7433: return 'error';
7434: }
7435:
7436: sub get_query_reply {
7437: my $queryid=shift;
7438: my $replyfile=LONCAPA::tempdir().$queryid;
7439: my $reply='';
7440: for (1..100) {
7441: sleep 2;
7442: if (-e $replyfile.'.end') {
7443: if (open(my $fh,$replyfile)) {
7444: $reply = join('',<$fh>);
7445: close($fh);
7446: } else { return 'error: reply_file_error'; }
7447: return &unescape($reply);
7448: }
7449: }
7450: return 'timeout:'.$queryid;
7451: }
7452:
7453: sub courselog_query {
7454: #
7455: # possible filters:
7456: # url: url or symb
7457: # username
7458: # domain
7459: # action: view, submit, grade
7460: # start: timestamp
7461: # end: timestamp
7462: #
7463: my (%filters)=@_;
7464: unless ($env{'request.course.id'}) { return 'no_course'; }
7465: if ($filters{'url'}) {
7466: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7467: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7468: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7469: }
7470: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7471: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7472: return &log_query($cname,$cdom,'courselog',%filters);
7473: }
7474:
7475: sub userlog_query {
7476: #
7477: # possible filters:
7478: # action: log check role
7479: # start: timestamp
7480: # end: timestamp
7481: #
7482: my ($uname,$udom,%filters)=@_;
7483: return &log_query($uname,$udom,'userlog',%filters);
7484: }
7485:
7486: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7487:
7488: sub auto_run {
7489: my ($cnum,$cdom) = @_;
7490: my $response = 0;
7491: my $settings;
7492: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7493: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7494: $settings = $domconfig{'autoenroll'};
7495: if ($settings->{'run'} eq '1') {
7496: $response = 1;
7497: }
7498: } else {
7499: my $homeserver;
7500: if (&is_course($cdom,$cnum)) {
7501: $homeserver = &homeserver($cnum,$cdom);
7502: } else {
7503: $homeserver = &domain($cdom,'primary');
7504: }
7505: if ($homeserver ne 'no_host') {
7506: $response = &reply('autorun:'.$cdom,$homeserver);
7507: }
7508: }
7509: return $response;
7510: }
7511:
7512: sub auto_get_sections {
7513: my ($cnum,$cdom,$inst_coursecode) = @_;
7514: my $homeserver;
7515: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7516: $homeserver = &homeserver($cnum,$cdom);
7517: }
7518: if (!defined($homeserver)) {
7519: if ($cdom =~ /^$match_domain$/) {
7520: $homeserver = &domain($cdom,'primary');
7521: }
7522: }
7523: my @secs;
7524: if (defined($homeserver)) {
7525: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7526: unless ($response eq 'refused') {
7527: @secs = split(/:/,$response);
7528: }
7529: }
7530: return @secs;
7531: }
7532:
7533: sub auto_new_course {
7534: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
7535: my $homeserver = &homeserver($cnum,$cdom);
7536: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
7537: return $response;
7538: }
7539:
7540: sub auto_validate_courseID {
7541: my ($cnum,$cdom,$inst_course_id) = @_;
7542: my $homeserver = &homeserver($cnum,$cdom);
7543: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
7544: return $response;
7545: }
7546:
7547: sub auto_validate_instcode {
7548: my ($cnum,$cdom,$instcode,$owner) = @_;
7549: my ($homeserver,$response);
7550: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7551: $homeserver = &homeserver($cnum,$cdom);
7552: }
7553: if (!defined($homeserver)) {
7554: if ($cdom =~ /^$match_domain$/) {
7555: $homeserver = &domain($cdom,'primary');
7556: }
7557: }
7558: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7559: &escape($instcode).':'.&escape($owner),$homeserver));
7560: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7561: return ($outcome,$description,$defaultcredits);
7562: }
7563:
7564: sub auto_create_password {
7565: my ($cnum,$cdom,$authparam,$udom) = @_;
7566: my ($homeserver,$response);
7567: my $create_passwd = 0;
7568: my $authchk = '';
7569: if ($udom =~ /^$match_domain$/) {
7570: $homeserver = &domain($udom,'primary');
7571: }
7572: if ($homeserver eq '') {
7573: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7574: $homeserver = &homeserver($cnum,$cdom);
7575: }
7576: }
7577: if ($homeserver eq '') {
7578: $authchk = 'nodomain';
7579: } else {
7580: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7581: if ($response eq 'refused') {
7582: $authchk = 'refused';
7583: } else {
7584: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
7585: }
7586: }
7587: return ($authparam,$create_passwd,$authchk);
7588: }
7589:
7590: sub auto_photo_permission {
7591: my ($cnum,$cdom,$students) = @_;
7592: my $homeserver = &homeserver($cnum,$cdom);
7593: my ($outcome,$perm_reqd,$conditions) =
7594: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
7595: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7596: return (undef,undef);
7597: }
7598: return ($outcome,$perm_reqd,$conditions);
7599: }
7600:
7601: sub auto_checkphotos {
7602: my ($uname,$udom,$pid) = @_;
7603: my $homeserver = &homeserver($uname,$udom);
7604: my ($result,$resulttype);
7605: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
7606: &escape($uname).':'.&escape($pid),
7607: $homeserver));
7608: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7609: return (undef,undef);
7610: }
7611: if ($outcome) {
7612: ($result,$resulttype) = split(/:/,$outcome);
7613: }
7614: return ($result,$resulttype);
7615: }
7616:
7617: sub auto_photochoice {
7618: my ($cnum,$cdom) = @_;
7619: my $homeserver = &homeserver($cnum,$cdom);
7620: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
7621: &escape($cdom),
7622: $homeserver)));
7623: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7624: return (undef,undef);
7625: }
7626: return ($update,$comment);
7627: }
7628:
7629: sub auto_photoupdate {
7630: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7631: my $homeserver = &homeserver($cnum,$dom);
7632: my $host=&hostname($homeserver);
7633: my $cmd = '';
7634: my $maxtries = 1;
7635: foreach my $affiliate (keys(%{$affiliatesref})) {
7636: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7637: }
7638: $cmd =~ s/%%$//;
7639: $cmd = &escape($cmd);
7640: my $query = 'institutionalphotos';
7641: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7642: unless ($queryid=~/^\Q$host\E\_/) {
7643: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7644: return 'error: '.$queryid;
7645: }
7646: my $reply = &get_query_reply($queryid);
7647: my $tries = 1;
7648: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7649: $reply = &get_query_reply($queryid);
7650: $tries ++;
7651: }
7652: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7653: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7654: } else {
7655: my @responses = split(/:/,$reply);
7656: my $outcome = shift(@responses);
7657: foreach my $item (@responses) {
7658: my ($key,$value) = split(/=/,$item);
7659: $$photo{$key} = $value;
7660: }
7661: return $outcome;
7662: }
7663: return 'error';
7664: }
7665:
7666: sub auto_instcode_format {
7667: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7668: $cat_order) = @_;
7669: my $courses = '';
7670: my @homeservers;
7671: if ($caller eq 'global') {
7672: my %servers = &get_servers($codedom,'library');
7673: foreach my $tryserver (keys(%servers)) {
7674: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7675: push(@homeservers,$tryserver);
7676: }
7677: }
7678: } elsif ($caller eq 'requests') {
7679: if ($codedom =~ /^$match_domain$/) {
7680: my $chome = &domain($codedom,'primary');
7681: unless ($chome eq 'no_host') {
7682: push(@homeservers,$chome);
7683: }
7684: }
7685: } else {
7686: push(@homeservers,&homeserver($caller,$codedom));
7687: }
7688: foreach my $code (keys(%{$instcodes})) {
7689: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
7690: }
7691: chop($courses);
7692: my $ok_response = 0;
7693: my $response;
7694: while (@homeservers > 0 && $ok_response == 0) {
7695: my $server = shift(@homeservers);
7696: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7697: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7698: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
7699: split(/:/,$response);
7700: %{$codes} = (%{$codes},&str2hash($codes_str));
7701: push(@{$codetitles},&str2array($codetitles_str));
7702: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7703: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7704: $ok_response = 1;
7705: }
7706: }
7707: if ($ok_response) {
7708: return 'ok';
7709: } else {
7710: return $response;
7711: }
7712: }
7713:
7714: sub auto_instcode_defaults {
7715: my ($domain,$returnhash,$code_order) = @_;
7716: my @homeservers;
7717:
7718: my %servers = &get_servers($domain,'library');
7719: foreach my $tryserver (keys(%servers)) {
7720: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7721: push(@homeservers,$tryserver);
7722: }
7723: }
7724:
7725: my $response;
7726: foreach my $server (@homeservers) {
7727: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7728: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7729:
7730: foreach my $pair (split(/\&/,$response)) {
7731: my ($name,$value)=split(/\=/,$pair);
7732: if ($name eq 'code_order') {
7733: @{$code_order} = split(/\&/,&unescape($value));
7734: } else {
7735: $returnhash->{&unescape($name)}=&unescape($value);
7736: }
7737: }
7738: return 'ok';
7739: }
7740:
7741: return $response;
7742: }
7743:
7744: sub auto_possible_instcodes {
7745: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7746: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7747: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7748: return;
7749: }
7750: my (@homeservers,$uhome);
7751: if (defined(&domain($domain,'primary'))) {
7752: $uhome=&domain($domain,'primary');
7753: push(@homeservers,&domain($domain,'primary'));
7754: } else {
7755: my %servers = &get_servers($domain,'library');
7756: foreach my $tryserver (keys(%servers)) {
7757: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7758: push(@homeservers,$tryserver);
7759: }
7760: }
7761: }
7762: my $response;
7763: foreach my $server (@homeservers) {
7764: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7765: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7766: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7767: split(':',$response);
7768: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7769: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7770: foreach my $item (split('&',$cat_title)) {
7771: my ($name,$value)=split('=',$item);
7772: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7773: }
7774: foreach my $item (split('&',$cat_order)) {
7775: my ($name,$value)=split('=',$item);
7776: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7777: }
7778: return 'ok';
7779: }
7780: return $response;
7781: }
7782:
7783: sub auto_courserequest_checks {
7784: my ($dom) = @_;
7785: my ($homeserver,%validations);
7786: if ($dom =~ /^$match_domain$/) {
7787: $homeserver = &domain($dom,'primary');
7788: }
7789: unless ($homeserver eq 'no_host') {
7790: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7791: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7792: my @items = split(/&/,$response);
7793: foreach my $item (@items) {
7794: my ($key,$value) = split('=',$item);
7795: $validations{&unescape($key)} = &thaw_unescape($value);
7796: }
7797: }
7798: }
7799: return %validations;
7800: }
7801:
7802: sub auto_courserequest_validation {
7803: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7804: my ($homeserver,$response);
7805: if ($dom =~ /^$match_domain$/) {
7806: $homeserver = &domain($dom,'primary');
7807: }
7808: unless ($homeserver eq 'no_host') {
7809:
7810: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7811: ':'.&escape($crstype).':'.&escape($inststatuslist).
7812: ':'.&escape($instcode).':'.&escape($instseclist),
7813: $homeserver));
7814: }
7815: return $response;
7816: }
7817:
7818: sub auto_validate_class_sec {
7819: my ($cdom,$cnum,$owners,$inst_class) = @_;
7820: my $homeserver = &homeserver($cnum,$cdom);
7821: my $ownerlist;
7822: if (ref($owners) eq 'ARRAY') {
7823: $ownerlist = join(',',@{$owners});
7824: } else {
7825: $ownerlist = $owners;
7826: }
7827: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7828: &escape($ownerlist).':'.$cdom,$homeserver);
7829: return $response;
7830: }
7831:
7832: # ------------------------------------------------------- Course Group routines
7833:
7834: sub get_coursegroups {
7835: my ($cdom,$cnum,$group,$namespace) = @_;
7836: return(&dump($namespace,$cdom,$cnum,$group));
7837: }
7838:
7839: sub modify_coursegroup {
7840: my ($cdom,$cnum,$groupsettings) = @_;
7841: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7842: }
7843:
7844: sub toggle_coursegroup_status {
7845: my ($cdom,$cnum,$group,$action) = @_;
7846: my ($from_namespace,$to_namespace);
7847: if ($action eq 'delete') {
7848: $from_namespace = 'coursegroups';
7849: $to_namespace = 'deleted_groups';
7850: } else {
7851: $from_namespace = 'deleted_groups';
7852: $to_namespace = 'coursegroups';
7853: }
7854: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
7855: if (my $tmp = &error(%curr_group)) {
7856: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7857: return ('read error',$tmp);
7858: } else {
7859: my %savedsettings = %curr_group;
7860: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
7861: my $deloutcome;
7862: if ($result eq 'ok') {
7863: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
7864: } else {
7865: return ('write error',$result);
7866: }
7867: if ($deloutcome eq 'ok') {
7868: return 'ok';
7869: } else {
7870: return ('delete error',$deloutcome);
7871: }
7872: }
7873: }
7874:
7875: sub modify_group_roles {
7876: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
7877: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7878: my $role = 'gr/'.&escape($userprivs);
7879: my ($uname,$udom) = split(/:/,$user);
7880: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
7881: if ($result eq 'ok') {
7882: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7883: }
7884: return $result;
7885: }
7886:
7887: sub modify_coursegroup_membership {
7888: my ($cdom,$cnum,$membership) = @_;
7889: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7890: return $result;
7891: }
7892:
7893: sub get_active_groups {
7894: my ($udom,$uname,$cdom,$cnum) = @_;
7895: my $now = time;
7896: my %groups = ();
7897: foreach my $key (keys(%env)) {
7898: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
7899: my ($start,$end) = split(/\./,$env{$key});
7900: if (($end!=0) && ($end<$now)) { next; }
7901: if (($start!=0) && ($start>$now)) { next; }
7902: if ($1 eq $cdom && $2 eq $cnum) {
7903: $groups{$3} = $env{$key} ;
7904: }
7905: }
7906: }
7907: return %groups;
7908: }
7909:
7910: sub get_group_membership {
7911: my ($cdom,$cnum,$group) = @_;
7912: return(&dump('groupmembership',$cdom,$cnum,$group));
7913: }
7914:
7915: sub get_users_groups {
7916: my ($udom,$uname,$courseid) = @_;
7917: my @usersgroups;
7918: my $cachetime=1800;
7919:
7920: my $hashid="$udom:$uname:$courseid";
7921: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7922: if (defined($cached)) {
7923: @usersgroups = split(/:/,$grouplist);
7924: } else {
7925: $grouplist = '';
7926: my $courseurl = &courseid_to_courseurl($courseid);
7927: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
7928: my $access_end = $env{'course.'.$courseid.
7929: '.default_enrollment_end_date'};
7930: my $now = time;
7931: foreach my $key (keys(%roleshash)) {
7932: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7933: my $group = $1;
7934: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7935: my $start = $2;
7936: my $end = $1;
7937: if ($start == -1) { next; } # deleted from group
7938: if (($start!=0) && ($start>$now)) { next; }
7939: if (($end!=0) && ($end<$now)) {
7940: if ($access_end && $access_end < $now) {
7941: if ($access_end - $end < 86400) {
7942: push(@usersgroups,$group);
7943: }
7944: }
7945: next;
7946: }
7947: push(@usersgroups,$group);
7948: }
7949: }
7950: }
7951: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7952: $grouplist = join(':',@usersgroups);
7953: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
7954: }
7955: return @usersgroups;
7956: }
7957:
7958: sub devalidate_getgroups_cache {
7959: my ($udom,$uname,$cdom,$cnum)=@_;
7960: my $courseid = $cdom.'_'.$cnum;
7961:
7962: my $hashid="$udom:$uname:$courseid";
7963: &devalidate_cache_new('getgroups',$hashid);
7964: }
7965:
7966: # ------------------------------------------------------------------ Plain Text
7967:
7968: sub plaintext {
7969: my ($short,$type,$cid,$forcedefault) = @_;
7970: if ($short =~ m{^cr/}) {
7971: return (split('/',$short))[-1];
7972: }
7973: if (!defined($cid)) {
7974: $cid = $env{'request.course.id'};
7975: }
7976: my %rolenames = (
7977: Course => 'std',
7978: Community => 'alt1',
7979: );
7980: if ($cid ne '') {
7981: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7982: unless ($forcedefault) {
7983: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7984: &Apache::lonlocal::mt_escape(\$roletext);
7985: return &Apache::lonlocal::mt($roletext);
7986: }
7987: }
7988: }
7989: if ((defined($type)) && (defined($rolenames{$type})) &&
7990: (defined($rolenames{$type})) &&
7991: (defined($prp{$short}{$rolenames{$type}}))) {
7992: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
7993: } elsif ($cid ne '') {
7994: my $crstype = $env{'course.'.$cid.'.type'};
7995: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7996: (defined($prp{$short}{$rolenames{$crstype}}))) {
7997: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7998: }
7999: }
8000: return &Apache::lonlocal::mt($prp{$short}{'std'});
8001: }
8002:
8003: # ----------------------------------------------------------------- Assign Role
8004:
8005: sub assignrole {
8006: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8007: $context)=@_;
8008: my $mrole;
8009: if ($role =~ /^cr\//) {
8010: my $cwosec=$url;
8011: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
8012: unless (&allowed('ccr',$cwosec)) {
8013: my $refused = 1;
8014: if ($context eq 'requestcourses') {
8015: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8016: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8017: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8018: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8019: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8020: if ($crsenv{'internal.courseowner'} eq
8021: $env{'user.name'}.':'.$env{'user.domain'}) {
8022: $refused = '';
8023: }
8024: }
8025: }
8026: }
8027: }
8028: if ($refused) {
8029: &logthis('Refused custom assignrole: '.
8030: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8031: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8032: return 'refused';
8033: }
8034: }
8035: $mrole='cr';
8036: } elsif ($role =~ /^gr\//) {
8037: my $cwogrp=$url;
8038: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
8039: unless (&allowed('mdg',$cwogrp)) {
8040: &logthis('Refused group assignrole: '.
8041: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8042: $env{'user.name'}.' at '.$env{'user.domain'});
8043: return 'refused';
8044: }
8045: $mrole='gr';
8046: } else {
8047: my $cwosec=$url;
8048: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
8049: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8050: my $refused;
8051: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8052: if (!(&allowed('c'.$role,$url))) {
8053: $refused = 1;
8054: }
8055: } else {
8056: $refused = 1;
8057: }
8058: if ($refused) {
8059: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8060: if (!$selfenroll && $context eq 'course') {
8061: my %crsenv;
8062: if ($role eq 'cc' || $role eq 'co') {
8063: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8064: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8065: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8066: if ($crsenv{'internal.courseowner'} eq
8067: $env{'user.name'}.':'.$env{'user.domain'}) {
8068: $refused = '';
8069: }
8070: }
8071: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8072: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8073: if ($crsenv{'internal.courseowner'} eq
8074: $env{'user.name'}.':'.$env{'user.domain'}) {
8075: $refused = '';
8076: }
8077: }
8078: }
8079: }
8080: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8081: $refused = '';
8082: } elsif ($context eq 'requestcourses') {
8083: my @possroles = ('st','ta','ep','in','cc','co');
8084: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
8085: my $wrongcc;
8086: if ($cnum =~ /^$match_community$/) {
8087: $wrongcc = 1 if ($role eq 'cc');
8088: } else {
8089: $wrongcc = 1 if ($role eq 'co');
8090: }
8091: unless ($wrongcc) {
8092: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8093: if ($crsenv{'internal.courseowner'} eq
8094: $env{'user.name'}.':'.$env{'user.domain'}) {
8095: $refused = '';
8096: }
8097: }
8098: }
8099: } elsif ($context eq 'requestauthor') {
8100: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8101: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8102: if ($env{'environment.requestauthor'} eq 'automatic') {
8103: $refused = '';
8104: } else {
8105: my %domdefaults = &get_domain_defaults($udom);
8106: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8107: my $checkbystatus;
8108: if ($env{'user.adv'}) {
8109: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8110: if ($disposition eq 'automatic') {
8111: $refused = '';
8112: } elsif ($disposition eq '') {
8113: $checkbystatus = 1;
8114: }
8115: } else {
8116: $checkbystatus = 1;
8117: }
8118: if ($checkbystatus) {
8119: if ($env{'environment.inststatus'}) {
8120: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8121: foreach my $type (@inststatuses) {
8122: if (($type ne '') &&
8123: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8124: $refused = '';
8125: }
8126: }
8127: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8128: $refused = '';
8129: }
8130: }
8131: }
8132: }
8133: }
8134: }
8135: if ($refused) {
8136: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8137: ' '.$role.' '.$end.' '.$start.' by '.
8138: $env{'user.name'}.' at '.$env{'user.domain'});
8139: return 'refused';
8140: }
8141: }
8142: } elsif ($role eq 'au') {
8143: if ($url ne '/'.$udom.'/') {
8144: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8145: ' to assign author role for '.$uname.':'.$udom.
8146: ' in domain: '.$url.' refused (wrong domain).');
8147: return 'refused';
8148: }
8149: }
8150: $mrole=$role;
8151: }
8152: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8153: "$udom:$uname:$url".'_'."$mrole=$role";
8154: if ($end) { $command.='_'.$end; }
8155: if ($start) {
8156: if ($end) {
8157: $command.='_'.$start;
8158: } else {
8159: $command.='_0_'.$start;
8160: }
8161: }
8162: my $origstart = $start;
8163: my $origend = $end;
8164: my $delflag;
8165: # actually delete
8166: if ($deleteflag) {
8167: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
8168: # modify command to delete the role
8169: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
8170: "$udom:$uname:$url".'_'."$mrole";
8171: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
8172: # set start and finish to negative values for userrolelog
8173: $start=-1;
8174: $end=-1;
8175: $delflag = 1;
8176: }
8177: }
8178: # send command
8179: my $answer=&reply($command,&homeserver($uname,$udom));
8180: # log new user role if status is ok
8181: if ($answer eq 'ok') {
8182: &userrolelog($role,$uname,$udom,$url,$start,$end);
8183: if (($role eq 'cc') || ($role eq 'in') ||
8184: ($role eq 'ep') || ($role eq 'ad') ||
8185: ($role eq 'ta') || ($role eq 'st') ||
8186: ($role=~/^cr/) || ($role eq 'gr') ||
8187: ($role eq 'co')) {
8188: # for course roles, perform group memberships changes triggered by role change.
8189: unless ($role =~ /^gr/) {
8190: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8191: $origstart,$selfenroll,$context);
8192: }
8193: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8194: $selfenroll,$context);
8195: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8196: ($role eq 'au') || ($role eq 'dc')) {
8197: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8198: $context);
8199: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8200: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8201: $context);
8202: }
8203: if ($role eq 'cc') {
8204: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8205: }
8206: }
8207: return $answer;
8208: }
8209:
8210: sub autoupdate_coowners {
8211: my ($url,$end,$start,$uname,$udom) = @_;
8212: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8213: if (($cdom ne '') && ($cnum ne '')) {
8214: my $now = time;
8215: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8216: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8217: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8218: my $instcode = $coursehash{'internal.coursecode'};
8219: if ($instcode ne '') {
8220: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8221: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
8222: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
8223: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8224: if ($result eq 'valid') {
8225: if ($coursehash{'internal.co-owners'}) {
8226: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8227: push(@newcoowners,$coowner);
8228: }
8229: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8230: push(@newcoowners,$uname.':'.$udom);
8231: }
8232: @newcoowners = sort(@newcoowners);
8233: } else {
8234: push(@newcoowners,$uname.':'.$udom);
8235: }
8236: } else {
8237: if ($coursehash{'internal.co-owners'}) {
8238: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8239: unless ($coowner eq $uname.':'.$udom) {
8240: push(@newcoowners,$coowner);
8241: }
8242: }
8243: unless (@newcoowners > 0) {
8244: $delcoowners = 1;
8245: $coowners = '';
8246: }
8247: }
8248: }
8249: if (@newcoowners || $delcoowners) {
8250: &store_coowners($cdom,$cnum,$coursehash{'home'},
8251: $delcoowners,@newcoowners);
8252: }
8253: }
8254: }
8255: }
8256: }
8257: }
8258: }
8259:
8260: sub store_coowners {
8261: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8262: my $cid = $cdom.'_'.$cnum;
8263: my ($coowners,$delresult,$putresult);
8264: if (@newcoowners) {
8265: $coowners = join(',',@newcoowners);
8266: my %coownershash = (
8267: 'internal.co-owners' => $coowners,
8268: );
8269: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8270: if ($putresult eq 'ok') {
8271: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8272: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8273: }
8274: }
8275: }
8276: if ($delcoowners) {
8277: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8278: if ($delresult eq 'ok') {
8279: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8280: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8281: }
8282: }
8283: }
8284: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8285: my %crsinfo =
8286: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8287: if (ref($crsinfo{$cid}) eq 'HASH') {
8288: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8289: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8290: }
8291: }
8292: }
8293:
8294: # -------------------------------------------------- Modify user authentication
8295: # Overrides without validation
8296:
8297: sub modifyuserauth {
8298: my ($udom,$uname,$umode,$upass)=@_;
8299: my $uhome=&homeserver($uname,$udom);
8300: unless (&allowed('mau',$udom)) { return 'refused'; }
8301: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
8302: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8303: ' in domain '.$env{'request.role.domain'});
8304: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8305: &escape($upass),$uhome);
8306: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
8307: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8308: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8309: &log($udom,,$uname,$uhome,
8310: 'Authentication changed by '.$env{'user.domain'}.', '.
8311: $env{'user.name'}.', '.$umode.
8312: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8313: unless ($reply eq 'ok') {
8314: &logthis('Authentication mode error: '.$reply);
8315: return 'error: '.$reply;
8316: }
8317: return 'ok';
8318: }
8319:
8320: # --------------------------------------------------------------- Modify a user
8321:
8322: sub modifyuser {
8323: my ($udom, $uname, $uid,
8324: $umode, $upass, $first,
8325: $middle, $last, $gene,
8326: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
8327: $udom= &LONCAPA::clean_domain($udom);
8328: $uname=&LONCAPA::clean_username($uname);
8329: my $showcandelete = 'none';
8330: if (ref($candelete) eq 'ARRAY') {
8331: if (@{$candelete} > 0) {
8332: $showcandelete = join(', ',@{$candelete});
8333: }
8334: }
8335: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
8336: $umode.', '.$first.', '.$middle.', '.
8337: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
8338: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8339: ' desiredhome not specified').
8340: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8341: ' in domain '.$env{'request.role.domain'});
8342: my $uhome=&homeserver($uname,$udom,'true');
8343: my $newuser;
8344: if ($uhome eq 'no_host') {
8345: $newuser = 1;
8346: }
8347: # ----------------------------------------------------------------- Create User
8348: if (($uhome eq 'no_host') &&
8349: (($umode && $upass) || ($umode eq 'localauth'))) {
8350: my $unhome='';
8351: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
8352: $unhome = $desiredhome;
8353: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8354: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
8355: } else { # load balancing routine for determining $unhome
8356: my $loadm=10000000;
8357: my %servers = &get_servers($udom,'library');
8358: foreach my $tryserver (keys(%servers)) {
8359: my $answer=reply('load',$tryserver);
8360: if (($answer=~/\d+/) && ($answer<$loadm)) {
8361: $loadm=$answer;
8362: $unhome=$tryserver;
8363: }
8364: }
8365: }
8366: if (($unhome eq '') || ($unhome eq 'no_host')) {
8367: return 'error: unable to find a home server for '.$uname.
8368: ' in domain '.$udom;
8369: }
8370: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8371: &escape($upass),$unhome);
8372: unless ($reply eq 'ok') {
8373: return 'error: '.$reply;
8374: }
8375: $uhome=&homeserver($uname,$udom,'true');
8376: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
8377: return 'error: unable verify users home machine.';
8378: }
8379: } # End of creation of new user
8380: # ---------------------------------------------------------------------- Add ID
8381: if ($uid) {
8382: $uid=~tr/A-Z/a-z/;
8383: my %uidhash=&idrget($udom,$uname);
8384: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8385: && (!$forceid)) {
8386: unless ($uid eq $uidhash{$uname}) {
8387: return 'error: user id "'.$uid.'" does not match '.
8388: 'current user id "'.$uidhash{$uname}.'".';
8389: }
8390: } else {
8391: &idput($udom,($uname => $uid));
8392: }
8393: }
8394: # -------------------------------------------------------------- Add names, etc
8395: my @tmp=&get('environment',
8396: ['firstname','middlename','lastname','generation','id',
8397: 'permanentemail','inststatus'],
8398: $udom,$uname);
8399: my (%names,%oldnames);
8400: if ($tmp[0] =~ m/^error:.*/) {
8401: %names=();
8402: } else {
8403: %names = @tmp;
8404: %oldnames = %names;
8405: }
8406: #
8407: # If name, email and/or uid are blank (e.g., because an uploaded file
8408: # of users did not contain them), do not overwrite existing values
8409: # unless field is in $candelete array ref.
8410: #
8411:
8412: my @fields = ('firstname','middlename','lastname','generation',
8413: 'permanentemail','id');
8414: my %newvalues;
8415: if (ref($candelete) eq 'ARRAY') {
8416: foreach my $field (@fields) {
8417: if (grep(/^\Q$field\E$/,@{$candelete})) {
8418: if ($field eq 'firstname') {
8419: $names{$field} = $first;
8420: } elsif ($field eq 'middlename') {
8421: $names{$field} = $middle;
8422: } elsif ($field eq 'lastname') {
8423: $names{$field} = $last;
8424: } elsif ($field eq 'generation') {
8425: $names{$field} = $gene;
8426: } elsif ($field eq 'permanentemail') {
8427: $names{$field} = $email;
8428: } elsif ($field eq 'id') {
8429: $names{$field} = $uid;
8430: }
8431: }
8432: }
8433: }
8434: if ($first) { $names{'firstname'} = $first; }
8435: if (defined($middle)) { $names{'middlename'} = $middle; }
8436: if ($last) { $names{'lastname'} = $last; }
8437: if (defined($gene)) { $names{'generation'} = $gene; }
8438: if ($email) {
8439: $email=~s/[^\w\@\.\-\,]//gs;
8440: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
8441: }
8442: if ($uid) { $names{'id'} = $uid; }
8443: if (defined($inststatus)) {
8444: $names{'inststatus'} = '';
8445: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8446: if (ref($usertypes) eq 'HASH') {
8447: my @okstatuses;
8448: foreach my $item (split(/:/,$inststatus)) {
8449: if (defined($usertypes->{$item})) {
8450: push(@okstatuses,$item);
8451: }
8452: }
8453: if (@okstatuses) {
8454: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8455: }
8456: }
8457: }
8458: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
8459: $umode.', '.$first.', '.$middle.', '.
8460: $last.', '.$gene.', '.$email.', '.$inststatus;
8461: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8462: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8463: } else {
8464: $logmsg .= ' during self creation';
8465: }
8466: my $changed;
8467: if ($newuser) {
8468: $changed = 1;
8469: } else {
8470: foreach my $field (@fields) {
8471: if ($names{$field} ne $oldnames{$field}) {
8472: $changed = 1;
8473: last;
8474: }
8475: }
8476: }
8477: unless ($changed) {
8478: $logmsg = 'No changes in user information needed for: '.$logmsg;
8479: &logthis($logmsg);
8480: return 'ok';
8481: }
8482: my $reply = &put('environment', \%names, $udom,$uname);
8483: if ($reply ne 'ok') {
8484: return 'error: '.$reply;
8485: }
8486: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8487: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8488: }
8489: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8490: &devalidate_cache_new('namescache',$uname.':'.$udom);
8491: $logmsg = 'Success modifying user '.$logmsg;
8492: &logthis($logmsg);
8493: return 'ok';
8494: }
8495:
8496: # -------------------------------------------------------------- Modify student
8497:
8498: sub modifystudent {
8499: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
8500: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
8501: $selfenroll,$context,$inststatus,$credits)=@_;
8502: if (!$cid) {
8503: unless ($cid=$env{'request.course.id'}) {
8504: return 'not_in_class';
8505: }
8506: }
8507: # --------------------------------------------------------------- Make the user
8508: my $reply=&modifyuser
8509: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
8510: $desiredhome,$email,$inststatus);
8511: unless ($reply eq 'ok') { return $reply; }
8512: # This will cause &modify_student_enrollment to get the uid from the
8513: # student's environment
8514: $uid = undef if (!$forceid);
8515: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
8516: $gene,$usec,$end,$start,$type,$locktype,
8517: $cid,$selfenroll,$context,$credits);
8518: return $reply;
8519: }
8520:
8521: sub modify_student_enrollment {
8522: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8523: $locktype,$cid,$selfenroll,$context,$credits) = @_;
8524: my ($cdom,$cnum,$chome);
8525: if (!$cid) {
8526: unless ($cid=$env{'request.course.id'}) {
8527: return 'not_in_class';
8528: }
8529: $cdom=$env{'course.'.$cid.'.domain'};
8530: $cnum=$env{'course.'.$cid.'.num'};
8531: } else {
8532: ($cdom,$cnum)=split(/_/,$cid);
8533: }
8534: $chome=$env{'course.'.$cid.'.home'};
8535: if (!$chome) {
8536: $chome=&homeserver($cnum,$cdom);
8537: }
8538: if (!$chome) { return 'unknown_course'; }
8539: # Make sure the user exists
8540: my $uhome=&homeserver($uname,$udom);
8541: if (($uhome eq '') || ($uhome eq 'no_host')) {
8542: return 'error: no such user';
8543: }
8544: # Get student data if we were not given enough information
8545: if (!defined($first) || $first eq '' ||
8546: !defined($last) || $last eq '' ||
8547: !defined($uid) || $uid eq '' ||
8548: !defined($middle) || $middle eq '' ||
8549: !defined($gene) || $gene eq '') {
8550: # They did not supply us with enough data to enroll the student, so
8551: # we need to pick up more information.
8552: my %tmp = &get('environment',
8553: ['firstname','middlename','lastname', 'generation','id']
8554: ,$udom,$uname);
8555:
8556: #foreach my $key (keys(%tmp)) {
8557: # &logthis("key $key = ".$tmp{$key});
8558: #}
8559: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8560: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8561: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
8562: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
8563: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8564: }
8565: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
8566: my $user = "$uname:$udom";
8567: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
8568: my $reply=cput('classlist',
8569: {$user =>
8570: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
8571: $cdom,$cnum);
8572: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8573: &devalidate_getsection_cache($udom,$uname,$cid);
8574: } else {
8575: return 'error: '.$reply;
8576: }
8577: # Add student role to user
8578: my $uurl='/'.$cid;
8579: $uurl=~s/\_/\//g;
8580: if ($usec) {
8581: $uurl.='/'.$usec;
8582: }
8583: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8584: $selfenroll,$context);
8585: if ($result ne 'ok') {
8586: if ($old_entry{$user} ne '') {
8587: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8588: } else {
8589: $reply = &del('classlist',[$user],$cdom,$cnum);
8590: }
8591: }
8592: return $result;
8593: }
8594:
8595: sub format_name {
8596: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8597: my $name;
8598: if ($first ne 'lastname') {
8599: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8600: } else {
8601: if ($lastname=~/\S/) {
8602: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8603: $name=~s/\s+,/,/;
8604: } else {
8605: $name.= $firstname.' '.$middlename.' '.$generation;
8606: }
8607: }
8608: $name=~s/^\s+//;
8609: $name=~s/\s+$//;
8610: $name=~s/\s+/ /g;
8611: return $name;
8612: }
8613:
8614: # ------------------------------------------------- Write to course preferences
8615:
8616: sub writecoursepref {
8617: my ($courseid,%prefs)=@_;
8618: $courseid=~s/^\///;
8619: $courseid=~s/\_/\//g;
8620: my ($cdomain,$cnum)=split(/\//,$courseid);
8621: my $chome=homeserver($cnum,$cdomain);
8622: if (($chome eq '') || ($chome eq 'no_host')) {
8623: return 'error: no such course';
8624: }
8625: my $cstring='';
8626: foreach my $pref (keys(%prefs)) {
8627: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
8628: }
8629: $cstring=~s/\&$//;
8630: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8631: }
8632:
8633: # ---------------------------------------------------------- Make/modify course
8634:
8635: sub createcourse {
8636: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
8637: $course_owner,$crstype,$cnum,$context,$category)=@_;
8638: $url=&declutter($url);
8639: my $cid='';
8640: if ($context eq 'requestcourses') {
8641: my $can_create = 0;
8642: my ($ownername,$ownerdom) = split(':',$course_owner);
8643: if ($udom eq $ownerdom) {
8644: if (&usertools_access($ownername,$ownerdom,$category,undef,
8645: $context)) {
8646: $can_create = 1;
8647: }
8648: } else {
8649: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8650: $category);
8651: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8652: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8653: if (@curr > 0) {
8654: my @options = qw(approval validate autolimit);
8655: my $optregex = join('|',@options);
8656: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8657: $can_create = 1;
8658: }
8659: }
8660: }
8661: }
8662: if ($can_create) {
8663: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8664: unless (&allowed('ccc',$udom)) {
8665: return 'refused';
8666: }
8667: }
8668: } else {
8669: return 'refused';
8670: }
8671: } elsif (!&allowed('ccc',$udom)) {
8672: return 'refused';
8673: }
8674: # --------------------------------------------------------------- Get Unique ID
8675: my $uname;
8676: if ($cnum =~ /^$match_courseid$/) {
8677: my $chome=&homeserver($cnum,$udom,'true');
8678: if (($chome eq '') || ($chome eq 'no_host')) {
8679: $uname = $cnum;
8680: } else {
8681: $uname = &generate_coursenum($udom,$crstype);
8682: }
8683: } else {
8684: $uname = &generate_coursenum($udom,$crstype);
8685: }
8686: return $uname if ($uname =~ /^error/);
8687: # -------------------------------------------------- Check supplied server name
8688: if (!defined($course_server)) {
8689: if (defined(&domain($udom,'primary'))) {
8690: $course_server = &domain($udom,'primary');
8691: } else {
8692: $course_server = $env{'user.home'};
8693: }
8694: }
8695: my %host_servers =
8696: &Apache::lonnet::get_servers($udom,'library');
8697: unless ($host_servers{$course_server}) {
8698: return 'error: invalid home server for course: '.$course_server;
8699: }
8700: # ------------------------------------------------------------- Make the course
8701: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
8702: $course_server);
8703: unless ($reply eq 'ok') { return 'error: '.$reply; }
8704: my $uhome=&homeserver($uname,$udom,'true');
8705: if (($uhome eq '') || ($uhome eq 'no_host')) {
8706: return 'error: no such course';
8707: }
8708: # ----------------------------------------------------------------- Course made
8709: # log existence
8710: my $now = time;
8711: my $newcourse = {
8712: $udom.'_'.$uname => {
8713: description => $description,
8714: inst_code => $inst_code,
8715: owner => $course_owner,
8716: type => $crstype,
8717: creator => $env{'user.name'}.':'.
8718: $env{'user.domain'},
8719: created => $now,
8720: context => $context,
8721: },
8722: };
8723: &courseidput($udom,$newcourse,$uhome,'notime');
8724: # set toplevel url
8725: my $topurl=$url;
8726: unless ($nonstandard) {
8727: # ------------------------------------------ For standard courses, make top url
8728: my $mapurl=&clutter($url);
8729: if ($mapurl eq '/res/') { $mapurl=''; }
8730: $env{'form.initmap'}=(<<ENDINITMAP);
8731: <map>
8732: <resource id="1" type="start"></resource>
8733: <resource id="2" src="$mapurl"></resource>
8734: <resource id="3" type="finish"></resource>
8735: <link index="1" from="1" to="2"></link>
8736: <link index="2" from="2" to="3"></link>
8737: </map>
8738: ENDINITMAP
8739: $topurl=&declutter(
8740: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
8741: );
8742: }
8743: # ----------------------------------------------------------- Write preferences
8744: &writecoursepref($udom.'_'.$uname,
8745: ('description' => $description,
8746: 'url' => $topurl,
8747: 'internal.creator' => $env{'user.name'}.':'.
8748: $env{'user.domain'},
8749: 'internal.created' => $now,
8750: 'internal.creationcontext' => $context)
8751: );
8752: return '/'.$udom.'/'.$uname;
8753: }
8754:
8755: # ------------------------------------------------------------------- Create ID
8756: sub generate_coursenum {
8757: my ($udom,$crstype) = @_;
8758: my $domdesc = &domain($udom);
8759: return 'error: invalid domain' if ($domdesc eq '');
8760: my $first;
8761: if ($crstype eq 'Community') {
8762: $first = '0';
8763: } else {
8764: $first = int(1+rand(9));
8765: }
8766: my $uname=$first.
8767: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8768: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8769: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8770: # ----------------------------------------------- Make sure that does not exist
8771: my $uhome=&homeserver($uname,$udom,'true');
8772: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8773: if ($crstype eq 'Community') {
8774: $first = '0';
8775: } else {
8776: $first = int(1+rand(9));
8777: }
8778: $uname=$first.
8779: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8780: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8781: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8782: $uhome=&homeserver($uname,$udom,'true');
8783: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8784: return 'error: unable to generate unique course-ID';
8785: }
8786: }
8787: return $uname;
8788: }
8789:
8790: sub is_course {
8791: my ($cdom, $cnum) = scalar(@_) == 1 ?
8792: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8793:
8794: return unless $cdom and $cnum;
8795:
8796: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8797: '.');
8798:
8799: return unless(exists($courses{$cdom.'_'.$cnum}));
8800: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
8801: }
8802:
8803: sub store_userdata {
8804: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8805: my $result;
8806: if ($datakey ne '') {
8807: if (ref($storehash) eq 'HASH') {
8808: if ($udom eq '' || $uname eq '') {
8809: $udom = $env{'user.domain'};
8810: $uname = $env{'user.name'};
8811: }
8812: my $uhome=&homeserver($uname,$udom);
8813: if (($uhome eq '') || ($uhome eq 'no_host')) {
8814: $result = 'error: no_host';
8815: } else {
8816: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8817: $storehash->{'host'} = $perlvar{'lonHostID'};
8818:
8819: my $namevalue='';
8820: foreach my $key (keys(%{$storehash})) {
8821: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8822: }
8823: $namevalue=~s/\&$//;
8824: unless ($namespace eq 'courserequests') {
8825: $datakey = &escape($datakey);
8826: }
8827: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8828: $namevalue,$uhome);
8829: }
8830: } else {
8831: $result = 'error: data to store was not a hash reference';
8832: }
8833: } else {
8834: $result= 'error: invalid requestkey';
8835: }
8836: return $result;
8837: }
8838:
8839: # ---------------------------------------------------------- Assign Custom Role
8840:
8841: sub assigncustomrole {
8842: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
8843: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
8844: $end,$start,$deleteflag,$selfenroll,$context);
8845: }
8846:
8847: # ----------------------------------------------------------------- Revoke Role
8848:
8849: sub revokerole {
8850: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
8851: my $now=time;
8852: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
8853: }
8854:
8855: # ---------------------------------------------------------- Revoke Custom Role
8856:
8857: sub revokecustomrole {
8858: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
8859: my $now=time;
8860: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
8861: $deleteflag,$selfenroll,$context);
8862: }
8863:
8864: # ------------------------------------------------------------ Disk usage
8865: sub diskusage {
8866: my ($udom,$uname,$directorypath,$getpropath)=@_;
8867: $directorypath =~ s/\/$//;
8868: my $listing=&reply('du2:'.&escape($directorypath).':'
8869: .&escape($getpropath).':'.&escape($uname).':'
8870: .&escape($udom),homeserver($uname,$udom));
8871: if ($listing eq 'unknown_cmd') {
8872: if ($getpropath) {
8873: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8874: }
8875: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8876: }
8877: return $listing;
8878: }
8879:
8880: sub is_locked {
8881: my ($file_name, $domain, $user, $which) = @_;
8882: my @check;
8883: my $is_locked;
8884: push (@check,$file_name);
8885: my %locked = &get('file_permissions',\@check,
8886: $env{'user.domain'},$env{'user.name'});
8887: my ($tmp)=keys(%locked);
8888: if ($tmp=~/^error:/) { undef(%locked); }
8889:
8890: if (ref($locked{$file_name}) eq 'ARRAY') {
8891: $is_locked = 'false';
8892: foreach my $entry (@{$locked{$file_name}}) {
8893: if (ref($entry) eq 'ARRAY') {
8894: $is_locked = 'true';
8895: if (ref($which) eq 'ARRAY') {
8896: push(@{$which},$entry);
8897: } else {
8898: last;
8899: }
8900: }
8901: }
8902: } else {
8903: $is_locked = 'false';
8904: }
8905: return $is_locked;
8906: }
8907:
8908: sub declutter_portfile {
8909: my ($file) = @_;
8910: $file =~ s{^(/portfolio/|portfolio/)}{/};
8911: return $file;
8912: }
8913:
8914: # ------------------------------------------------------------- Mark as Read Only
8915:
8916: sub mark_as_readonly {
8917: my ($domain,$user,$files,$what) = @_;
8918: my %current_permissions = &dump('file_permissions',$domain,$user);
8919: my ($tmp)=keys(%current_permissions);
8920: if ($tmp=~/^error:/) { undef(%current_permissions); }
8921: foreach my $file (@{$files}) {
8922: $file = &declutter_portfile($file);
8923: push(@{$current_permissions{$file}},$what);
8924: }
8925: &put('file_permissions',\%current_permissions,$domain,$user);
8926: return;
8927: }
8928:
8929: # ------------------------------------------------------------Save Selected Files
8930:
8931: sub save_selected_files {
8932: my ($user, $path, @files) = @_;
8933: my $filename = $user."savedfiles";
8934: my @other_files = &files_not_in_path($user, $path);
8935: open (OUT, '>'.$tmpdir.$filename);
8936: foreach my $file (@files) {
8937: print (OUT $env{'form.currentpath'}.$file."\n");
8938: }
8939: foreach my $file (@other_files) {
8940: print (OUT $file."\n");
8941: }
8942: close (OUT);
8943: return 'ok';
8944: }
8945:
8946: sub clear_selected_files {
8947: my ($user) = @_;
8948: my $filename = $user."savedfiles";
8949: open (OUT, '>'.LONCAPA::tempdir().$filename);
8950: print (OUT undef);
8951: close (OUT);
8952: return ("ok");
8953: }
8954:
8955: sub files_in_path {
8956: my ($user, $path) = @_;
8957: my $filename = $user."savedfiles";
8958: my %return_files;
8959: open (IN, '<'.LONCAPA::tempdir().$filename);
8960: while (my $line_in = <IN>) {
8961: chomp ($line_in);
8962: my @paths_and_file = split (m!/!, $line_in);
8963: my $file_part = pop (@paths_and_file);
8964: my $path_part = join ('/', @paths_and_file);
8965: $path_part.='/';
8966: my $path_and_file = $path_part.$file_part;
8967: if ($path_part eq $path) {
8968: $return_files{$file_part}= 'selected';
8969: }
8970: }
8971: close (IN);
8972: return (\%return_files);
8973: }
8974:
8975: # called in portfolio select mode, to show files selected NOT in current directory
8976: sub files_not_in_path {
8977: my ($user, $path) = @_;
8978: my $filename = $user."savedfiles";
8979: my @return_files;
8980: my $path_part;
8981: open(IN, '<'.LONCAPA::.$filename);
8982: while (my $line = <IN>) {
8983: #ok, I know it's clunky, but I want it to work
8984: my @paths_and_file = split(m|/|, $line);
8985: my $file_part = pop(@paths_and_file);
8986: chomp($file_part);
8987: my $path_part = join('/', @paths_and_file);
8988: $path_part .= '/';
8989: my $path_and_file = $path_part.$file_part;
8990: if ($path_part ne $path) {
8991: push(@return_files, ($path_and_file));
8992: }
8993: }
8994: close(OUT);
8995: return (@return_files);
8996: }
8997:
8998: #----------------------------------------------Get portfolio file permissions
8999:
9000: sub get_portfile_permissions {
9001: my ($domain,$user) = @_;
9002: my %current_permissions = &dump('file_permissions',$domain,$user);
9003: my ($tmp)=keys(%current_permissions);
9004: if ($tmp=~/^error:/) { undef(%current_permissions); }
9005: return \%current_permissions;
9006: }
9007:
9008: #---------------------------------------------Get portfolio file access controls
9009:
9010: sub get_access_controls {
9011: my ($current_permissions,$group,$file) = @_;
9012: my %access;
9013: my $real_file = $file;
9014: $file =~ s/\.meta$//;
9015: if (defined($file)) {
9016: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9017: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
9018: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
9019: }
9020: }
9021: } else {
9022: foreach my $key (keys(%{$current_permissions})) {
9023: if ($key =~ /\0accesscontrol$/) {
9024: if (defined($group)) {
9025: if ($key !~ m-^\Q$group\E/-) {
9026: next;
9027: }
9028: }
9029: my ($fullpath) = split(/\0/,$key);
9030: if (ref($$current_permissions{$key}) eq 'HASH') {
9031: foreach my $control (keys(%{$$current_permissions{$key}})) {
9032: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9033: }
9034: }
9035: }
9036: }
9037: }
9038: return %access;
9039: }
9040:
9041: sub modify_access_controls {
9042: my ($file_name,$changes,$domain,$user)=@_;
9043: my ($outcome,$deloutcome);
9044: my %store_permissions;
9045: my %new_values;
9046: my %new_control;
9047: my %translation;
9048: my @deletions = ();
9049: my $now = time;
9050: if (exists($$changes{'activate'})) {
9051: if (ref($$changes{'activate'}) eq 'HASH') {
9052: my @newitems = sort(keys(%{$$changes{'activate'}}));
9053: my $numnew = scalar(@newitems);
9054: for (my $i=0; $i<$numnew; $i++) {
9055: my $newkey = $newitems[$i];
9056: my $newid = &Apache::loncommon::get_cgi_id();
9057: if ($newkey =~ /^\d+:/) {
9058: $newkey =~ s/^(\d+)/$newid/;
9059: $translation{$1} = $newid;
9060: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9061: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9062: $translation{$1} = $newid;
9063: }
9064: $new_values{$file_name."\0".$newkey} =
9065: $$changes{'activate'}{$newitems[$i]};
9066: $new_control{$newkey} = $now;
9067: }
9068: }
9069: }
9070: my %todelete;
9071: my %changed_items;
9072: foreach my $action ('delete','update') {
9073: if (exists($$changes{$action})) {
9074: if (ref($$changes{$action}) eq 'HASH') {
9075: foreach my $key (keys(%{$$changes{$action}})) {
9076: my ($itemnum) = ($key =~ /^([^:]+):/);
9077: if ($action eq 'delete') {
9078: $todelete{$itemnum} = 1;
9079: } else {
9080: $changed_items{$itemnum} = $key;
9081: }
9082: }
9083: }
9084: }
9085: }
9086: # get lock on access controls for file.
9087: my $lockhash = {
9088: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9089: ':'.$env{'user.domain'},
9090: };
9091: my $tries = 0;
9092: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9093:
9094: while (($gotlock ne 'ok') && $tries <3) {
9095: $tries ++;
9096: sleep 1;
9097: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9098: }
9099: if ($gotlock eq 'ok') {
9100: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9101: my ($tmp)=keys(%curr_permissions);
9102: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9103: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9104: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9105: if (ref($curr_controls) eq 'HASH') {
9106: foreach my $control_item (keys(%{$curr_controls})) {
9107: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9108: if (defined($todelete{$itemnum})) {
9109: push(@deletions,$file_name."\0".$control_item);
9110: } else {
9111: if (defined($changed_items{$itemnum})) {
9112: $new_control{$changed_items{$itemnum}} = $now;
9113: push(@deletions,$file_name."\0".$control_item);
9114: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9115: } else {
9116: $new_control{$control_item} = $$curr_controls{$control_item};
9117: }
9118: }
9119: }
9120: }
9121: }
9122: my ($group);
9123: if (&is_course($domain,$user)) {
9124: ($group,my $file) = split(/\//,$file_name,2);
9125: }
9126: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9127: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9128: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9129: # remove lock
9130: my @del_lock = ($file_name."\0".'locked_access_records');
9131: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
9132: my $sqlresult =
9133: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
9134: $group);
9135: } else {
9136: $outcome = "error: could not obtain lockfile\n";
9137: }
9138: return ($outcome,$deloutcome,\%new_values,\%translation);
9139: }
9140:
9141: sub make_public_indefinitely {
9142: my ($requrl) = @_;
9143: my $now = time;
9144: my $action = 'activate';
9145: my $aclnum = 0;
9146: if (&is_portfolio_url($requrl)) {
9147: my (undef,$udom,$unum,$file_name,$group) =
9148: &parse_portfolio_url($requrl);
9149: my $current_perms = &get_portfile_permissions($udom,$unum);
9150: my %access_controls = &get_access_controls($current_perms,
9151: $group,$file_name);
9152: foreach my $key (keys(%{$access_controls{$file_name}})) {
9153: my ($num,$scope,$end,$start) =
9154: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9155: if ($scope eq 'public') {
9156: if ($start <= $now && $end == 0) {
9157: $action = 'none';
9158: } else {
9159: $action = 'update';
9160: $aclnum = $num;
9161: }
9162: last;
9163: }
9164: }
9165: if ($action eq 'none') {
9166: return 'ok';
9167: } else {
9168: my %changes;
9169: my $newend = 0;
9170: my $newstart = $now;
9171: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9172: $changes{$action}{$newkey} = {
9173: type => 'public',
9174: time => {
9175: start => $newstart,
9176: end => $newend,
9177: },
9178: };
9179: my ($outcome,$deloutcome,$new_values,$translation) =
9180: &modify_access_controls($file_name,\%changes,$udom,$unum);
9181: return $outcome;
9182: }
9183: } else {
9184: return 'invalid';
9185: }
9186: }
9187:
9188: #------------------------------------------------------Get Marked as Read Only
9189:
9190: sub get_marked_as_readonly {
9191: my ($domain,$user,$what,$group) = @_;
9192: my $current_permissions = &get_portfile_permissions($domain,$user);
9193: my @readonly_files;
9194: my $cmp1=$what;
9195: if (ref($what)) { $cmp1=join('',@{$what}) };
9196: while (my ($file_name,$value) = each(%{$current_permissions})) {
9197: if (defined($group)) {
9198: if ($file_name !~ m-^\Q$group\E/-) {
9199: next;
9200: }
9201: }
9202: if (ref($value) eq "ARRAY"){
9203: foreach my $stored_what (@{$value}) {
9204: my $cmp2=$stored_what;
9205: if (ref($stored_what) eq 'ARRAY') {
9206: $cmp2=join('',@{$stored_what});
9207: }
9208: if ($cmp1 eq $cmp2) {
9209: push(@readonly_files, $file_name);
9210: last;
9211: } elsif (!defined($what)) {
9212: push(@readonly_files, $file_name);
9213: last;
9214: }
9215: }
9216: }
9217: }
9218: return @readonly_files;
9219: }
9220: #-----------------------------------------------------------Get Marked as Read Only Hash
9221:
9222: sub get_marked_as_readonly_hash {
9223: my ($current_permissions,$group,$what) = @_;
9224: my %readonly_files;
9225: while (my ($file_name,$value) = each(%{$current_permissions})) {
9226: if (defined($group)) {
9227: if ($file_name !~ m-^\Q$group\E/-) {
9228: next;
9229: }
9230: }
9231: if (ref($value) eq "ARRAY"){
9232: foreach my $stored_what (@{$value}) {
9233: if (ref($stored_what) eq 'ARRAY') {
9234: foreach my $lock_descriptor(@{$stored_what}) {
9235: if ($lock_descriptor eq 'graded') {
9236: $readonly_files{$file_name} = 'graded';
9237: } elsif ($lock_descriptor eq 'handback') {
9238: $readonly_files{$file_name} = 'handback';
9239: } else {
9240: if (!exists($readonly_files{$file_name})) {
9241: $readonly_files{$file_name} = 'locked';
9242: }
9243: }
9244: }
9245: }
9246: }
9247: }
9248: }
9249: return %readonly_files;
9250: }
9251: # ------------------------------------------------------------ Unmark as Read Only
9252:
9253: sub unmark_as_readonly {
9254: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9255: # for portfolio submissions, $what contains [$symb,$crsid]
9256: my ($domain,$user,$what,$file_name,$group) = @_;
9257: $file_name = &declutter_portfile($file_name);
9258: my $symb_crs = $what;
9259: if (ref($what)) { $symb_crs=join('',@$what); }
9260: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
9261: my ($tmp)=keys(%current_permissions);
9262: if ($tmp=~/^error:/) { undef(%current_permissions); }
9263: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
9264: foreach my $file (@readonly_files) {
9265: my $clean_file = &declutter_portfile($file);
9266: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
9267: my $current_locks = $current_permissions{$file};
9268: my @new_locks;
9269: my @del_keys;
9270: if (ref($current_locks) eq "ARRAY"){
9271: foreach my $locker (@{$current_locks}) {
9272: my $compare=$locker;
9273: if (ref($locker) eq 'ARRAY') {
9274: $compare=join('',@{$locker});
9275: if ($compare ne $symb_crs) {
9276: push(@new_locks, $locker);
9277: }
9278: }
9279: }
9280: if (scalar(@new_locks) > 0) {
9281: $current_permissions{$file} = \@new_locks;
9282: } else {
9283: push(@del_keys, $file);
9284: &del('file_permissions',\@del_keys, $domain, $user);
9285: delete($current_permissions{$file});
9286: }
9287: }
9288: }
9289: &put('file_permissions',\%current_permissions,$domain,$user);
9290: return;
9291: }
9292:
9293: # ------------------------------------------------------------ Directory lister
9294:
9295: sub dirlist {
9296: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
9297: $uri=~s/^\///;
9298: $uri=~s/\/$//;
9299: my ($udom, $uname);
9300: if ($getuserdir) {
9301: $udom = $userdomain;
9302: $uname = $username;
9303: } else {
9304: (undef,$udom,$uname)=split(/\//,$uri);
9305: if(defined($userdomain)) {
9306: $udom = $userdomain;
9307: }
9308: if(defined($username)) {
9309: $uname = $username;
9310: }
9311: }
9312: my ($dirRoot,$listing,@listing_results);
9313:
9314: $dirRoot = $perlvar{'lonDocRoot'};
9315: if (defined($getpropath)) {
9316: $dirRoot = &propath($udom,$uname);
9317: $dirRoot =~ s/\/$//;
9318: } elsif (defined($getuserdir)) {
9319: my $subdir=$uname.'__';
9320: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9321: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9322: ."/$udom/$subdir/$uname";
9323: } elsif (defined($alternateRoot)) {
9324: $dirRoot = $alternateRoot;
9325: }
9326:
9327: if($udom) {
9328: if($uname) {
9329: my $uhome = &homeserver($uname,$udom);
9330: if ($uhome eq 'no_host') {
9331: return ([],'no_host');
9332: }
9333: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
9334: .$getuserdir.':'.&escape($dirRoot)
9335: .':'.&escape($uname).':'.&escape($udom),$uhome);
9336: if ($listing eq 'unknown_cmd') {
9337: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
9338: } else {
9339: @listing_results = map { &unescape($_); } split(/:/,$listing);
9340: }
9341: if ($listing eq 'unknown_cmd') {
9342: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
9343: @listing_results = split(/:/,$listing);
9344: } else {
9345: @listing_results = map { &unescape($_); } split(/:/,$listing);
9346: }
9347: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9348: ($listing eq 'rejected') || ($listing eq 'refused') ||
9349: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9350: return ([],$listing);
9351: } else {
9352: return (\@listing_results);
9353: }
9354: } elsif(!$alternateRoot) {
9355: my (%allusers,%listerror);
9356: my %servers = &get_servers($udom,'library');
9357: foreach my $tryserver (keys(%servers)) {
9358: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9359: &escape($udom),$tryserver);
9360: if ($listing eq 'unknown_cmd') {
9361: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9362: $udom, $tryserver);
9363: } else {
9364: @listing_results = map { &unescape($_); } split(/:/,$listing);
9365: }
9366: if ($listing eq 'unknown_cmd') {
9367: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9368: $udom, $tryserver);
9369: @listing_results = split(/:/,$listing);
9370: } else {
9371: @listing_results =
9372: map { &unescape($_); } split(/:/,$listing);
9373: }
9374: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9375: ($listing eq 'rejected') || ($listing eq 'refused') ||
9376: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9377: $listerror{$tryserver} = $listing;
9378: } else {
9379: foreach my $line (@listing_results) {
9380: my ($entry) = split(/&/,$line,2);
9381: $allusers{$entry} = 1;
9382: }
9383: }
9384: }
9385: my @alluserslist=();
9386: foreach my $user (sort(keys(%allusers))) {
9387: push(@alluserslist,$user.'&user');
9388: }
9389: return (\@alluserslist);
9390: } else {
9391: return ([],'missing username');
9392: }
9393: } elsif(!defined($getpropath)) {
9394: my $path = $perlvar{'lonDocRoot'}.'/res/';
9395: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9396: return (\@all_domains);
9397: } else {
9398: return ([],'missing domain');
9399: }
9400: }
9401:
9402: # --------------------------------------------- GetFileTimestamp
9403: # This function utilizes dirlist and returns the date stamp for
9404: # when it was last modified. It will also return an error of -1
9405: # if an error occurs
9406:
9407: sub GetFileTimestamp {
9408: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
9409: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9410: $studentName = &LONCAPA::clean_username($studentName);
9411: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9412: undef,$getuserdir);
9413: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9414: return -1;
9415: }
9416: if (ref($fileref) eq 'ARRAY') {
9417: my @stats = split('&',$fileref->[0]);
9418: # @stats contains first the filename, then the stat output
9419: return $stats[10]; # so this is 10 instead of 9.
9420: } else {
9421: return -1;
9422: }
9423: }
9424:
9425: sub stat_file {
9426: my ($uri) = @_;
9427: $uri = &clutter_with_no_wrapper($uri);
9428:
9429: my ($udom,$uname,$file);
9430: if ($uri =~ m-^/(uploaded|editupload)/-) {
9431: ($udom,$uname,$file) =
9432: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
9433: $file = 'userfiles/'.$file;
9434: }
9435: if ($uri =~ m-^/res/-) {
9436: ($udom,$uname) =
9437: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
9438: $file = $uri;
9439: }
9440:
9441: if (!$udom || !$uname || !$file) {
9442: # unable to handle the uri
9443: return ();
9444: }
9445: my $getpropath;
9446: if ($file =~ /^userfiles\//) {
9447: $getpropath = 1;
9448: }
9449: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9450: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9451: return ();
9452: } else {
9453: if (ref($listref) eq 'ARRAY') {
9454: my @stats = split('&',$listref->[0]);
9455: shift(@stats); #filename is first
9456: return @stats;
9457: }
9458: }
9459: return ();
9460: }
9461:
9462: # -------------------------------------------------------- Value of a Condition
9463:
9464: # gets the value of a specific preevaluated condition
9465: # stored in the string $env{user.state.<cid>}
9466: # or looks up a condition reference in the bighash and if if hasn't
9467: # already been evaluated recurses into docondval to get the value of
9468: # the condition, then memoizing it to
9469: # $env{user.state.<cid>.<condition>}
9470: sub directcondval {
9471: my $number=shift;
9472: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
9473: &Apache::lonuserstate::evalstate();
9474: }
9475: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9476: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9477: } elsif ($number =~ /^_/) {
9478: my $sub_condition;
9479: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9480: &GDBM_READER(),0640)) {
9481: $sub_condition=$bighash{'conditions'.$number};
9482: untie(%bighash);
9483: }
9484: my $value = &docondval($sub_condition);
9485: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
9486: return $value;
9487: }
9488: if ($env{'user.state.'.$env{'request.course.id'}}) {
9489: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
9490: } else {
9491: return 2;
9492: }
9493: }
9494:
9495: # get the collection of conditions for this resource
9496: sub condval {
9497: my $condidx=shift;
9498: my $allpathcond='';
9499: foreach my $cond (split(/\|/,$condidx)) {
9500: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9501: $allpathcond.=
9502: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9503: }
9504: }
9505: $allpathcond=~s/\|$//;
9506: return &docondval($allpathcond);
9507: }
9508:
9509: #evaluates an expression of conditions
9510: sub docondval {
9511: my ($allpathcond) = @_;
9512: my $result=0;
9513: if ($env{'request.course.id'}
9514: && defined($allpathcond)) {
9515: my $operand='|';
9516: my @stack;
9517: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9518: if ($chunk eq '(') {
9519: push @stack,($operand,$result);
9520: } elsif ($chunk eq ')') {
9521: my $before=pop @stack;
9522: if (pop @stack eq '&') {
9523: $result=$result>$before?$before:$result;
9524: } else {
9525: $result=$result>$before?$result:$before;
9526: }
9527: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9528: $operand=$chunk;
9529: } else {
9530: my $new=directcondval($chunk);
9531: if ($operand eq '&') {
9532: $result=$result>$new?$new:$result;
9533: } else {
9534: $result=$result>$new?$result:$new;
9535: }
9536: }
9537: }
9538: }
9539: return $result;
9540: }
9541:
9542: # ---------------------------------------------------- Devalidate courseresdata
9543:
9544: sub devalidatecourseresdata {
9545: my ($coursenum,$coursedomain)=@_;
9546: my $hashid=$coursenum.':'.$coursedomain;
9547: &devalidate_cache_new('courseres',$hashid);
9548: }
9549:
9550:
9551: # --------------------------------------------------- Course Resourcedata Query
9552: #
9553: # Parameters:
9554: # $coursenum - Number of the course.
9555: # $coursedomain - Domain at which the course was created.
9556: # Returns:
9557: # A hash of the course parameters along (I think) with timestamps
9558: # and version info.
9559:
9560: sub get_courseresdata {
9561: my ($coursenum,$coursedomain)=@_;
9562: my $coursehom=&homeserver($coursenum,$coursedomain);
9563: my $hashid=$coursenum.':'.$coursedomain;
9564: my ($result,$cached)=&is_cached_new('courseres',$hashid);
9565: my %dumpreply;
9566: unless (defined($cached)) {
9567: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
9568: $result=\%dumpreply;
9569: my ($tmp) = keys(%dumpreply);
9570: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9571: &do_cache_new('courseres',$hashid,$result,600);
9572: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9573: return $tmp;
9574: } elsif ($tmp =~ /^(error)/) {
9575: $result=undef;
9576: &do_cache_new('courseres',$hashid,$result,600);
9577: }
9578: }
9579: return $result;
9580: }
9581:
9582: sub devalidateuserresdata {
9583: my ($uname,$udom)=@_;
9584: my $hashid="$udom:$uname";
9585: &devalidate_cache_new('userres',$hashid);
9586: }
9587:
9588: sub get_userresdata {
9589: my ($uname,$udom)=@_;
9590: #most student don\'t have any data set, check if there is some data
9591: if (&EXT_cache_status($udom,$uname)) { return undef; }
9592:
9593: my $hashid="$udom:$uname";
9594: my ($result,$cached)=&is_cached_new('userres',$hashid);
9595: if (!defined($cached)) {
9596: my %resourcedata=&dump('resourcedata',$udom,$uname);
9597: $result=\%resourcedata;
9598: &do_cache_new('userres',$hashid,$result,600);
9599: }
9600: my ($tmp)=keys(%$result);
9601: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9602: return $result;
9603: }
9604: #error 2 occurs when the .db doesn't exist
9605: if ($tmp!~/error: 2 /) {
9606: &logthis("<font color=\"blue\">WARNING:".
9607: " Trying to get resource data for ".
9608: $uname." at ".$udom.": ".
9609: $tmp."</font>");
9610: } elsif ($tmp=~/error: 2 /) {
9611: #&EXT_cache_set($udom,$uname);
9612: &do_cache_new('userres',$hashid,undef,600);
9613: undef($tmp); # not really an error so don't send it back
9614: }
9615: return $tmp;
9616: }
9617: #----------------------------------------------- resdata - return resource data
9618: # Purpose:
9619: # Return resource data for either users or for a course.
9620: # Parameters:
9621: # $name - Course/user name.
9622: # $domain - Name of the domain the user/course is registered on.
9623: # $type - Type of thing $name is (must be 'course' or 'user'
9624: # @which - Array of names of resources desired.
9625: # Returns:
9626: # The value of the first reasource in @which that is found in the
9627: # resource hash.
9628: # Exceptional Conditions:
9629: # If the $type passed in is not valid (not the string 'course' or
9630: # 'user', an undefined reference is returned.
9631: # If none of the resources are found, an undef is returned
9632: sub resdata {
9633: my ($name,$domain,$type,@which)=@_;
9634: my $result;
9635: if ($type eq 'course') {
9636: $result=&get_courseresdata($name,$domain);
9637: } elsif ($type eq 'user') {
9638: $result=&get_userresdata($name,$domain);
9639: }
9640: if (!ref($result)) { return $result; }
9641: foreach my $item (@which) {
9642: if (defined($result->{$item->[0]})) {
9643: return [$result->{$item->[0]},$item->[1]];
9644: }
9645: }
9646: return undef;
9647: }
9648:
9649: sub get_numsuppfiles {
9650: my ($cnum,$cdom,$ignorecache)=@_;
9651: my $hashid=$cnum.':'.$cdom;
9652: my ($suppcount,$cached);
9653: unless ($ignorecache) {
9654: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9655: }
9656: unless (defined($cached)) {
9657: my $chome=&homeserver($cnum,$cdom);
9658: unless ($chome eq 'no_host') {
9659: ($suppcount,my $errors) = (0,0);
9660: my $suppmap = 'supplemental.sequence';
9661: ($suppcount,$errors) =
9662: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9663: }
9664: &do_cache_new('suppcount',$hashid,$suppcount,600);
9665: }
9666: return $suppcount;
9667: }
9668:
9669: #
9670: # EXT resource caching routines
9671: #
9672:
9673: sub clear_EXT_cache_status {
9674: &delenv('cache.EXT.');
9675: }
9676:
9677: sub EXT_cache_status {
9678: my ($target_domain,$target_user) = @_;
9679: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9680: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
9681: # We know already the user has no data
9682: return 1;
9683: } else {
9684: return 0;
9685: }
9686: }
9687:
9688: sub EXT_cache_set {
9689: my ($target_domain,$target_user) = @_;
9690: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9691: #&appenv({$cachename => time});
9692: }
9693:
9694: # --------------------------------------------------------- Value of a Variable
9695: sub EXT {
9696:
9697: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
9698: unless ($varname) { return ''; }
9699: #get real user name/domain, courseid and symb
9700: my $courseid;
9701: my $publicuser;
9702: if ($symbparm) {
9703: $symbparm=&get_symb_from_alias($symbparm);
9704: }
9705: if (!($uname && $udom)) {
9706: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
9707: if (!$symbparm) { $symbparm=$cursymb; }
9708: } else {
9709: $courseid=$env{'request.course.id'};
9710: }
9711: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9712: my $rest;
9713: if (defined($therest[0])) {
9714: $rest=join('.',@therest);
9715: } else {
9716: $rest='';
9717: }
9718:
9719: my $qualifierrest=$qualifier;
9720: if ($rest) { $qualifierrest.='.'.$rest; }
9721: my $spacequalifierrest=$space;
9722: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
9723: if ($realm eq 'user') {
9724: # --------------------------------------------------------------- user.resource
9725: if ($space eq 'resource') {
9726: if ( (defined($Apache::lonhomework::parsing_a_problem)
9727: || defined($Apache::lonhomework::parsing_a_task))
9728: &&
9729: ($symbparm eq &symbread()) ) {
9730: # if we are in the middle of processing the resource the
9731: # get the value we are planning on committing
9732: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9733: return $Apache::lonhomework::results{$qualifierrest};
9734: } else {
9735: return $Apache::lonhomework::history{$qualifierrest};
9736: }
9737: } else {
9738: my %restored;
9739: if ($publicuser || $env{'request.state'} eq 'construct') {
9740: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9741: } else {
9742: %restored=&restore($symbparm,$courseid,$udom,$uname);
9743: }
9744: return $restored{$qualifierrest};
9745: }
9746: # ----------------------------------------------------------------- user.access
9747: } elsif ($space eq 'access') {
9748: # FIXME - not supporting calls for a specific user
9749: return &allowed($qualifier,$rest);
9750: # ------------------------------------------ user.preferences, user.environment
9751: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
9752: if (($uname eq $env{'user.name'}) &&
9753: ($udom eq $env{'user.domain'})) {
9754: return $env{join('.',('environment',$qualifierrest))};
9755: } else {
9756: my %returnhash;
9757: if (!$publicuser) {
9758: %returnhash=&userenvironment($udom,$uname,
9759: $qualifierrest);
9760: }
9761: return $returnhash{$qualifierrest};
9762: }
9763: # ----------------------------------------------------------------- user.course
9764: } elsif ($space eq 'course') {
9765: # FIXME - not supporting calls for a specific user
9766: return $env{join('.',('request.course',$qualifier))};
9767: # ------------------------------------------------------------------- user.role
9768: } elsif ($space eq 'role') {
9769: # FIXME - not supporting calls for a specific user
9770: my ($role,$where)=split(/\./,$env{'request.role'});
9771: if ($qualifier eq 'value') {
9772: return $role;
9773: } elsif ($qualifier eq 'extent') {
9774: return $where;
9775: }
9776: # ----------------------------------------------------------------- user.domain
9777: } elsif ($space eq 'domain') {
9778: return $udom;
9779: # ------------------------------------------------------------------- user.name
9780: } elsif ($space eq 'name') {
9781: return $uname;
9782: # ---------------------------------------------------- Any other user namespace
9783: } else {
9784: my %reply;
9785: if (!$publicuser) {
9786: %reply=&get($space,[$qualifierrest],$udom,$uname);
9787: }
9788: return $reply{$qualifierrest};
9789: }
9790: } elsif ($realm eq 'query') {
9791: # ---------------------------------------------- pull stuff out of query string
9792: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9793: [$spacequalifierrest]);
9794: return $env{'form.'.$spacequalifierrest};
9795: } elsif ($realm eq 'request') {
9796: # ------------------------------------------------------------- request.browser
9797: if ($space eq 'browser') {
9798: return $env{'browser.'.$qualifier};
9799: # ------------------------------------------------------------ request.filename
9800: } else {
9801: return $env{'request.'.$spacequalifierrest};
9802: }
9803: } elsif ($realm eq 'course') {
9804: # ---------------------------------------------------------- course.description
9805: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
9806: } elsif ($realm eq 'resource') {
9807:
9808: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
9809: if (!$symbparm) { $symbparm=&symbread(); }
9810: }
9811:
9812: if ($qualifier eq '') {
9813: if ($space eq 'title') {
9814: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9815: return &gettitle($symbparm);
9816: }
9817:
9818: if ($space eq 'map') {
9819: my ($map) = &decode_symb($symbparm);
9820: return &symbread($map);
9821: }
9822: if ($space eq 'maptitle') {
9823: my ($map) = &decode_symb($symbparm);
9824: return &gettitle($map);
9825: }
9826: if ($space eq 'filename') {
9827: if ($symbparm) {
9828: return &clutter((&decode_symb($symbparm))[2]);
9829: }
9830: return &hreflocation('',$env{'request.filename'});
9831: }
9832:
9833: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9834: if ($space eq 'visibleparts') {
9835: my $navmap = Apache::lonnavmaps::navmap->new();
9836: my $item;
9837: if (ref($navmap)) {
9838: my $res = $navmap->getBySymb($symbparm);
9839: my $parts = $res->parts();
9840: if (ref($parts) eq 'ARRAY') {
9841: $item = join(',',@{$parts});
9842: }
9843: undef($navmap);
9844: }
9845: return $item;
9846: }
9847: }
9848: }
9849:
9850: my ($section, $group, @groups);
9851: my ($courselevelm,$courselevel);
9852: if (($courseid eq '') && ($cid)) {
9853: $courseid = $cid;
9854: }
9855: if (($symbparm && $courseid) &&
9856: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
9857:
9858: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
9859:
9860: # ----------------------------------------------------- Cascading lookup scheme
9861: my $symbp=$symbparm;
9862: my $mapp=&deversion((&decode_symb($symbp))[0]);
9863:
9864: my $symbparm=$symbp.'.'.$spacequalifierrest;
9865: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9866:
9867: if (($env{'user.name'} eq $uname) &&
9868: ($env{'user.domain'} eq $udom)) {
9869: $section=$env{'request.course.sec'};
9870: @groups = split(/:/,$env{'request.course.groups'});
9871: @groups=&sort_course_groups($courseid,@groups);
9872: } else {
9873: if (! defined($usection)) {
9874: $section=&getsection($udom,$uname,$courseid);
9875: } else {
9876: $section = $usection;
9877: }
9878: @groups = &get_users_groups($udom,$uname,$courseid);
9879: }
9880:
9881: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9882: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9883: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9884:
9885: $courselevel=$courseid.'.'.$spacequalifierrest;
9886: my $courselevelr=$courseid.'.'.$symbparm;
9887: $courselevelm=$courseid.'.'.$mapparm;
9888:
9889: # ----------------------------------------------------------- first, check user
9890:
9891: my $userreply=&resdata($uname,$udom,'user',
9892: ([$courselevelr,'resource'],
9893: [$courselevelm,'map' ],
9894: [$courselevel, 'course' ]));
9895: if (defined($userreply)) { return &get_reply($userreply); }
9896:
9897: # ------------------------------------------------ second, check some of course
9898: my $coursereply;
9899: if (@groups > 0) {
9900: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9901: $mapparm,$spacequalifierrest);
9902: if (defined($coursereply)) { return &get_reply($coursereply); }
9903: }
9904:
9905: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9906: $env{'course.'.$courseid.'.domain'},
9907: 'course',
9908: ([$seclevelr, 'resource'],
9909: [$seclevelm, 'map' ],
9910: [$seclevel, 'course' ],
9911: [$courselevelr,'resource']));
9912: if (defined($coursereply)) { return &get_reply($coursereply); }
9913:
9914: # ------------------------------------------------------ third, check map parms
9915: my %parmhash=();
9916: my $thisparm='';
9917: if (tie(%parmhash,'GDBM_File',
9918: $env{'request.course.fn'}.'_parms.db',
9919: &GDBM_READER(),0640)) {
9920: $thisparm=$parmhash{$symbparm};
9921: untie(%parmhash);
9922: }
9923: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
9924: }
9925: # ------------------------------------------ fourth, look in resource metadata
9926:
9927: $spacequalifierrest=~s/\./\_/;
9928: my $filename;
9929: if (!$symbparm) { $symbparm=&symbread(); }
9930: if ($symbparm) {
9931: $filename=(&decode_symb($symbparm))[2];
9932: } else {
9933: $filename=$env{'request.filename'};
9934: }
9935: my $metadata=&metadata($filename,$spacequalifierrest);
9936: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9937: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
9938: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9939:
9940: # ---------------------------------------------- fourth, look in rest of course
9941: if ($symbparm && defined($courseid) &&
9942: $courseid eq $env{'request.course.id'}) {
9943: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9944: $env{'course.'.$courseid.'.domain'},
9945: 'course',
9946: ([$courselevelm,'map' ],
9947: [$courselevel, 'course']));
9948: if (defined($coursereply)) { return &get_reply($coursereply); }
9949: }
9950: # ------------------------------------------------------------------ Cascade up
9951: unless ($space eq '0') {
9952: my @parts=split(/_/,$space);
9953: my $id=pop(@parts);
9954: my $part=join('_',@parts);
9955: if ($part eq '') { $part='0'; }
9956: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
9957: $symbparm,$udom,$uname,$section,1);
9958: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
9959: }
9960: if ($recurse) { return undef; }
9961: my $pack_def=&packages_tab_default($filename,$varname);
9962: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
9963: # ---------------------------------------------------- Any other user namespace
9964: } elsif ($realm eq 'environment') {
9965: # ----------------------------------------------------------------- environment
9966: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9967: return $env{'environment.'.$spacequalifierrest};
9968: } else {
9969: if ($uname eq 'anonymous' && $udom eq '') {
9970: return '';
9971: }
9972: my %returnhash=&userenvironment($udom,$uname,
9973: $spacequalifierrest);
9974: return $returnhash{$spacequalifierrest};
9975: }
9976: } elsif ($realm eq 'system') {
9977: # ----------------------------------------------------------------- system.time
9978: if ($space eq 'time') {
9979: return time;
9980: }
9981: } elsif ($realm eq 'server') {
9982: # ----------------------------------------------------------------- system.time
9983: if ($space eq 'name') {
9984: return $ENV{'SERVER_NAME'};
9985: }
9986: }
9987: return '';
9988: }
9989:
9990: sub get_reply {
9991: my ($reply_value) = @_;
9992: if (ref($reply_value) eq 'ARRAY') {
9993: if (wantarray) {
9994: return @$reply_value;
9995: }
9996: return $reply_value->[0];
9997: } else {
9998: return $reply_value;
9999: }
10000: }
10001:
10002: sub check_group_parms {
10003: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10004: my @groupitems = ();
10005: my $resultitem;
10006: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10007: foreach my $group (@{$groups}) {
10008: foreach my $level (@levels) {
10009: my $item = $courseid.'.['.$group.'].'.$level->[0];
10010: push(@groupitems,[$item,$level->[1]]);
10011: }
10012: }
10013: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10014: $env{'course.'.$courseid.'.domain'},
10015: 'course',@groupitems);
10016: return $coursereply;
10017: }
10018:
10019: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10020: my ($courseid,@groups) = @_;
10021: @groups = sort(@groups);
10022: return @groups;
10023: }
10024:
10025: sub packages_tab_default {
10026: my ($uri,$varname)=@_;
10027: my (undef,$part,$name)=split(/\./,$varname);
10028:
10029: my (@extension,@specifics,$do_default);
10030: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10031: my ($pack_type,$pack_part)=split(/_/,$package,2);
10032: if ($pack_type eq 'default') {
10033: $do_default=1;
10034: } elsif ($pack_type eq 'extension') {
10035: push(@extension,[$package,$pack_type,$pack_part]);
10036: } elsif ($pack_part eq $part || $pack_type eq 'part') {
10037: # only look at packages defaults for packages that this id is
10038: push(@specifics,[$package,$pack_type,$pack_part]);
10039: }
10040: }
10041: # first look for a package that matches the requested part id
10042: foreach my $package (@specifics) {
10043: my (undef,$pack_type,$pack_part)=@{$package};
10044: next if ($pack_part ne $part);
10045: if (defined($packagetab{"$pack_type&$name&default"})) {
10046: return $packagetab{"$pack_type&$name&default"};
10047: }
10048: }
10049: # look for any possible matching non extension_ package
10050: foreach my $package (@specifics) {
10051: my (undef,$pack_type,$pack_part)=@{$package};
10052: if (defined($packagetab{"$pack_type&$name&default"})) {
10053: return $packagetab{"$pack_type&$name&default"};
10054: }
10055: if ($pack_type eq 'part') { $pack_part='0'; }
10056: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10057: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10058: }
10059: }
10060: # look for any posible extension_ match
10061: foreach my $package (@extension) {
10062: my ($package,$pack_type)=@{$package};
10063: if (defined($packagetab{"$pack_type&$name&default"})) {
10064: return $packagetab{"$pack_type&$name&default"};
10065: }
10066: if (defined($packagetab{$package."&$name&default"})) {
10067: return $packagetab{$package."&$name&default"};
10068: }
10069: }
10070: # look for a global default setting
10071: if ($do_default && defined($packagetab{"default&$name&default"})) {
10072: return $packagetab{"default&$name&default"};
10073: }
10074: return undef;
10075: }
10076:
10077: sub add_prefix_and_part {
10078: my ($prefix,$part)=@_;
10079: my $keyroot;
10080: if (defined($prefix) && $prefix !~ /^__/) {
10081: # prefix that has a part already
10082: $keyroot=$prefix;
10083: } elsif (defined($prefix)) {
10084: # prefix that is missing a part
10085: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10086: } else {
10087: # no prefix at all
10088: if (defined($part)) { $keyroot='_'.$part; }
10089: }
10090: return $keyroot;
10091: }
10092:
10093: # ---------------------------------------------------------------- Get metadata
10094:
10095: my %metaentry;
10096: my %importedpartids;
10097: sub metadata {
10098: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10099: $uri=&declutter($uri);
10100: # if it is a non metadata possible uri return quickly
10101: if (($uri eq '') ||
10102: (($uri =~ m|^/*adm/|) &&
10103: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10104: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10105: return undef;
10106: }
10107: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
10108: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10109: return undef;
10110: }
10111: my $filename=$uri;
10112: $uri=~s/\.meta$//;
10113: #
10114: # Is the metadata already cached?
10115: # Look at timestamp of caching
10116: # Everything is cached by the main uri, libraries are never directly cached
10117: #
10118: if (!defined($liburi)) {
10119: my ($result,$cached)=&is_cached_new('meta',$uri);
10120: if (defined($cached)) { return $result->{':'.$what}; }
10121: }
10122: {
10123: # Imported parts would go here
10124: my %importedids=();
10125: my @origfileimportpartids=();
10126: my $importedparts=0;
10127: #
10128: # Is this a recursive call for a library?
10129: #
10130: # if (! exists($metacache{$uri})) {
10131: # $metacache{$uri}={};
10132: # }
10133: my $cachetime = 60*60;
10134: if ($liburi) {
10135: $liburi=&declutter($liburi);
10136: $filename=$liburi;
10137: } else {
10138: &devalidate_cache_new('meta',$uri);
10139: undef(%metaentry);
10140: }
10141: my %metathesekeys=();
10142: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10143: my $metastring;
10144: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10145: my $which = &hreflocation('','/'.($liburi || $uri));
10146: $metastring =
10147: &Apache::lonnet::ssi_body($which,
10148: ('grade_target' => 'meta'));
10149: $cachetime = 1; # only want this cached in the child not long term
10150: } elsif (($uri !~ m -^(editupload)/-) &&
10151: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10152: my $file=&filelocation('',&clutter($filename));
10153: #push(@{$metaentry{$uri.'.file'}},$file);
10154: $metastring=&getfile($file);
10155: }
10156: my $parser=HTML::LCParser->new(\$metastring);
10157: my $token;
10158: undef %metathesekeys;
10159: while ($token=$parser->get_token) {
10160: if ($token->[0] eq 'S') {
10161: if (defined($token->[2]->{'package'})) {
10162: #
10163: # This is a package - get package info
10164: #
10165: my $package=$token->[2]->{'package'};
10166: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10167: if (defined($token->[2]->{'id'})) {
10168: $keyroot.='_'.$token->[2]->{'id'};
10169: }
10170: if ($metaentry{':packages'}) {
10171: $metaentry{':packages'}.=','.$package.$keyroot;
10172: } else {
10173: $metaentry{':packages'}=$package.$keyroot;
10174: }
10175: foreach my $pack_entry (keys(%packagetab)) {
10176: my $part=$keyroot;
10177: $part=~s/^\_//;
10178: if ($pack_entry=~/^\Q$package\E\&/ ||
10179: $pack_entry=~/^\Q$package\E_0\&/) {
10180: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10181: # ignore package.tab specified default values
10182: # here &package_tab_default() will fetch those
10183: if ($subp eq 'default') { next; }
10184: my $value=$packagetab{$pack_entry};
10185: my $unikey;
10186: if ($pack =~ /_0$/) {
10187: $unikey='parameter_0_'.$name;
10188: $part=0;
10189: } else {
10190: $unikey='parameter'.$keyroot.'_'.$name;
10191: }
10192: if ($subp eq 'display') {
10193: $value.=' [Part: '.$part.']';
10194: }
10195: $metaentry{':'.$unikey.'.part'}=$part;
10196: $metathesekeys{$unikey}=1;
10197: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10198: $metaentry{':'.$unikey.'.'.$subp}=$value;
10199: }
10200: if (defined($metaentry{':'.$unikey.'.default'})) {
10201: $metaentry{':'.$unikey}=
10202: $metaentry{':'.$unikey.'.default'};
10203: }
10204: }
10205: }
10206: } else {
10207: #
10208: # This is not a package - some other kind of start tag
10209: #
10210: my $entry=$token->[1];
10211: my $unikey='';
10212:
10213: if ($entry eq 'import') {
10214: #
10215: # Importing a library here
10216: #
10217: my $location=$parser->get_text('/import');
10218: my $dir=$filename;
10219: $dir=~s|[^/]*$||;
10220: $location=&filelocation($dir,$location);
10221:
10222: my $importmode=$token->[2]->{'importmode'};
10223: if ($importmode eq 'problem') {
10224: # Import as problem/response
10225: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10226: } elsif ($importmode eq 'part') {
10227: # Import as part(s)
10228: $importedparts=1;
10229: # We need to get the original file and the imported file to get the part order correct
10230: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10231: # Load and inspect original file
10232: if ($#origfileimportpartids<0) {
10233: undef(%importedpartids);
10234: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10235: my $origfile=&getfile($origfilelocation);
10236: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10237: }
10238:
10239: # Load and inspect imported file
10240: my $impfile=&getfile($location);
10241: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10242: if ($#impfilepartids>=0) {
10243: # This problem had parts
10244: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10245: } else {
10246: # Importing by turning a single problem into a problem part
10247: # It gets the import-tags ID as part-ID
10248: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10249: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10250: }
10251: } else {
10252: # Normal import
10253: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10254: if (defined($token->[2]->{'id'})) {
10255: $unikey.='_'.$token->[2]->{'id'};
10256: }
10257: }
10258:
10259: if ($depthcount<20) {
10260: my $metadata =
10261: &metadata($uri,'keys', $location,$unikey,
10262: $depthcount+1);
10263: foreach my $meta (split(',',$metadata)) {
10264: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10265: $metathesekeys{$meta}=1;
10266: }
10267:
10268: }
10269: } else {
10270: #
10271: # Not importing, some other kind of non-package, non-library start tag
10272: #
10273: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10274: if (defined($token->[2]->{'id'})) {
10275: $unikey.='_'.$token->[2]->{'id'};
10276: }
10277: if (defined($token->[2]->{'name'})) {
10278: $unikey.='_'.$token->[2]->{'name'};
10279: }
10280: $metathesekeys{$unikey}=1;
10281: foreach my $param (@{$token->[3]}) {
10282: $metaentry{':'.$unikey.'.'.$param} =
10283: $token->[2]->{$param};
10284: }
10285: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10286: my $default=$metaentry{':'.$unikey.'.default'};
10287: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10288: # only ws inside the tag, and not in default, so use default
10289: # as value
10290: $metaentry{':'.$unikey}=$default;
10291: } elsif ( $internaltext =~ /\S/ ) {
10292: # something interesting inside the tag
10293: $metaentry{':'.$unikey}=$internaltext;
10294: } else {
10295: # no interesting values, don't set a default
10296: }
10297: # end of not-a-package not-a-library import
10298: }
10299: # end of not-a-package start tag
10300: }
10301: # the next is the end of "start tag"
10302: }
10303: }
10304: my ($extension) = ($uri =~ /\.(\w+)$/);
10305: $extension = lc($extension);
10306: if ($extension eq 'htm') { $extension='html'; }
10307:
10308: foreach my $key (keys(%packagetab)) {
10309: #no specific packages #how's our extension
10310: if ($key!~/^extension_\Q$extension\E&/) { next; }
10311: &metadata_create_package_def($uri,$key,'extension_'.$extension,
10312: \%metathesekeys);
10313: }
10314:
10315: if (!exists($metaentry{':packages'})
10316: || $packagetab{"import_defaults&extension_$extension"}) {
10317: foreach my $key (keys(%packagetab)) {
10318: #no specific packages well let's get default then
10319: if ($key!~/^default&/) { next; }
10320: &metadata_create_package_def($uri,$key,'default',
10321: \%metathesekeys);
10322: }
10323: }
10324: # are there custom rights to evaluate
10325: if ($metaentry{':copyright'} eq 'custom') {
10326:
10327: #
10328: # Importing a rights file here
10329: #
10330: unless ($depthcount) {
10331: my $location=$metaentry{':customdistributionfile'};
10332: my $dir=$filename;
10333: $dir=~s|[^/]*$||;
10334: $location=&filelocation($dir,$location);
10335: my $rights_metadata =
10336: &metadata($uri,'keys',$location,'_rights',
10337: $depthcount+1);
10338: foreach my $rights (split(',',$rights_metadata)) {
10339: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10340: $metathesekeys{$rights}=1;
10341: }
10342: }
10343: }
10344: # uniqifiy package listing
10345: my %seen;
10346: my @uniq_packages =
10347: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10348: $metaentry{':packages'} = join(',',@uniq_packages);
10349:
10350: if ($importedparts) {
10351: # We had imported parts and need to rebuild partorder
10352: $metaentry{':partorder'}='';
10353: $metathesekeys{'partorder'}=1;
10354: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10355: if ($origfileimportpartids[$index] eq 'part') {
10356: # original part, part of the problem
10357: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10358: } else {
10359: # we have imported parts at this position
10360: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10361: }
10362: }
10363: $metaentry{':partorder'}=~s/^\,//;
10364: }
10365:
10366: $metaentry{':keys'} = join(',',keys(%metathesekeys));
10367: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10368: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10369: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
10370: # this is the end of "was not already recently cached
10371: }
10372: return $metaentry{':'.$what};
10373: }
10374:
10375: sub metadata_create_package_def {
10376: my ($uri,$key,$package,$metathesekeys)=@_;
10377: my ($pack,$name,$subp)=split(/\&/,$key);
10378: if ($subp eq 'default') { next; }
10379:
10380: if (defined($metaentry{':packages'})) {
10381: $metaentry{':packages'}.=','.$package;
10382: } else {
10383: $metaentry{':packages'}=$package;
10384: }
10385: my $value=$packagetab{$key};
10386: my $unikey;
10387: $unikey='parameter_0_'.$name;
10388: $metaentry{':'.$unikey.'.part'}=0;
10389: $$metathesekeys{$unikey}=1;
10390: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10391: $metaentry{':'.$unikey.'.'.$subp}=$value;
10392: }
10393: if (defined($metaentry{':'.$unikey.'.default'})) {
10394: $metaentry{':'.$unikey}=
10395: $metaentry{':'.$unikey.'.default'};
10396: }
10397: }
10398:
10399: sub metadata_generate_part0 {
10400: my ($metadata,$metacache,$uri) = @_;
10401: my %allnames;
10402: foreach my $metakey (keys(%$metadata)) {
10403: if ($metakey=~/^parameter\_(.*)/) {
10404: my $part=$$metacache{':'.$metakey.'.part'};
10405: my $name=$$metacache{':'.$metakey.'.name'};
10406: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10407: $allnames{$name}=$part;
10408: }
10409: }
10410: }
10411: foreach my $name (keys(%allnames)) {
10412: $$metadata{"parameter_0_$name"}=1;
10413: my $key=":parameter_0_$name";
10414: $$metacache{"$key.part"}='0';
10415: $$metacache{"$key.name"}=$name;
10416: $$metacache{"$key.type"}=$$metacache{':parameter_'.
10417: $allnames{$name}.'_'.$name.
10418: '.type'};
10419: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10420: '.display'};
10421: my $expr='[Part: '.$allnames{$name}.']';
10422: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10423: $$metacache{"$key.display"}=$olddis;
10424: }
10425: }
10426:
10427: # ------------------------------------------------------ Devalidate title cache
10428:
10429: sub devalidate_title_cache {
10430: my ($url)=@_;
10431: if (!$env{'request.course.id'}) { return; }
10432: my $symb=&symbread($url);
10433: if (!$symb) { return; }
10434: my $key=$env{'request.course.id'}."\0".$symb;
10435: &devalidate_cache_new('title',$key);
10436: }
10437:
10438: # ------------------------------------------------- Get the title of a course
10439:
10440: sub current_course_title {
10441: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10442: }
10443: # ------------------------------------------------- Get the title of a resource
10444:
10445: sub gettitle {
10446: my $urlsymb=shift;
10447: my $symb=&symbread($urlsymb);
10448: if ($symb) {
10449: my $key=$env{'request.course.id'}."\0".$symb;
10450: my ($result,$cached)=&is_cached_new('title',$key);
10451: if (defined($cached)) {
10452: return $result;
10453: }
10454: my ($map,$resid,$url)=&decode_symb($symb);
10455: my $title='';
10456: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10457: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10458: } else {
10459: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10460: &GDBM_READER(),0640)) {
10461: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10462: $title=$bighash{'title_'.$mapid.'.'.$resid};
10463: untie(%bighash);
10464: }
10465: }
10466: $title=~s/\&colon\;/\:/gs;
10467: if ($title) {
10468: # Remember both $symb and $title for dynamic metadata
10469: $accesshash{$symb.'___crstitle'}=$title;
10470: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10471: # Cache this title and then return it
10472: return &do_cache_new('title',$key,$title,600);
10473: }
10474: $urlsymb=$url;
10475: }
10476: my $title=&metadata($urlsymb,'title');
10477: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10478: return $title;
10479: }
10480:
10481: sub get_slot {
10482: my ($which,$cnum,$cdom)=@_;
10483: if (!$cnum || !$cdom) {
10484: (undef,my $courseid)=&whichuser();
10485: $cdom=$env{'course.'.$courseid.'.domain'};
10486: $cnum=$env{'course.'.$courseid.'.num'};
10487: }
10488: my $key=join("\0",'slots',$cdom,$cnum,$which);
10489: my %slotinfo;
10490: if (exists($remembered{$key})) {
10491: $slotinfo{$which} = $remembered{$key};
10492: } else {
10493: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10494: &Apache::lonhomework::showhash(%slotinfo);
10495: my ($tmp)=keys(%slotinfo);
10496: if ($tmp=~/^error:/) { return (); }
10497: $remembered{$key} = $slotinfo{$which};
10498: }
10499: if (ref($slotinfo{$which}) eq 'HASH') {
10500: return %{$slotinfo{$which}};
10501: }
10502: return $slotinfo{$which};
10503: }
10504:
10505: sub get_reservable_slots {
10506: my ($cnum,$cdom,$uname,$udom) = @_;
10507: my $now = time;
10508: my $reservable_info;
10509: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10510: if (exists($remembered{$key})) {
10511: $reservable_info = $remembered{$key};
10512: } else {
10513: my %resv;
10514: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10515: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10516: $reservable_info = \%resv;
10517: $remembered{$key} = $reservable_info;
10518: }
10519: return $reservable_info;
10520: }
10521:
10522: sub get_course_slots {
10523: my ($cnum,$cdom) = @_;
10524: my $hashid=$cnum.':'.$cdom;
10525: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10526: if (defined($cached)) {
10527: if (ref($result) eq 'HASH') {
10528: return %{$result};
10529: }
10530: } else {
10531: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10532: my ($tmp) = keys(%slots);
10533: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10534: &do_cache_new('allslots',$hashid,\%slots,600);
10535: return %slots;
10536: }
10537: }
10538: return;
10539: }
10540:
10541: sub devalidate_slots_cache {
10542: my ($cnum,$cdom)=@_;
10543: my $hashid=$cnum.':'.$cdom;
10544: &devalidate_cache_new('allslots',$hashid);
10545: }
10546:
10547: sub get_coursechange {
10548: my ($cdom,$cnum) = @_;
10549: if ($cdom eq '' || $cnum eq '') {
10550: return unless ($env{'request.course.id'});
10551: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10552: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10553: }
10554: my $hashid=$cdom.'_'.$cnum;
10555: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10556: if ((defined($cached)) && ($change ne '')) {
10557: return $change;
10558: } else {
10559: my %crshash;
10560: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10561: if ($crshash{'internal.contentchange'} eq '') {
10562: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10563: if ($change eq '') {
10564: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10565: $change = $crshash{'internal.created'};
10566: }
10567: } else {
10568: $change = $crshash{'internal.contentchange'};
10569: }
10570: my $cachetime = 600;
10571: &do_cache_new('crschange',$hashid,$change,$cachetime);
10572: }
10573: return $change;
10574: }
10575:
10576: sub devalidate_coursechange_cache {
10577: my ($cnum,$cdom)=@_;
10578: my $hashid=$cnum.':'.$cdom;
10579: &devalidate_cache_new('crschange',$hashid);
10580: }
10581:
10582: # ------------------------------------------------- Update symbolic store links
10583:
10584: sub symblist {
10585: my ($mapname,%newhash)=@_;
10586: $mapname=&deversion(&declutter($mapname));
10587: my %hash;
10588: if (($env{'request.course.fn'}) && (%newhash)) {
10589: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10590: &GDBM_WRCREAT(),0640)) {
10591: foreach my $url (keys(%newhash)) {
10592: next if ($url eq 'last_known'
10593: && $env{'form.no_update_last_known'});
10594: $hash{declutter($url)}=&encode_symb($mapname,
10595: $newhash{$url}->[1],
10596: $newhash{$url}->[0]);
10597: }
10598: if (untie(%hash)) {
10599: return 'ok';
10600: }
10601: }
10602: }
10603: return 'error';
10604: }
10605:
10606: # --------------------------------------------------------------- Verify a symb
10607:
10608: sub symbverify {
10609: my ($symb,$thisurl,$encstate)=@_;
10610: my $thisfn=$thisurl;
10611: $thisfn=&declutter($thisfn);
10612: # direct jump to resource in page or to a sequence - will construct own symbs
10613: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10614: # check URL part
10615: my ($map,$resid,$url)=&decode_symb($symb);
10616:
10617: unless ($url eq $thisfn) { return 0; }
10618:
10619: $symb=&symbclean($symb);
10620: $thisurl=&deversion($thisurl);
10621: $thisfn=&deversion($thisfn);
10622:
10623: my %bighash;
10624: my $okay=0;
10625:
10626: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10627: &GDBM_READER(),0640)) {
10628: my $noclutter;
10629: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10630: $thisurl =~ s/\?.+$//;
10631: if ($map =~ m{^uploaded/.+\.page$}) {
10632: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10633: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10634: $noclutter = 1;
10635: }
10636: }
10637: my $ids;
10638: if ($noclutter) {
10639: $ids=$bighash{'ids_'.$thisurl};
10640: } else {
10641: $ids=$bighash{'ids_'.&clutter($thisurl)};
10642: }
10643: unless ($ids) {
10644: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10645: $ids=$bighash{$idkey};
10646: }
10647: if ($ids) {
10648: # ------------------------------------------------------------------- Has ID(s)
10649: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10650: $symb =~ s/\?.+$//;
10651: }
10652: foreach my $id (split(/\,/,$ids)) {
10653: my ($mapid,$resid)=split(/\./,$id);
10654: if (
10655: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10656: eq $symb) {
10657: if (ref($encstate)) {
10658: $$encstate = $bighash{'encrypted_'.$id};
10659: }
10660: if (($env{'request.role.adv'}) ||
10661: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10662: ($thisurl eq '/adm/navmaps')) {
10663: $okay=1;
10664: last;
10665: }
10666: }
10667: }
10668: }
10669: untie(%bighash);
10670: }
10671: return $okay;
10672: }
10673:
10674: # --------------------------------------------------------------- Clean-up symb
10675:
10676: sub symbclean {
10677: my $symb=shift;
10678: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10679: # remove version from map
10680: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10681:
10682: # remove version from URL
10683: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10684:
10685: # remove wrapper
10686:
10687: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10688: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10689: return $symb;
10690: }
10691:
10692: # ---------------------------------------------- Split symb to find map and url
10693:
10694: sub encode_symb {
10695: my ($map,$resid,$url)=@_;
10696: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10697: }
10698:
10699: sub decode_symb {
10700: my $symb=shift;
10701: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10702: my ($map,$resid,$url)=split(/___/,$symb);
10703: return (&fixversion($map),$resid,&fixversion($url));
10704: }
10705:
10706: sub fixversion {
10707: my $fn=shift;
10708: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10709: my %bighash;
10710: my $uri=&clutter($fn);
10711: my $key=$env{'request.course.id'}.'_'.$uri;
10712: # is this cached?
10713: my ($result,$cached)=&is_cached_new('courseresversion',$key);
10714: if (defined($cached)) { return $result; }
10715: # unfortunately not cached, or expired
10716: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10717: &GDBM_READER(),0640)) {
10718: if ($bighash{'version_'.$uri}) {
10719: my $version=$bighash{'version_'.$uri};
10720: unless (($version eq 'mostrecent') ||
10721: ($version==&getversion($uri))) {
10722: $uri=~s/\.(\w+)$/\.$version\.$1/;
10723: }
10724: }
10725: untie %bighash;
10726: }
10727: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10728: }
10729:
10730: sub deversion {
10731: my $url=shift;
10732: $url=~s/\.\d+\.(\w+)$/\.$1/;
10733: return $url;
10734: }
10735:
10736: # ------------------------------------------------------ Return symb list entry
10737:
10738: sub symbread {
10739: my ($thisfn,$donotrecurse)=@_;
10740: my $cache_str;
10741: if ($thisfn ne '') {
10742: $cache_str='request.symbread.cached.'.$thisfn;
10743: if ($env{$cache_str} ne '') {
10744: return $env{$cache_str};
10745: }
10746: } else {
10747: # no filename provided? try from environment
10748: if ($env{'request.symb'}) {
10749: return $env{$cache_str}=&symbclean($env{'request.symb'});
10750: }
10751: $thisfn=$env{'request.filename'};
10752: }
10753: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10754: # is that filename actually a symb? Verify, clean, and return
10755: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10756: if (&symbverify($thisfn,$1)) {
10757: return $env{$cache_str}=&symbclean($thisfn);
10758: }
10759: }
10760: $thisfn=declutter($thisfn);
10761: my %hash;
10762: my %bighash;
10763: my $syval='';
10764: if (($env{'request.course.fn'}) && ($thisfn)) {
10765: my $targetfn = $thisfn;
10766: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10767: $targetfn = 'adm/wrapper/'.$thisfn;
10768: }
10769: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10770: $targetfn=$1;
10771: }
10772: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10773: &GDBM_READER(),0640)) {
10774: $syval=$hash{$targetfn};
10775: untie(%hash);
10776: }
10777: # ---------------------------------------------------------- There was an entry
10778: if ($syval) {
10779: #unless ($syval=~/\_\d+$/) {
10780: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10781: #&appenv({'request.ambiguous' => $thisfn});
10782: #return $env{$cache_str}='';
10783: #}
10784: #$syval.=$1;
10785: #}
10786: } else {
10787: # ------------------------------------------------------- Was not in symb table
10788: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10789: &GDBM_READER(),0640)) {
10790: # ---------------------------------------------- Get ID(s) for current resource
10791: my $ids=$bighash{'ids_'.&clutter($thisfn)};
10792: unless ($ids) {
10793: $ids=$bighash{'ids_/'.$thisfn};
10794: }
10795: unless ($ids) {
10796: # alias?
10797: $ids=$bighash{'mapalias_'.$thisfn};
10798: }
10799: if ($ids) {
10800: # ------------------------------------------------------------------- Has ID(s)
10801: my @possibilities=split(/\,/,$ids);
10802: if ($#possibilities==0) {
10803: # ----------------------------------------------- There is only one possibility
10804: my ($mapid,$resid)=split(/\./,$ids);
10805: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10806: $resid,$thisfn);
10807: } elsif (!$donotrecurse) {
10808: # ------------------------------------------ There is more than one possibility
10809: my $realpossible=0;
10810: foreach my $id (@possibilities) {
10811: my $file=$bighash{'src_'.$id};
10812: if (&allowed('bre',$file)) {
10813: my ($mapid,$resid)=split(/\./,$id);
10814: if ($bighash{'map_type_'.$mapid} ne 'page') {
10815: $realpossible++;
10816: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10817: $resid,$thisfn);
10818: }
10819: }
10820: }
10821: if ($realpossible!=1) { $syval=''; }
10822: } else {
10823: $syval='';
10824: }
10825: }
10826: untie(%bighash)
10827: }
10828: }
10829: if ($syval) {
10830: return $env{$cache_str}=$syval;
10831: }
10832: }
10833: &appenv({'request.ambiguous' => $thisfn});
10834: return $env{$cache_str}='';
10835: }
10836:
10837: # ---------------------------------------------------------- Return random seed
10838:
10839: sub numval {
10840: my $txt=shift;
10841: $txt=~tr/A-J/0-9/;
10842: $txt=~tr/a-j/0-9/;
10843: $txt=~tr/K-T/0-9/;
10844: $txt=~tr/k-t/0-9/;
10845: $txt=~tr/U-Z/0-5/;
10846: $txt=~tr/u-z/0-5/;
10847: $txt=~s/\D//g;
10848: if ($_64bit) { if ($txt > 2**32) { return -1; } }
10849: return int($txt);
10850: }
10851:
10852: sub numval2 {
10853: my $txt=shift;
10854: $txt=~tr/A-J/0-9/;
10855: $txt=~tr/a-j/0-9/;
10856: $txt=~tr/K-T/0-9/;
10857: $txt=~tr/k-t/0-9/;
10858: $txt=~tr/U-Z/0-5/;
10859: $txt=~tr/u-z/0-5/;
10860: $txt=~s/\D//g;
10861: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10862: my $total;
10863: foreach my $val (@txts) { $total+=$val; }
10864: if ($_64bit) { if ($total > 2**32) { return -1; } }
10865: return int($total);
10866: }
10867:
10868: sub numval3 {
10869: use integer;
10870: my $txt=shift;
10871: $txt=~tr/A-J/0-9/;
10872: $txt=~tr/a-j/0-9/;
10873: $txt=~tr/K-T/0-9/;
10874: $txt=~tr/k-t/0-9/;
10875: $txt=~tr/U-Z/0-5/;
10876: $txt=~tr/u-z/0-5/;
10877: $txt=~s/\D//g;
10878: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10879: my $total;
10880: foreach my $val (@txts) { $total+=$val; }
10881: if ($_64bit) { $total=(($total<<32)>>32); }
10882: return $total;
10883: }
10884:
10885: sub digest {
10886: my ($data)=@_;
10887: my $digest=&Digest::MD5::md5($data);
10888: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10889: my ($e,$f);
10890: {
10891: use integer;
10892: $e=($a+$b);
10893: $f=($c+$d);
10894: if ($_64bit) {
10895: $e=(($e<<32)>>32);
10896: $f=(($f<<32)>>32);
10897: }
10898: }
10899: if (wantarray) {
10900: return ($e,$f);
10901: } else {
10902: my $g;
10903: {
10904: use integer;
10905: $g=($e+$f);
10906: if ($_64bit) {
10907: $g=(($g<<32)>>32);
10908: }
10909: }
10910: return $g;
10911: }
10912: }
10913:
10914: sub latest_rnd_algorithm_id {
10915: return '64bit5';
10916: }
10917:
10918: sub get_rand_alg {
10919: my ($courseid)=@_;
10920: if (!$courseid) { $courseid=(&whichuser())[1]; }
10921: if ($courseid) {
10922: return $env{"course.$courseid.rndseed"};
10923: }
10924: return &latest_rnd_algorithm_id();
10925: }
10926:
10927: sub validCODE {
10928: my ($CODE)=@_;
10929: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10930: return 0;
10931: }
10932:
10933: sub getCODE {
10934: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10935: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10936: defined($Apache::lonhomework::parsing_a_task) ) &&
10937: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10938: return $Apache::lonhomework::history{'resource.CODE'};
10939: }
10940: return undef;
10941: }
10942: #
10943: # Determines the random seed for a specific context:
10944: #
10945: # parameters:
10946: # symb - in course context the symb for the seed.
10947: # course_id - The course id of the form domain_coursenum.
10948: # domain - Domain for the user.
10949: # course - Course for the user.
10950: # cenv - environment of the course.
10951: #
10952: # NOTE:
10953: # All parameters are picked out of the environment if missing
10954: # or not defined.
10955: # If a symb cannot be determined the current time is used instead.
10956: #
10957: # For a given well defined symb, courside, domain, username,
10958: # and course environment, the seed is reproducible.
10959: #
10960: sub rndseed {
10961: my ($symb,$courseid,$domain,$username, $cenv)=@_;
10962: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10963: if (!defined($symb)) {
10964: unless ($symb=$wsymb) { return time; }
10965: }
10966: if (!defined $courseid) {
10967: $courseid=$wcourseid;
10968: }
10969: if (!defined $domain) { $domain=$wdomain; }
10970: if (!defined $username) { $username=$wusername }
10971:
10972: my $which;
10973: if (defined($cenv->{'rndseed'})) {
10974: $which = $cenv->{'rndseed'};
10975: } else {
10976: $which =&get_rand_alg($courseid);
10977: }
10978: if (defined(&getCODE())) {
10979:
10980: if ($which eq '64bit5') {
10981: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10982: } elsif ($which eq '64bit4') {
10983: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10984: } else {
10985: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10986: }
10987: } elsif ($which eq '64bit5') {
10988: return &rndseed_64bit5($symb,$courseid,$domain,$username);
10989: } elsif ($which eq '64bit4') {
10990: return &rndseed_64bit4($symb,$courseid,$domain,$username);
10991: } elsif ($which eq '64bit3') {
10992: return &rndseed_64bit3($symb,$courseid,$domain,$username);
10993: } elsif ($which eq '64bit2') {
10994: return &rndseed_64bit2($symb,$courseid,$domain,$username);
10995: } elsif ($which eq '64bit') {
10996: return &rndseed_64bit($symb,$courseid,$domain,$username);
10997: }
10998: return &rndseed_32bit($symb,$courseid,$domain,$username);
10999: }
11000:
11001: sub rndseed_32bit {
11002: my ($symb,$courseid,$domain,$username)=@_;
11003: {
11004: use integer;
11005: my $symbchck=unpack("%32C*",$symb) << 27;
11006: my $symbseed=numval($symb) << 22;
11007: my $namechck=unpack("%32C*",$username) << 17;
11008: my $nameseed=numval($username) << 12;
11009: my $domainseed=unpack("%32C*",$domain) << 7;
11010: my $courseseed=unpack("%32C*",$courseid);
11011: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11012: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11013: #&logthis("rndseed :$num:$symb");
11014: if ($_64bit) { $num=(($num<<32)>>32); }
11015: return $num;
11016: }
11017: }
11018:
11019: sub rndseed_64bit {
11020: my ($symb,$courseid,$domain,$username)=@_;
11021: {
11022: use integer;
11023: my $symbchck=unpack("%32S*",$symb) << 21;
11024: my $symbseed=numval($symb) << 10;
11025: my $namechck=unpack("%32S*",$username);
11026:
11027: my $nameseed=numval($username) << 21;
11028: my $domainseed=unpack("%32S*",$domain) << 10;
11029: my $courseseed=unpack("%32S*",$courseid);
11030:
11031: my $num1=$symbchck+$symbseed+$namechck;
11032: my $num2=$nameseed+$domainseed+$courseseed;
11033: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11034: #&logthis("rndseed :$num:$symb");
11035: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11036: return "$num1,$num2";
11037: }
11038: }
11039:
11040: sub rndseed_64bit2 {
11041: my ($symb,$courseid,$domain,$username)=@_;
11042: {
11043: use integer;
11044: # strings need to be an even # of cahracters long, it it is odd the
11045: # last characters gets thrown away
11046: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11047: my $symbseed=numval($symb) << 10;
11048: my $namechck=unpack("%32S*",$username.' ');
11049:
11050: my $nameseed=numval($username) << 21;
11051: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11052: my $courseseed=unpack("%32S*",$courseid.' ');
11053:
11054: my $num1=$symbchck+$symbseed+$namechck;
11055: my $num2=$nameseed+$domainseed+$courseseed;
11056: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11057: #&logthis("rndseed :$num:$symb");
11058: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11059: return "$num1,$num2";
11060: }
11061: }
11062:
11063: sub rndseed_64bit3 {
11064: my ($symb,$courseid,$domain,$username)=@_;
11065: {
11066: use integer;
11067: # strings need to be an even # of cahracters long, it it is odd the
11068: # last characters gets thrown away
11069: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11070: my $symbseed=numval2($symb) << 10;
11071: my $namechck=unpack("%32S*",$username.' ');
11072:
11073: my $nameseed=numval2($username) << 21;
11074: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11075: my $courseseed=unpack("%32S*",$courseid.' ');
11076:
11077: my $num1=$symbchck+$symbseed+$namechck;
11078: my $num2=$nameseed+$domainseed+$courseseed;
11079: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11080: #&logthis("rndseed :$num1:$num2:$_64bit");
11081: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11082:
11083: return "$num1:$num2";
11084: }
11085: }
11086:
11087: sub rndseed_64bit4 {
11088: my ($symb,$courseid,$domain,$username)=@_;
11089: {
11090: use integer;
11091: # strings need to be an even # of cahracters long, it it is odd the
11092: # last characters gets thrown away
11093: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11094: my $symbseed=numval3($symb) << 10;
11095: my $namechck=unpack("%32S*",$username.' ');
11096:
11097: my $nameseed=numval3($username) << 21;
11098: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11099: my $courseseed=unpack("%32S*",$courseid.' ');
11100:
11101: my $num1=$symbchck+$symbseed+$namechck;
11102: my $num2=$nameseed+$domainseed+$courseseed;
11103: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11104: #&logthis("rndseed :$num1:$num2:$_64bit");
11105: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11106:
11107: return "$num1:$num2";
11108: }
11109: }
11110:
11111: sub rndseed_64bit5 {
11112: my ($symb,$courseid,$domain,$username)=@_;
11113: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11114: return "$num1:$num2";
11115: }
11116:
11117: sub rndseed_CODE_64bit {
11118: my ($symb,$courseid,$domain,$username)=@_;
11119: {
11120: use integer;
11121: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11122: my $symbseed=numval2($symb);
11123: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11124: my $CODEseed=numval(&getCODE());
11125: my $courseseed=unpack("%32S*",$courseid.' ');
11126: my $num1=$symbseed+$CODEchck;
11127: my $num2=$CODEseed+$courseseed+$symbchck;
11128: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11129: #&logthis("rndseed :$num1:$num2:$symb");
11130: if ($_64bit) { $num1=(($num1<<32)>>32); }
11131: if ($_64bit) { $num2=(($num2<<32)>>32); }
11132: return "$num1:$num2";
11133: }
11134: }
11135:
11136: sub rndseed_CODE_64bit4 {
11137: my ($symb,$courseid,$domain,$username)=@_;
11138: {
11139: use integer;
11140: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11141: my $symbseed=numval3($symb);
11142: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11143: my $CODEseed=numval3(&getCODE());
11144: my $courseseed=unpack("%32S*",$courseid.' ');
11145: my $num1=$symbseed+$CODEchck;
11146: my $num2=$CODEseed+$courseseed+$symbchck;
11147: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11148: #&logthis("rndseed :$num1:$num2:$symb");
11149: if ($_64bit) { $num1=(($num1<<32)>>32); }
11150: if ($_64bit) { $num2=(($num2<<32)>>32); }
11151: return "$num1:$num2";
11152: }
11153: }
11154:
11155: sub rndseed_CODE_64bit5 {
11156: my ($symb,$courseid,$domain,$username)=@_;
11157: my $code = &getCODE();
11158: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11159: return "$num1:$num2";
11160: }
11161:
11162: sub setup_random_from_rndseed {
11163: my ($rndseed)=@_;
11164: if ($rndseed =~/([,:])/) {
11165: my ($num1,$num2)=split(/[,:]/,$rndseed);
11166: &Math::Random::random_set_seed(abs($num1),abs($num2));
11167: } else {
11168: &Math::Random::random_set_seed_from_phrase($rndseed);
11169: }
11170: }
11171:
11172: sub latest_receipt_algorithm_id {
11173: return 'receipt3';
11174: }
11175:
11176: sub recunique {
11177: my $fucourseid=shift;
11178: my $unique;
11179: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11180: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11181: $unique=$env{"course.$fucourseid.internal.encseed"};
11182: } else {
11183: $unique=$perlvar{'lonReceipt'};
11184: }
11185: return unpack("%32C*",$unique);
11186: }
11187:
11188: sub recprefix {
11189: my $fucourseid=shift;
11190: my $prefix;
11191: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11192: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11193: $prefix=$env{"course.$fucourseid.internal.encpref"};
11194: } else {
11195: $prefix=$perlvar{'lonHostID'};
11196: }
11197: return unpack("%32C*",$prefix);
11198: }
11199:
11200: sub ireceipt {
11201: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11202:
11203: my $return =&recprefix($fucourseid).'-';
11204:
11205: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11206: $env{'request.state'} eq 'construct') {
11207: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11208: return $return;
11209: }
11210:
11211: my $cuname=unpack("%32C*",$funame);
11212: my $cudom=unpack("%32C*",$fudom);
11213: my $cucourseid=unpack("%32C*",$fucourseid);
11214: my $cusymb=unpack("%32C*",$fusymb);
11215: my $cunique=&recunique($fucourseid);
11216: my $cpart=unpack("%32S*",$part);
11217: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11218:
11219: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
11220:
11221: $return.= ($cunique%$cuname+
11222: $cunique%$cudom+
11223: $cusymb%$cuname+
11224: $cusymb%$cudom+
11225: $cucourseid%$cuname+
11226: $cucourseid%$cudom+
11227: $cpart%$cuname+
11228: $cpart%$cudom);
11229: } else {
11230: $return.= ($cunique%$cuname+
11231: $cunique%$cudom+
11232: $cusymb%$cuname+
11233: $cusymb%$cudom+
11234: $cucourseid%$cuname+
11235: $cucourseid%$cudom);
11236: }
11237: return $return;
11238: }
11239:
11240: sub receipt {
11241: my ($part)=@_;
11242: my ($symb,$courseid,$domain,$name) = &whichuser();
11243: return &ireceipt($name,$domain,$courseid,$symb,$part);
11244: }
11245:
11246: sub whichuser {
11247: my ($passedsymb)=@_;
11248: my ($symb,$courseid,$domain,$name,$publicuser);
11249: if (defined($env{'form.grade_symb'})) {
11250: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11251: my $allowed=&allowed('vgr',$tmp_courseid);
11252: if (!$allowed &&
11253: exists($env{'request.course.sec'}) &&
11254: $env{'request.course.sec'} !~ /^\s*$/) {
11255: $allowed=&allowed('vgr',$tmp_courseid.
11256: '/'.$env{'request.course.sec'});
11257: }
11258: if ($allowed) {
11259: ($symb)=&get_env_multiple('form.grade_symb');
11260: $courseid=$tmp_courseid;
11261: ($domain)=&get_env_multiple('form.grade_domain');
11262: ($name)=&get_env_multiple('form.grade_username');
11263: return ($symb,$courseid,$domain,$name,$publicuser);
11264: }
11265: }
11266: if (!$passedsymb) {
11267: $symb=&symbread();
11268: } else {
11269: $symb=$passedsymb;
11270: }
11271: $courseid=$env{'request.course.id'};
11272: $domain=$env{'user.domain'};
11273: $name=$env{'user.name'};
11274: if ($name eq 'public' && $domain eq 'public') {
11275: if (!defined($env{'form.username'})) {
11276: $env{'form.username'}.=time.rand(10000000);
11277: }
11278: $name.=$env{'form.username'};
11279: }
11280: return ($symb,$courseid,$domain,$name,$publicuser);
11281:
11282: }
11283:
11284: # ------------------------------------------------------------ Serves up a file
11285: # returns either the contents of the file or
11286: # -1 if the file doesn't exist
11287: #
11288: # if the target is a file that was uploaded via DOCS,
11289: # a check will be made to see if a current copy exists on the local server,
11290: # if it does this will be served, otherwise a copy will be retrieved from
11291: # the home server for the course and stored in /home/httpd/html/userfiles on
11292: # the local server.
11293:
11294: sub getfile {
11295: my ($file) = @_;
11296: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11297: &repcopy($file);
11298: return &readfile($file);
11299: }
11300:
11301: sub repcopy_userfile {
11302: my ($file)=@_;
11303: my $londocroot = $perlvar{'lonDocRoot'};
11304: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11305: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11306: my ($cdom,$cnum,$filename) =
11307: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11308: my $uri="/uploaded/$cdom/$cnum/$filename";
11309: if (-e "$file") {
11310: # we already have a local copy, check it out
11311: my @fileinfo = stat($file);
11312: my $rtncode;
11313: my $info;
11314: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11315: if ($lwpresp ne 'ok') {
11316: # there is no such file anymore, even though we had a local copy
11317: if ($rtncode eq '404') {
11318: unlink($file);
11319: }
11320: return -1;
11321: }
11322: if ($info < $fileinfo[9]) {
11323: # nice, the file we have is up-to-date, just say okay
11324: return 'ok';
11325: } else {
11326: # the file is outdated, get rid of it
11327: unlink($file);
11328: }
11329: }
11330: # one way or the other, at this point, we don't have the file
11331: # construct the correct path for the file
11332: my @parts = ($cdom,$cnum);
11333: if ($filename =~ m|^(.+)/[^/]+$|) {
11334: push @parts, split(/\//,$1);
11335: }
11336: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11337: foreach my $part (@parts) {
11338: $path .= '/'.$part;
11339: if (!-e $path) {
11340: mkdir($path,0770);
11341: }
11342: }
11343: # now the path exists for sure
11344: # get a user agent
11345: my $ua=new LWP::UserAgent;
11346: my $transferfile=$file.'.in.transfer';
11347: # FIXME: this should flock
11348: if (-e $transferfile) { return 'ok'; }
11349: my $request;
11350: $uri=~s/^\///;
11351: my $homeserver = &homeserver($cnum,$cdom);
11352: my $protocol = $protocol{$homeserver};
11353: $protocol = 'http' if ($protocol ne 'https');
11354: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11355: my $response=$ua->request($request,$transferfile);
11356: # did it work?
11357: if ($response->is_error()) {
11358: unlink($transferfile);
11359: &logthis("Userfile repcopy failed for $uri");
11360: return -1;
11361: }
11362: # worked, rename the transfer file
11363: rename($transferfile,$file);
11364: return 'ok';
11365: }
11366:
11367: sub tokenwrapper {
11368: my $uri=shift;
11369: $uri=~s|^https?\://([^/]+)||;
11370: $uri=~s|^/||;
11371: $env{'user.environment'}=~/\/([^\/]+)\.id/;
11372: my $token=$1;
11373: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11374: if ($udom && $uname && $file) {
11375: $file=~s|(\?\.*)*$||;
11376: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11377: my $homeserver = &homeserver($uname,$udom);
11378: my $protocol = $protocol{$homeserver};
11379: $protocol = 'http' if ($protocol ne 'https');
11380: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11381: (($uri=~/\?/)?'&':'?').'token='.$token.
11382: '&tokenissued='.$perlvar{'lonHostID'};
11383: } else {
11384: return '/adm/notfound.html';
11385: }
11386: }
11387:
11388: # call with reqtype HEAD: get last modification time
11389: # call with reqtype GET: get the file contents
11390: # Do not call this with reqtype GET for large files! It loads everything into memory
11391: #
11392: sub getuploaded {
11393: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11394: $uri=~s/^\///;
11395: my $homeserver = &homeserver($cnum,$cdom);
11396: my $protocol = $protocol{$homeserver};
11397: $protocol = 'http' if ($protocol ne 'https');
11398: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11399: my $ua=new LWP::UserAgent;
11400: my $request=new HTTP::Request($reqtype,$uri);
11401: my $response=$ua->request($request);
11402: $$rtncode = $response->code;
11403: if (! $response->is_success()) {
11404: return 'failed';
11405: }
11406: if ($reqtype eq 'HEAD') {
11407: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11408: } elsif ($reqtype eq 'GET') {
11409: $$info = $response->content;
11410: }
11411: return 'ok';
11412: }
11413:
11414: sub readfile {
11415: my $file = shift;
11416: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11417: my $fh;
11418: open($fh,"<$file");
11419: my $a='';
11420: while (my $line = <$fh>) { $a .= $line; }
11421: return $a;
11422: }
11423:
11424: sub filelocation {
11425: my ($dir,$file) = @_;
11426: my $location;
11427: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11428:
11429: if ($file =~ m-^/adm/-) {
11430: $file=~s-^/adm/wrapper/-/-;
11431: $file=~s-^/adm/coursedocs/showdoc/-/-;
11432: }
11433:
11434: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11435: $location = $file;
11436: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11437: my ($udom,$uname,$filename)=
11438: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11439: my $home=&homeserver($uname,$udom);
11440: my $is_me=0;
11441: my @ids=¤t_machine_ids();
11442: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11443: if ($is_me) {
11444: $location=propath($udom,$uname).'/userfiles/'.$filename;
11445: } else {
11446: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11447: $udom.'/'.$uname.'/'.$filename;
11448: }
11449: } elsif ($file =~ m-^/adm/-) {
11450: $location = $perlvar{'lonDocRoot'}.'/'.$file;
11451: } else {
11452: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11453: $file=~s:^/(res|priv)/:/:;
11454: my $space=$1;
11455: if ( !( $file =~ m:^/:) ) {
11456: $location = $dir. '/'.$file;
11457: } else {
11458: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11459: }
11460: }
11461: $location=~s://+:/:g; # remove duplicate /
11462: while ($location=~m{/\.\./}) {
11463: if ($location =~ m{/[^/]+/\.\./}) {
11464: $location=~ s{/[^/]+/\.\./}{/}g;
11465: } else {
11466: $location=~ s{/\.\./}{/}g;
11467: }
11468: } #remove dir/..
11469: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11470: return $location;
11471: }
11472:
11473: sub hreflocation {
11474: my ($dir,$file)=@_;
11475: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11476: $file=filelocation($dir,$file);
11477: } elsif ($file=~m-^/adm/-) {
11478: $file=~s-^/adm/wrapper/-/-;
11479: $file=~s-^/adm/coursedocs/showdoc/-/-;
11480: }
11481: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11482: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11483: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11484: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11485: {/uploaded/$1/$2/}x;
11486: }
11487: if ($file=~ m{^/userfiles/}) {
11488: $file =~ s{^/userfiles/}{/uploaded/};
11489: }
11490: return $file;
11491: }
11492:
11493:
11494:
11495:
11496:
11497: sub current_machine_domains {
11498: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11499: }
11500:
11501: sub machine_domains {
11502: my ($hostname) = @_;
11503: my @domains;
11504: my %hostname = &all_hostnames();
11505: while( my($id, $name) = each(%hostname)) {
11506: # &logthis("-$id-$name-$hostname-");
11507: if ($hostname eq $name) {
11508: push(@domains,&host_domain($id));
11509: }
11510: }
11511: return @domains;
11512: }
11513:
11514: sub current_machine_ids {
11515: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11516: }
11517:
11518: sub machine_ids {
11519: my ($hostname) = @_;
11520: $hostname ||= &hostname($perlvar{'lonHostID'});
11521: my @ids;
11522: my %name_to_host = &all_names();
11523: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11524: return @{ $name_to_host{$hostname} };
11525: }
11526: return;
11527: }
11528:
11529: sub additional_machine_domains {
11530: my @domains;
11531: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11532: while( my $line = <$fh>) {
11533: $line =~ s/\s//g;
11534: push(@domains,$line);
11535: }
11536: return @domains;
11537: }
11538:
11539: sub default_login_domain {
11540: my $domain = $perlvar{'lonDefDomain'};
11541: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11542: foreach my $posdom (¤t_machine_domains(),
11543: &additional_machine_domains()) {
11544: if (lc($posdom) eq lc($testdomain)) {
11545: $domain=$posdom;
11546: last;
11547: }
11548: }
11549: return $domain;
11550: }
11551:
11552: # ------------------------------------------------------------- Declutters URLs
11553:
11554: sub declutter {
11555: my $thisfn=shift;
11556: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11557: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11558: $thisfn=~s/^\///;
11559: $thisfn=~s|^adm/wrapper/||;
11560: $thisfn=~s|^adm/coursedocs/showdoc/||;
11561: $thisfn=~s/^res\///;
11562: $thisfn=~s/^priv\///;
11563: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11564: $thisfn=~s/\?.+$//;
11565: }
11566: return $thisfn;
11567: }
11568:
11569: # ------------------------------------------------------------- Clutter up URLs
11570:
11571: sub clutter {
11572: my $thisfn='/'.&declutter(shift);
11573: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11574: || $thisfn =~ m{^/adm/(includes|pages)} ) {
11575: $thisfn='/res'.$thisfn;
11576: }
11577: if ($thisfn !~m|^/adm|) {
11578: if ($thisfn =~ m|^/ext/|) {
11579: $thisfn='/adm/wrapper'.$thisfn;
11580: } else {
11581: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11582: my $embstyle=&Apache::loncommon::fileembstyle($ext);
11583: if ($embstyle eq 'ssi'
11584: || ($embstyle eq 'hdn')
11585: || ($embstyle eq 'rat')
11586: || ($embstyle eq 'prv')
11587: || ($embstyle eq 'ign')) {
11588: #do nothing with these
11589: } elsif (($embstyle eq 'img')
11590: || ($embstyle eq 'emb')
11591: || ($embstyle eq 'wrp')) {
11592: $thisfn='/adm/wrapper'.$thisfn;
11593: } elsif ($embstyle eq 'unk'
11594: && $thisfn!~/\.(sequence|page)$/) {
11595: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
11596: } else {
11597: # &logthis("Got a blank emb style");
11598: }
11599: }
11600: }
11601: return $thisfn;
11602: }
11603:
11604: sub clutter_with_no_wrapper {
11605: my $uri = &clutter(shift);
11606: if ($uri =~ m-^/adm/-) {
11607: $uri =~ s-^/adm/wrapper/-/-;
11608: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11609: }
11610: return $uri;
11611: }
11612:
11613: sub freeze_escape {
11614: my ($value)=@_;
11615: if (ref($value)) {
11616: $value=&nfreeze($value);
11617: return '__FROZEN__'.&escape($value);
11618: }
11619: return &escape($value);
11620: }
11621:
11622:
11623: sub thaw_unescape {
11624: my ($value)=@_;
11625: if ($value =~ /^__FROZEN__/) {
11626: substr($value,0,10,undef);
11627: $value=&unescape($value);
11628: return &thaw($value);
11629: }
11630: return &unescape($value);
11631: }
11632:
11633: sub correct_line_ends {
11634: my ($result)=@_;
11635: $$result =~s/\r\n/\n/mg;
11636: $$result =~s/\r/\n/mg;
11637: }
11638: # ================================================================ Main Program
11639:
11640: sub goodbye {
11641: &logthis("Starting Shut down");
11642: #not converted to using infrastruture and probably shouldn't be
11643: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11644: #converted
11645: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11646: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11647: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11648: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11649: #1.1 only
11650: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11651: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11652: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11653: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11654: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11655: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11656: &logthis(sprintf("%-20s is %s",'hits',$hits));
11657: &flushcourselogs();
11658: &logthis("Shutting down");
11659: }
11660:
11661: sub get_dns {
11662: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11663: if (!$ignore_cache) {
11664: my ($content,$cached)=
11665: &Apache::lonnet::is_cached_new('dns',$url);
11666: if ($cached) {
11667: &$func($content,$hashref);
11668: return;
11669: }
11670: }
11671:
11672: my %alldns;
11673: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11674: foreach my $dns (<$config>) {
11675: next if ($dns !~ /^\^(\S*)/x);
11676: my $line = $1;
11677: my ($host,$protocol) = split(/:/,$line);
11678: if ($protocol ne 'https') {
11679: $protocol = 'http';
11680: }
11681: $alldns{$host} = $protocol;
11682: }
11683: while (%alldns) {
11684: my ($dns) = keys(%alldns);
11685: my $ua=new LWP::UserAgent;
11686: $ua->timeout(30);
11687: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11688: my $response=$ua->request($request);
11689: delete($alldns{$dns});
11690: next if ($response->is_error());
11691: my @content = split("\n",$response->content);
11692: unless ($nocache) {
11693: &do_cache_new('dns',$url,\@content,30*24*60*60);
11694: }
11695: &$func(\@content,$hashref);
11696: return;
11697: }
11698: close($config);
11699: my $which = (split('/',$url))[3];
11700: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11701: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11702: my @content = <$config>;
11703: &$func(\@content,$hashref);
11704: return;
11705: }
11706:
11707: # ------------------------------------------------------Get DNS checksums file
11708: sub parse_dns_checksums_tab {
11709: my ($lines,$hashref) = @_;
11710: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11711: my $loncaparev = &get_server_loncaparev($machine_dom);
11712: my ($release,$timestamp) = split(/\-/,$loncaparev);
11713: my (%chksum,%revnum);
11714: if (ref($lines) eq 'ARRAY') {
11715: chomp(@{$lines});
11716: my $version = shift(@{$lines});
11717: if ($version eq $release) {
11718: foreach my $line (@{$lines}) {
11719: my ($file,$version,$shasum) = split(/,/,$line);
11720: $chksum{$file} = $shasum;
11721: $revnum{$file} = $version;
11722: }
11723: if (ref($hashref) eq 'HASH') {
11724: %{$hashref} = (
11725: sums => \%chksum,
11726: versions => \%revnum,
11727: );
11728: }
11729: }
11730: }
11731: return;
11732: }
11733:
11734: sub fetch_dns_checksums {
11735: my %checksums;
11736: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11737: my $loncaparev = &get_server_loncaparev($machine_dom);
11738: my ($release,$timestamp) = split(/\-/,$loncaparev);
11739: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11740: \%checksums);
11741: return \%checksums;
11742: }
11743:
11744: # ------------------------------------------------------------ Read domain file
11745: {
11746: my $loaded;
11747: my %domain;
11748:
11749: sub parse_domain_tab {
11750: my ($lines) = @_;
11751: foreach my $line (@$lines) {
11752: next if ($line =~ /^(\#|\s*$ )/x);
11753:
11754: chomp($line);
11755: my ($name,@elements) = split(/:/,$line,9);
11756: my %this_domain;
11757: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11758: 'lang_def', 'city', 'longi', 'lati',
11759: 'primary') {
11760: $this_domain{$field} = shift(@elements);
11761: }
11762: $domain{$name} = \%this_domain;
11763: }
11764: }
11765:
11766: sub reset_domain_info {
11767: undef($loaded);
11768: undef(%domain);
11769: }
11770:
11771: sub load_domain_tab {
11772: my ($ignore_cache) = @_;
11773: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11774: my $fh;
11775: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11776: my @lines = <$fh>;
11777: &parse_domain_tab(\@lines);
11778: }
11779: close($fh);
11780: $loaded = 1;
11781: }
11782:
11783: sub domain {
11784: &load_domain_tab() if (!$loaded);
11785:
11786: my ($name,$what) = @_;
11787: return if ( !exists($domain{$name}) );
11788:
11789: if (!$what) {
11790: return $domain{$name}{'description'};
11791: }
11792: return $domain{$name}{$what};
11793: }
11794:
11795: sub domain_info {
11796: &load_domain_tab() if (!$loaded);
11797: return %domain;
11798: }
11799:
11800: }
11801:
11802:
11803: # ------------------------------------------------------------- Read hosts file
11804: {
11805: my %hostname;
11806: my %hostdom;
11807: my %libserv;
11808: my $loaded;
11809: my %name_to_host;
11810: my %internetdom;
11811: my %LC_dns_serv;
11812:
11813: sub parse_hosts_tab {
11814: my ($file) = @_;
11815: foreach my $configline (@$file) {
11816: next if ($configline =~ /^(\#|\s*$ )/x);
11817: chomp($configline);
11818: if ($configline =~ /^\^/) {
11819: if ($configline =~ /^\^([\w.\-]+)/) {
11820: $LC_dns_serv{$1} = 1;
11821: }
11822: next;
11823: }
11824: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11825: $name=~s/\s//g;
11826: if ($id && $domain && $role && $name) {
11827: $hostname{$id}=$name;
11828: push(@{$name_to_host{$name}}, $id);
11829: $hostdom{$id}=$domain;
11830: if ($role eq 'library') { $libserv{$id}=$name; }
11831: if (defined($protocol)) {
11832: if ($protocol eq 'https') {
11833: $protocol{$id} = $protocol;
11834: } else {
11835: $protocol{$id} = 'http';
11836: }
11837: } else {
11838: $protocol{$id} = 'http';
11839: }
11840: if (defined($intdom)) {
11841: $internetdom{$id} = $intdom;
11842: }
11843: }
11844: }
11845: }
11846:
11847: sub reset_hosts_info {
11848: &purge_remembered();
11849: &reset_domain_info();
11850: &reset_hosts_ip_info();
11851: undef(%name_to_host);
11852: undef(%hostname);
11853: undef(%hostdom);
11854: undef(%libserv);
11855: undef($loaded);
11856: }
11857:
11858: sub load_hosts_tab {
11859: my ($ignore_cache) = @_;
11860: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11861: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11862: my @config = <$config>;
11863: &parse_hosts_tab(\@config);
11864: close($config);
11865: $loaded=1;
11866: }
11867:
11868: sub hostname {
11869: &load_hosts_tab() if (!$loaded);
11870:
11871: my ($lonid) = @_;
11872: return $hostname{$lonid};
11873: }
11874:
11875: sub all_hostnames {
11876: &load_hosts_tab() if (!$loaded);
11877:
11878: return %hostname;
11879: }
11880:
11881: sub all_names {
11882: &load_hosts_tab() if (!$loaded);
11883:
11884: return %name_to_host;
11885: }
11886:
11887: sub all_host_domain {
11888: &load_hosts_tab() if (!$loaded);
11889: return %hostdom;
11890: }
11891:
11892: sub is_library {
11893: &load_hosts_tab() if (!$loaded);
11894:
11895: return exists($libserv{$_[0]});
11896: }
11897:
11898: sub all_library {
11899: &load_hosts_tab() if (!$loaded);
11900:
11901: return %libserv;
11902: }
11903:
11904: sub unique_library {
11905: #2x reverse removes all hostnames that appear more than once
11906: my %unique = reverse &all_library();
11907: return reverse %unique;
11908: }
11909:
11910: sub get_servers {
11911: &load_hosts_tab() if (!$loaded);
11912:
11913: my ($domain,$type) = @_;
11914: my %possible_hosts = ($type eq 'library') ? %libserv
11915: : %hostname;
11916: my %result;
11917: if (ref($domain) eq 'ARRAY') {
11918: while ( my ($host,$hostname) = each(%possible_hosts)) {
11919: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11920: $result{$host} = $hostname;
11921: }
11922: }
11923: } else {
11924: while ( my ($host,$hostname) = each(%possible_hosts)) {
11925: if ($hostdom{$host} eq $domain) {
11926: $result{$host} = $hostname;
11927: }
11928: }
11929: }
11930: return %result;
11931: }
11932:
11933: sub get_unique_servers {
11934: my %unique = reverse &get_servers(@_);
11935: return reverse %unique;
11936: }
11937:
11938: sub host_domain {
11939: &load_hosts_tab() if (!$loaded);
11940:
11941: my ($lonid) = @_;
11942: return $hostdom{$lonid};
11943: }
11944:
11945: sub all_domains {
11946: &load_hosts_tab() if (!$loaded);
11947:
11948: my %seen;
11949: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11950: return @uniq;
11951: }
11952:
11953: sub internet_dom {
11954: &load_hosts_tab() if (!$loaded);
11955:
11956: my ($lonid) = @_;
11957: return $internetdom{$lonid};
11958: }
11959:
11960: sub is_LC_dns {
11961: &load_hosts_tab() if (!$loaded);
11962:
11963: my ($hostname) = @_;
11964: return exists($LC_dns_serv{$hostname});
11965: }
11966:
11967: }
11968:
11969: {
11970: my %iphost;
11971: my %name_to_ip;
11972: my %lonid_to_ip;
11973:
11974: sub get_hosts_from_ip {
11975: my ($ip) = @_;
11976: my %iphosts = &get_iphost();
11977: if (ref($iphosts{$ip})) {
11978: return @{$iphosts{$ip}};
11979: }
11980: return;
11981: }
11982:
11983: sub reset_hosts_ip_info {
11984: undef(%iphost);
11985: undef(%name_to_ip);
11986: undef(%lonid_to_ip);
11987: }
11988:
11989: sub get_host_ip {
11990: my ($lonid) = @_;
11991: if (exists($lonid_to_ip{$lonid})) {
11992: return $lonid_to_ip{$lonid};
11993: }
11994: my $name=&hostname($lonid);
11995: my $ip = gethostbyname($name);
11996: return if (!$ip || length($ip) ne 4);
11997: $ip=inet_ntoa($ip);
11998: $name_to_ip{$name} = $ip;
11999: $lonid_to_ip{$lonid} = $ip;
12000: return $ip;
12001: }
12002:
12003: sub get_iphost {
12004: my ($ignore_cache) = @_;
12005:
12006: if (!$ignore_cache) {
12007: if (%iphost) {
12008: return %iphost;
12009: }
12010: my ($ip_info,$cached)=
12011: &Apache::lonnet::is_cached_new('iphost','iphost');
12012: if ($cached) {
12013: %iphost = %{$ip_info->[0]};
12014: %name_to_ip = %{$ip_info->[1]};
12015: %lonid_to_ip = %{$ip_info->[2]};
12016: return %iphost;
12017: }
12018: }
12019:
12020: # get yesterday's info for fallback
12021: my %old_name_to_ip;
12022: my ($ip_info,$cached)=
12023: &Apache::lonnet::is_cached_new('iphost','iphost');
12024: if ($cached) {
12025: %old_name_to_ip = %{$ip_info->[1]};
12026: }
12027:
12028: my %name_to_host = &all_names();
12029: foreach my $name (keys(%name_to_host)) {
12030: my $ip;
12031: if (!exists($name_to_ip{$name})) {
12032: $ip = gethostbyname($name);
12033: if (!$ip || length($ip) ne 4) {
12034: if (defined($old_name_to_ip{$name})) {
12035: $ip = $old_name_to_ip{$name};
12036: &logthis("Can't find $name defaulting to old $ip");
12037: } else {
12038: &logthis("Name $name no IP found");
12039: next;
12040: }
12041: } else {
12042: $ip=inet_ntoa($ip);
12043: }
12044: $name_to_ip{$name} = $ip;
12045: } else {
12046: $ip = $name_to_ip{$name};
12047: }
12048: foreach my $id (@{ $name_to_host{$name} }) {
12049: $lonid_to_ip{$id} = $ip;
12050: }
12051: push(@{$iphost{$ip}},@{$name_to_host{$name}});
12052: }
12053: &do_cache_new('iphost','iphost',
12054: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12055: 48*60*60);
12056:
12057: return %iphost;
12058: }
12059:
12060: #
12061: # Given a DNS returns the loncapa host name for that DNS
12062: #
12063: sub host_from_dns {
12064: my ($dns) = @_;
12065: my @hosts;
12066: my $ip;
12067:
12068: if (exists($name_to_ip{$dns})) {
12069: $ip = $name_to_ip{$dns};
12070: }
12071: if (!$ip) {
12072: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12073: if (length($ip) == 4) {
12074: $ip = &IO::Socket::inet_ntoa($ip);
12075: }
12076: }
12077: if ($ip) {
12078: @hosts = get_hosts_from_ip($ip);
12079: return $hosts[0];
12080: }
12081: return undef;
12082: }
12083:
12084: sub get_internet_names {
12085: my ($lonid) = @_;
12086: return if ($lonid eq '');
12087: my ($idnref,$cached)=
12088: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12089: if ($cached) {
12090: return $idnref;
12091: }
12092: my $ip = &get_host_ip($lonid);
12093: my @hosts = &get_hosts_from_ip($ip);
12094: my %iphost = &get_iphost();
12095: my (@idns,%seen);
12096: foreach my $id (@hosts) {
12097: my $dom = &host_domain($id);
12098: my $prim_id = &domain($dom,'primary');
12099: my $prim_ip = &get_host_ip($prim_id);
12100: next if ($seen{$prim_ip});
12101: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12102: foreach my $id (@{$iphost{$prim_ip}}) {
12103: my $intdom = &internet_dom($id);
12104: unless (grep(/^\Q$intdom\E$/,@idns)) {
12105: push(@idns,$intdom);
12106: }
12107: }
12108: }
12109: $seen{$prim_ip} = 1;
12110: }
12111: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12112: }
12113:
12114: }
12115:
12116: sub all_loncaparevs {
12117: 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);
12118: }
12119:
12120: # ---------------------------------------------------------- Read loncaparev table
12121: {
12122: sub load_loncaparevs {
12123: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12124: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12125: while (my $configline=<$config>) {
12126: chomp($configline);
12127: my ($hostid,$loncaparev)=split(/:/,$configline);
12128: $loncaparevs{$hostid}=$loncaparev;
12129: }
12130: close($config);
12131: }
12132: }
12133: }
12134: }
12135:
12136: # ---------------------------------------------------------- Read serverhostID table
12137: {
12138: sub load_serverhomeIDs {
12139: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12140: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12141: while (my $configline=<$config>) {
12142: chomp($configline);
12143: my ($name,$id)=split(/:/,$configline);
12144: $serverhomeIDs{$name}=$id;
12145: }
12146: close($config);
12147: }
12148: }
12149: }
12150: }
12151:
12152:
12153: BEGIN {
12154:
12155: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12156: unless ($readit) {
12157: {
12158: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12159: %perlvar = (%perlvar,%{$configvars});
12160: }
12161:
12162:
12163: # ------------------------------------------------------ Read spare server file
12164: {
12165: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12166:
12167: while (my $configline=<$config>) {
12168: chomp($configline);
12169: if ($configline) {
12170: my ($host,$type) = split(':',$configline,2);
12171: if (!defined($type) || $type eq '') { $type = 'default' };
12172: push(@{ $spareid{$type} }, $host);
12173: }
12174: }
12175: close($config);
12176: }
12177: # ------------------------------------------------------------ Read permissions
12178: {
12179: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12180:
12181: while (my $configline=<$config>) {
12182: chomp($configline);
12183: if ($configline) {
12184: my ($role,$perm)=split(/ /,$configline);
12185: if ($perm ne '') { $pr{$role}=$perm; }
12186: }
12187: }
12188: close($config);
12189: }
12190:
12191: # -------------------------------------------- Read plain texts for permissions
12192: {
12193: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12194:
12195: while (my $configline=<$config>) {
12196: chomp($configline);
12197: if ($configline) {
12198: my ($short,@plain)=split(/:/,$configline);
12199: %{$prp{$short}} = ();
12200: if (@plain > 0) {
12201: $prp{$short}{'std'} = $plain[0];
12202: for (my $i=1; $i<@plain; $i++) {
12203: $prp{$short}{'alt'.$i} = $plain[$i];
12204: }
12205: }
12206: }
12207: }
12208: close($config);
12209: }
12210:
12211: # ---------------------------------------------------------- Read package table
12212: {
12213: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12214:
12215: while (my $configline=<$config>) {
12216: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12217: chomp($configline);
12218: my ($short,$plain)=split(/:/,$configline);
12219: my ($pack,$name)=split(/\&/,$short);
12220: if ($plain ne '') {
12221: $packagetab{$pack.'&'.$name.'&name'}=$name;
12222: $packagetab{$short}=$plain;
12223: }
12224: }
12225: close($config);
12226: }
12227:
12228: # ---------------------------------------------------------- Read loncaparev table
12229:
12230: &load_loncaparevs();
12231:
12232: # ---------------------------------------------------------- Read serverhostID table
12233:
12234: &load_serverhomeIDs();
12235:
12236: # ---------------------------------------------------------- Read releaseslist XML
12237: {
12238: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12239: if (-e $file) {
12240: my $parser = HTML::LCParser->new($file);
12241: while (my $token = $parser->get_token()) {
12242: if ($token->[0] eq 'S') {
12243: my $item = $token->[1];
12244: my $name = $token->[2]{'name'};
12245: my $value = $token->[2]{'value'};
12246: if ($item ne '' && $name ne '' && $value ne '') {
12247: my $release = $parser->get_text();
12248: $release =~ s/(^\s*|\s*$ )//gx;
12249: $needsrelease{$item.':'.$name.':'.$value} = $release;
12250: }
12251: }
12252: }
12253: }
12254: }
12255:
12256: # ---------------------------------------------------------- Read managers table
12257: {
12258: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12259: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12260: while (my $configline=<$config>) {
12261: chomp($configline);
12262: next if ($configline =~ /^\#/);
12263: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12264: $managerstab{$configline} = 1;
12265: }
12266: }
12267: close($config);
12268: }
12269: }
12270: }
12271:
12272: # ------------- set up temporary directory
12273: {
12274: $tmpdir = LONCAPA::tempdir();
12275:
12276: }
12277:
12278: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12279: 'compress_threshold'=> 20_000,
12280: });
12281:
12282: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12283: $dumpcount=0;
12284: $locknum=0;
12285:
12286: &logtouch();
12287: &logthis('<font color="yellow">INFO: Read configuration</font>');
12288: $readit=1;
12289: {
12290: use integer;
12291: my $test=(2**32)+1;
12292: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12293: &logthis(" Detected 64bit platform ($_64bit)");
12294: }
12295:
12296: {
12297: eval {
12298: ($apache) =
12299: (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12300: };
12301: if ($@) {
12302: $apache = 1.3;
12303: }
12304: }
12305:
12306: }
12307: }
12308:
12309: 1;
12310: __END__
12311:
12312: =pod
12313:
12314: =head1 NAME
12315:
12316: Apache::lonnet - Subroutines to ask questions about things in the network.
12317:
12318: =head1 SYNOPSIS
12319:
12320: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12321:
12322: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12323:
12324: Common parameters:
12325:
12326: =over 4
12327:
12328: =item *
12329:
12330: $uname : an internal username (if $cname expecting a course Id specifically)
12331:
12332: =item *
12333:
12334: $udom : a domain (if $cdom expecting a course's domain specifically)
12335:
12336: =item *
12337:
12338: $symb : a resource instance identifier
12339:
12340: =item *
12341:
12342: $namespace : the name of a .db file that contains the data needed or
12343: being set.
12344:
12345: =back
12346:
12347: =head1 OVERVIEW
12348:
12349: lonnet provides subroutines which interact with the
12350: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12351: about classes, users, and resources.
12352:
12353: For many of these objects you can also use this to store data about
12354: them or modify them in various ways.
12355:
12356: =head2 Symbs
12357:
12358: To identify a specific instance of a resource, LON-CAPA uses symbols
12359: or "symbs"X<symb>. These identifiers are built from the URL of the
12360: map, the resource number of the resource in the map, and the URL of
12361: the resource itself. The latter is somewhat redundant, but might help
12362: if maps change.
12363:
12364: An example is
12365:
12366: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12367:
12368: The respective map entry is
12369:
12370: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12371: title="Problem 2">
12372: </resource>
12373:
12374: Symbs are used by the random number generator, as well as to store and
12375: restore data specific to a certain instance of for example a problem.
12376:
12377: =head2 Storing And Retrieving Data
12378:
12379: X<store()>X<cstore()>X<restore()>Three of the most important functions
12380: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12381: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12382: is is the non-critical message twin of cstore. These functions are for
12383: handlers to store a perl hash to a user's permanent data space in an
12384: easy manner, and to retrieve it again on another call. It is expected
12385: that a handler would use this once at the beginning to retrieve data,
12386: and then again once at the end to send only the new data back.
12387:
12388: The data is stored in the user's data directory on the user's
12389: homeserver under the ID of the course.
12390:
12391: The hash that is returned by restore will have all of the previous
12392: value for all of the elements of the hash.
12393:
12394: Example:
12395:
12396: #creating a hash
12397: my %hash;
12398: $hash{'foo'}='bar';
12399:
12400: #storing it
12401: &Apache::lonnet::cstore(\%hash);
12402:
12403: #changing a value
12404: $hash{'foo'}='notbar';
12405:
12406: #adding a new value
12407: $hash{'bar'}='foo';
12408: &Apache::lonnet::cstore(\%hash);
12409:
12410: #retrieving the hash
12411: my %history=&Apache::lonnet::restore();
12412:
12413: #print the hash
12414: foreach my $key (sort(keys(%history))) {
12415: print("\%history{$key} = $history{$key}");
12416: }
12417:
12418: Will print out:
12419:
12420: %history{1:foo} = bar
12421: %history{1:keys} = foo:timestamp
12422: %history{1:timestamp} = 990455579
12423: %history{2:bar} = foo
12424: %history{2:foo} = notbar
12425: %history{2:keys} = foo:bar:timestamp
12426: %history{2:timestamp} = 990455580
12427: %history{bar} = foo
12428: %history{foo} = notbar
12429: %history{timestamp} = 990455580
12430: %history{version} = 2
12431:
12432: Note that the special hash entries C<keys>, C<version> and
12433: C<timestamp> were added to the hash. C<version> will be equal to the
12434: total number of versions of the data that have been stored. The
12435: C<timestamp> attribute will be the UNIX time the hash was
12436: stored. C<keys> is available in every historical section to list which
12437: keys were added or changed at a specific historical revision of a
12438: hash.
12439:
12440: B<Warning>: do not store the hash that restore returns directly. This
12441: will cause a mess since it will restore the historical keys as if the
12442: were new keys. I.E. 1:foo will become 1:1:foo etc.
12443:
12444: Calling convention:
12445:
12446: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12447: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12448:
12449: For more detailed information, see lonnet specific documentation.
12450:
12451: =head1 RETURN MESSAGES
12452:
12453: =over 4
12454:
12455: =item * B<con_lost>: unable to contact remote host
12456:
12457: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12458: when the connection is brought back up
12459:
12460: =item * B<con_failed>: unable to contact remote host and unable to save message
12461: for later delivery
12462:
12463: =item * B<error:>: an error a occurred, a description of the error follows the :
12464:
12465: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12466: that was requested
12467:
12468: =back
12469:
12470: =head1 PUBLIC SUBROUTINES
12471:
12472: =head2 Session Environment Functions
12473:
12474: =over 4
12475:
12476: =item *
12477: X<appenv()>
12478: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12479: the user envirnoment file, and will be restored for each access this
12480: user makes during this session, also modifies the %env for the current
12481: process. Optional rolesarrayref - if defined contains a reference to an array
12482: of roles which are exempt from the restriction on modifying user.role entries
12483: in the user's environment.db and in %env.
12484:
12485: =item *
12486: X<delenv()>
12487: B<delenv($delthis,$regexp)>: removes all items from the session
12488: environment file that begin with $delthis. If the
12489: optional second arg - $regexp - is true, $delthis is treated as a
12490: regular expression, otherwise \Q$delthis\E is used.
12491: The values are also deleted from the current processes %env.
12492:
12493: =item * get_env_multiple($name)
12494:
12495: gets $name from the %env hash, it seemlessly handles the cases where multiple
12496: values may be defined and end up as an array ref.
12497:
12498: returns an array of values
12499:
12500: =back
12501:
12502: =head2 User Information
12503:
12504: =over 4
12505:
12506: =item *
12507: X<queryauthenticate()>
12508: B<queryauthenticate($uname,$udom)>: try to determine user's current
12509: authentication scheme
12510:
12511: =item *
12512: X<authenticate()>
12513: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12514: authenticate user from domain's lib servers (first use the current
12515: one). C<$upass> should be the users password.
12516: $checkdefauth is optional (value is 1 if a check should be made to
12517: authenticate user using default authentication method, and allow
12518: account creation if username does not have account in the domain).
12519: $clientcancheckhost is optional (value is 1 if checking whether the
12520: server can host will occur on the client side in lonauth.pm).
12521:
12522: =item *
12523: X<homeserver()>
12524: B<homeserver($uname,$udom)>: find the server which has
12525: the user's directory and files (there must be only one), this caches
12526: the answer, and also caches if there is a borken connection.
12527:
12528: =item *
12529: X<idget()>
12530: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12531: (IDs are a unique resource in a domain, there must be only 1 ID per
12532: username, and only 1 username per ID in a specific domain) (returns
12533: hash: id=>name,id=>name)
12534:
12535: =item *
12536: X<idrget()>
12537: B<idrget($udom,@unames)>: find the IDs behind a list of
12538: usernames (returns hash: name=>id,name=>id)
12539:
12540: =item *
12541: X<idput()>
12542: B<idput($udom,%ids)>: store away a list of names and associated IDs
12543:
12544: =item *
12545: X<rolesinit()>
12546: B<rolesinit($udom,$username)>: get user privileges.
12547: returns user role, first access and timer interval hashes
12548:
12549: =item *
12550: X<privileged()>
12551: B<privileged($username,$domain)>: returns a true if user has a
12552: privileged and active role (i.e. su or dc), false otherwise.
12553:
12554: =item *
12555: X<getsection()>
12556: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12557: course $cname, return section name/number or '' for "not in course"
12558: and '-1' for "no section"
12559:
12560: =item *
12561: X<userenvironment()>
12562: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12563: passed in @what from the requested user's environment, returns a hash
12564:
12565: =item *
12566: X<userlog_query()>
12567: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12568: activity.log file. %filters defines filters applied when parsing the
12569: log file. These can be start or end timestamps, or the type of action
12570: - log to look for Login or Logout events, check for Checkin or
12571: Checkout, role for role selection. The response is in the form
12572: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12573: escaped strings of the action recorded in the activity.log file.
12574:
12575: =back
12576:
12577: =head2 User Roles
12578:
12579: =over 4
12580:
12581: =item *
12582:
12583: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12584: F: full access
12585: U,I,K: authentication modes (cxx only)
12586: '': forbidden
12587: 1: user needs to choose course
12588: 2: browse allowed
12589: A: passphrase authentication needed
12590:
12591: =item *
12592:
12593: constructaccess($url,$setpriv) : check for access to construction space URL
12594:
12595: See if the owner domain and name in the URL match those in the
12596: expected environment. If so, return three element list
12597: ($ownername,$ownerdomain,$ownerhome).
12598:
12599: Otherwise return the null string.
12600:
12601: If second argument 'setpriv' is true, it assigns the privileges,
12602: and returns the same three element list, unless the owner has
12603: blocked "ad hoc" Domain Coordinator access to the Author Space,
12604: in which case the null string is returned.
12605:
12606: =item *
12607:
12608: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12609: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12610: and course level
12611:
12612: =item *
12613:
12614: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12615: (rolesplain.tab); plain text explanation of a user role term.
12616: $type is Course (default) or Community.
12617: If $forcedefault evaluates to true, text returned will be default
12618: text for $type. Otherwise, if this is a course, the text returned
12619: will be a custom name for the role (if defined in the course's
12620: environment). If no custom name is defined the default is returned.
12621:
12622: =item *
12623:
12624: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12625: All arguments are optional. Returns a hash of a roles, either for
12626: co-author/assistant author roles for a user's Construction Space
12627: (default), or if $context is 'userroles', roles for the user himself,
12628: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12629: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12630: For each key, value is set to colon-separated start and end times for
12631: the role. If no username and domain are specified, will default to
12632: current user/domain. Types, roles, and roledoms are references to arrays
12633: of role statuses (active, future or previous), roles
12634: (e.g., cc,in, st etc.) and domains of the roles which can be used
12635: to restrict the list of roles reported. If no array ref is
12636: provided for types, will default to return only active roles.
12637:
12638: =item *
12639:
12640: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12641: user: $uname:$udom has a role in the course: $cdom_$cnum.
12642:
12643: Additional optional arguments are: $type (if role checking is to be restricted
12644: to certain user status types -- previous (expired roles), active (currently
12645: available roles) or future (roles available in the future), and
12646: $hideprivileged -- if true will not report course roles for users who
12647: have active Domain Coordinator role in course's domain or in additional
12648: domains (specified in 'Domains to check for privileged users' in course
12649: environment -- set via: Course Settings -> Classlists and staff listing).
12650:
12651: =item *
12652:
12653: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12654: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12655: $possdomains and $possroles are optional array refs -- to domains to check and
12656: roles to check. If $possdomains is not specified, a dump will be done of the
12657: users' roles.db to check for a dc or su role in any domain. This can be
12658: time consuming if &privileged is called repeatedly (e.g., when displaying a
12659: classlist), so in such cases, supplying a $possdomains array is preferred, as
12660: this then allows &privileged_by_domain() to be used, which caches the identity
12661: of privileged users, eliminating the need for repeated calls to &dump().
12662:
12663: =item *
12664:
12665: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12666: where the outer hash keys are domains specified in the $possdomains array ref,
12667: next inner hash keys are privileged roles specified in the $roles array ref,
12668: and the innermost hash contains key = value pairs for username:domain = end:start
12669: for active or future "privileged" users with that role in that domain. To avoid
12670: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12671: innerhash are cached using priv_$role and $dom as the identifiers.
12672:
12673: =back
12674:
12675: =head2 User Modification
12676:
12677: =over 4
12678:
12679: =item *
12680:
12681: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12682: user for the level given by URL. Optional start and end dates (leave empty
12683: string or zero for "no date")
12684:
12685: =item *
12686:
12687: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12688: change a users, password, possible return values are: ok,
12689: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12690: refused
12691:
12692: =item *
12693:
12694: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12695:
12696: =item *
12697:
12698: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12699: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12700:
12701: will update user information (firstname,middlename,lastname,generation,
12702: permanentemail), and if forceid is true, student/employee ID also.
12703: A user's institutional affiliation(s) can also be updated.
12704: User information fields will not be overwritten with empty entries
12705: unless the field is included in the $candelete array reference.
12706: This array is included when a single user is modified via "Manage Users",
12707: or when Autoupdate.pl is run by cron in a domain.
12708:
12709: =item *
12710:
12711: modifystudent
12712:
12713: modify a student's enrollment and identification information.
12714: The course id is resolved based on the current user's environment.
12715: This means the invoking user must be a course coordinator or otherwise
12716: associated with a course.
12717:
12718: This call is essentially a wrapper for lonnet::modifyuser and
12719: lonnet::modify_student_enrollment
12720:
12721: Inputs:
12722:
12723: =over 4
12724:
12725: =item B<$udom> Student's loncapa domain
12726:
12727: =item B<$uname> Student's loncapa login name
12728:
12729: =item B<$uid> Student/Employee ID
12730:
12731: =item B<$umode> Student's authentication mode
12732:
12733: =item B<$upass> Student's password
12734:
12735: =item B<$first> Student's first name
12736:
12737: =item B<$middle> Student's middle name
12738:
12739: =item B<$last> Student's last name
12740:
12741: =item B<$gene> Student's generation
12742:
12743: =item B<$usec> Student's section in course
12744:
12745: =item B<$end> Unix time of the roles expiration
12746:
12747: =item B<$start> Unix time of the roles start date
12748:
12749: =item B<$forceid> If defined, allow $uid to be changed
12750:
12751: =item B<$desiredhome> server to use as home server for student
12752:
12753: =item B<$email> Student's permanent e-mail address
12754:
12755: =item B<$type> Type of enrollment (auto or manual)
12756:
12757: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12758:
12759: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12760:
12761: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12762:
12763: =item B<$context> role change context (shown in User Management Logs display in a course)
12764:
12765: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12766:
12767: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
12768:
12769: =back
12770:
12771: =item *
12772:
12773: modify_student_enrollment
12774:
12775: Change a student's enrollment status in a class. The environment variable
12776: 'role.request.course' must be defined for this function to proceed.
12777:
12778: Inputs:
12779:
12780: =over 4
12781:
12782: =item $udom, student's domain
12783:
12784: =item $uname, student's name
12785:
12786: =item $uid, student's user id
12787:
12788: =item $first, student's first name
12789:
12790: =item $middle
12791:
12792: =item $last
12793:
12794: =item $gene
12795:
12796: =item $usec
12797:
12798: =item $end
12799:
12800: =item $start
12801:
12802: =item $type
12803:
12804: =item $locktype
12805:
12806: =item $cid
12807:
12808: =item $selfenroll
12809:
12810: =item $context
12811:
12812: =item $credits, number of credits student will earn from this class
12813:
12814: =back
12815:
12816:
12817: =item *
12818:
12819: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12820: custom role; give a custom role to a user for the level given by URL. Specify
12821: name and domain of role author, and role name
12822:
12823: =item *
12824:
12825: revokerole($udom,$uname,$url,$role) : revoke a role for url
12826:
12827: =item *
12828:
12829: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12830:
12831: =back
12832:
12833: =head2 Course Infomation
12834:
12835: =over 4
12836:
12837: =item *
12838:
12839: coursedescription($courseid,$options) : returns a hash of information about the
12840: specified course id, including all environment settings for the
12841: course, the description of the course will be in the hash under the
12842: key 'description'
12843:
12844: $options is an optional parameter that if supplied is a hash reference that controls
12845: what how this function works. It has the following key/values:
12846:
12847: =over 4
12848:
12849: =item freshen_cache
12850:
12851: If defined, and the environment cache for the course is valid, it is
12852: returned in the returned hash.
12853:
12854: =item one_time
12855:
12856: If defined, the last cache time is set to _now_
12857:
12858: =item user
12859:
12860: If defined, the supplied username is used instead of the current user.
12861:
12862:
12863: =back
12864:
12865: =item *
12866:
12867: resdata($name,$domain,$type,@which) : request for current parameter
12868: setting for a specific $type, where $type is either 'course' or 'user',
12869: @what should be a list of parameters to ask about. This routine caches
12870: answers for 10 minutes.
12871:
12872: =item *
12873:
12874: get_courseresdata($courseid, $domain) : dump the entire course resource
12875: data base, returning a hash that is keyed by the resource name and has
12876: values that are the resource value. I believe that the timestamps and
12877: versions are also returned.
12878:
12879: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12880: supplemental content area. This routine caches the number of files for
12881: 10 minutes.
12882:
12883: =back
12884:
12885: =head2 Course Modification
12886:
12887: =over 4
12888:
12889: =item *
12890:
12891: writecoursepref($courseid,%prefs) : write preferences (environment
12892: database) for a course
12893:
12894: =item *
12895:
12896: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12897:
12898: =item *
12899:
12900: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12901:
12902: =item *
12903:
12904: is_course($courseid), is_course($cdom, $cnum)
12905:
12906: Accepts either a combined $courseid (in the form of domain_courseid) or the
12907: two component version $cdom, $cnum. It checks if the specified course exists.
12908:
12909: Returns:
12910: undef if the course doesn't exist, otherwise
12911: in scalar context the combined courseid.
12912: in list context the two components of the course identifier, domain and
12913: courseid.
12914:
12915: =back
12916:
12917: =head2 Resource Subroutines
12918:
12919: =over 4
12920:
12921: =item *
12922:
12923: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12924:
12925: =item *
12926:
12927: repcopy($filename) : subscribes to the requested file, and attempts to
12928: replicate from the owning library server, Might return
12929: 'unavailable', 'not_found', 'forbidden', 'ok', or
12930: 'bad_request', also attempts to grab the metadata for the
12931: resource. Expects the local filesystem pathname
12932: (/home/httpd/html/res/....)
12933:
12934: =back
12935:
12936: =head2 Resource Information
12937:
12938: =over 4
12939:
12940: =item *
12941:
12942: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
12943: and returns the value of a variety of different possible values,
12944: $varname should be a request string, and the other parameters can be
12945: used to specify who and what one is asking about. Ordinarily, $cid
12946: does not need to be specified, as it is retrived from
12947: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12948: within lonuserstate::loadmap() when initializing a course, before
12949: $env{'request.course.id'} has been set, so it needs to be provided
12950: in that one case.
12951:
12952: Possible values for $varname are environment.lastname (or other item
12953: from the envirnment hash), user.name (or someother aspect about the
12954: user), resource.0.maxtries (or some other part and parameter of a
12955: resource)
12956:
12957: =item *
12958:
12959: directcondval($number) : get current value of a condition; reads from a state
12960: string
12961:
12962: =item *
12963:
12964: condval($condidx) : value of condition index based on state
12965:
12966: =item *
12967:
12968: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12969: resource's metadata, $what should be either a specific key, or either
12970: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12971: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12972:
12973: this function automatically caches all requests
12974:
12975: =item *
12976:
12977: metadata_query($query,$custom,$customshow) : make a metadata query against the
12978: network of library servers; returns file handle of where SQL and regex results
12979: will be stored for query
12980:
12981: =item *
12982:
12983: symbread($filename) : return symbolic list entry (filename argument optional);
12984: returns the data handle
12985:
12986: =item *
12987:
12988: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12989: and is a possible symb for the URL in $thisfn, and if is an encrypted
12990: resource that the user accessed using /enc/ returns a 1 on success, 0
12991: on failure, user must be in a course, as it assumes the existence of
12992: the course initial hash, and uses $env('request.course.id'}. The third
12993: arg is an optional reference to a scalar. If this arg is passed in the
12994: call to symbverify, it will be set to 1 if the symb has been set to be
12995: encrypted; otherwise it will be null.
12996:
12997: =item *
12998:
12999: symbclean($symb) : removes versions numbers from a symb, returns the
13000: cleaned symb
13001:
13002: =item *
13003:
13004: is_on_map($uri) : checks if the $uri is somewhere on the current
13005: course map, user must be in a course for it to work.
13006:
13007: =item *
13008:
13009: numval($salt) : return random seed value (addend for rndseed)
13010:
13011: =item *
13012:
13013: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13014: a random seed, all arguments are optional, if they aren't sent it uses the
13015: environment to derive them. Note: if symb isn't sent and it can't get one
13016: from &symbread it will use the current time as its return value
13017:
13018: =item *
13019:
13020: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13021: unfakeable, receipt
13022:
13023: =item *
13024:
13025: receipt() : API to ireceipt working off of env values; given out to users
13026:
13027: =item *
13028:
13029: countacc($url) : count the number of accesses to a given URL
13030:
13031: =item *
13032:
13033: 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
13034:
13035: =item *
13036:
13037: 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)
13038:
13039: =item *
13040:
13041: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13042:
13043: =item *
13044:
13045: devalidate($symb) : devalidate temporary spreadsheet calculations,
13046: forcing spreadsheet to reevaluate the resource scores next time.
13047:
13048: =item *
13049:
13050: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13051: when viewing in course context.
13052:
13053: input: six args -- filename (decluttered), course number, course domain,
13054: url, symb (if registered) and group (if this is a
13055: group item -- e.g., bulletin board, group page etc.).
13056:
13057: output: array of five scalars --
13058: $cfile -- url for file editing if editable on current server
13059: $home -- homeserver of resource (i.e., for author if published,
13060: or course if uploaded.).
13061: $switchserver -- 1 if server switch will be needed.
13062: $forceedit -- 1 if icon/link should be to go to edit mode
13063: $forceview -- 1 if icon/link should be to go to view mode
13064:
13065: =item *
13066:
13067: is_course_upload($file,$cnum,$cdom)
13068:
13069: Used in course context to determine if current file was uploaded to
13070: the course (i.e., would be found in /userfiles/docs on the course's
13071: homeserver.
13072:
13073: input: 3 args -- filename (decluttered), course number and course domain.
13074: output: boolean -- 1 if file was uploaded.
13075:
13076: =back
13077:
13078: =head2 Storing/Retreiving Data
13079:
13080: =over 4
13081:
13082: =item *
13083:
13084: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13085: for this url; hashref needs to be given and should be a \%hashname; the
13086: remaining args aren't required and if they aren't passed or are '' they will
13087: be derived from the env
13088:
13089: =item *
13090:
13091: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13092: uses critical subroutine
13093:
13094: =item *
13095:
13096: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13097: all args are optional
13098:
13099: =item *
13100:
13101: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13102: dumps the complete (or key matching regexp) namespace into a hash
13103: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13104: normally &store()ed into
13105:
13106: $range should be either an integer '100' (give me the first 100
13107: matching records)
13108: or be two integers sperated by a - with no spaces
13109: '30-50' (give me the 30th through the 50th matching
13110: records)
13111:
13112:
13113: =item *
13114:
13115: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13116: replaces a &store() version of data with a replacement set of data
13117: for a particular resource in a namespace passed in the $storehash hash
13118: reference
13119:
13120: =item *
13121:
13122: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13123: works very similar to store/cstore, but all data is stored in a
13124: temporary location and can be reset using tmpreset, $storehash should
13125: be a hash reference, returns nothing on success
13126:
13127: =item *
13128:
13129: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13130: similar to restore, but all data is stored in a temporary location and
13131: can be reset using tmpreset. Returns a hash of values on success,
13132: error string otherwise.
13133:
13134: =item *
13135:
13136: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13137: deltes all keys for $symb form the temporary storage hash.
13138:
13139: =item *
13140:
13141: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13142: reference filled in from namesp ($udom and $uname are optional)
13143:
13144: =item *
13145:
13146: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13147: namesp ($udom and $uname are optional)
13148:
13149: =item *
13150:
13151: dump($namespace,$udom,$uname,$regexp,$range) :
13152: dumps the complete (or key matching regexp) namespace into a hash
13153: ($udom, $uname, $regexp, $range are optional)
13154:
13155: $range should be either an integer '100' (give me the first 100
13156: matching records)
13157: or be two integers sperated by a - with no spaces
13158: '30-50' (give me the 30th through the 50th matching
13159: records)
13160: =item *
13161:
13162: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13163: $store can be a scalar, an array reference, or if the amount to be
13164: incremented is > 1, a hash reference.
13165:
13166: ($udom and $uname are optional)
13167:
13168: =item *
13169:
13170: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13171: ($udom and $uname are optional)
13172:
13173: =item *
13174:
13175: cput($namespace,$storehash,$udom,$uname) : critical put
13176: ($udom and $uname are optional)
13177:
13178: =item *
13179:
13180: newput($namespace,$storehash,$udom,$uname) :
13181:
13182: Attempts to store the items in the $storehash, but only if they don't
13183: currently exist, if this succeeds you can be certain that you have
13184: successfully created a new key value pair in the $namespace db.
13185:
13186:
13187: Args:
13188: $namespace: name of database to store values to
13189: $storehash: hashref to store to the db
13190: $udom: (optional) domain of user containing the db
13191: $uname: (optional) name of user caontaining the db
13192:
13193: Returns:
13194: 'ok' -> succeeded in storing all keys of $storehash
13195: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13196: least <key> already existed in the db (other
13197: requested keys may also already exist)
13198: 'error: <msg>' -> unable to tie the DB or other error occurred
13199: 'con_lost' -> unable to contact request server
13200: 'refused' -> action was not allowed by remote machine
13201:
13202:
13203: =item *
13204:
13205: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13206: reference filled in from namesp (encrypts the return communication)
13207: ($udom and $uname are optional)
13208:
13209: =item *
13210:
13211: log($udom,$name,$home,$message) : write to permanent log for user; use
13212: critical subroutine
13213:
13214: =item *
13215:
13216: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13217: array reference filled in from namespace found in domain level on either
13218: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13219:
13220: =item *
13221:
13222: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13223: domain level either on specified domain server ($uhome) or primary domain
13224: server ($udom and $uhome are optional)
13225:
13226: =item *
13227:
13228: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13229: for: authentication, language, quotas, timezone, date locale, and portal URL in
13230: the target domain.
13231:
13232: May also include additional key => value pairs for the following groups:
13233:
13234: =over
13235:
13236: =item
13237: disk quotas (MB allocated by default to portfolios and authoring spaces).
13238:
13239: =over
13240:
13241: =item defaultquota, authorquota
13242:
13243: =back
13244:
13245: =item
13246: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13247: portfolio for users).
13248:
13249: =over
13250:
13251: =item
13252: aboutme, blog, webdav, portfolio
13253:
13254: =back
13255:
13256: =item
13257: requestcourses: ability to request courses, and how requests are processed.
13258:
13259: =over
13260:
13261: =item
13262: official, unofficial, community
13263:
13264: =back
13265:
13266: =item
13267: inststatus: types of institutional affiliation, and order in which they are displayed.
13268:
13269: =over
13270:
13271: =item
13272: inststatustypes, inststatusorder
13273:
13274: =back
13275:
13276: =item
13277: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13278: for course's uploaded content.
13279:
13280: =over
13281:
13282: =item
13283: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13284:
13285: =back
13286:
13287: =item
13288: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13289: on your servers.
13290:
13291: =over
13292:
13293: =item
13294: remotesessions, hostedsessions
13295:
13296: =back
13297:
13298: =back
13299:
13300: In cases where a domain coordinator has never used the "Set Domain Configuration"
13301: utility to create a configuration.db file on a domain's primary library server
13302: only the following domain defaults: auth_def, auth_arg_def, lang_def
13303: -- corresponding values are authentication type (internal, krb4, krb5,
13304: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13305: will be available. Values are retrieved from cache (if current), unless the
13306: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13307: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13308:
13309: Typical usage:
13310:
13311: %domdefaults = &get_domain_defaults($target_domain);
13312:
13313: =back
13314:
13315: =head2 Network Status Functions
13316:
13317: =over 4
13318:
13319: =item *
13320:
13321: dirlist() : return directory list based on URI (first arg).
13322:
13323: Inputs: 1 required, 5 optional.
13324:
13325: =over
13326:
13327: =item
13328: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13329:
13330: =item
13331: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13332:
13333: =item
13334: $username - username of user/course to be listed. Extracted from $uri if absent.
13335:
13336: =item
13337: $getpropath - boolean: 1 if prepend path using &propath().
13338:
13339: =item
13340: $getuserdir - boolean: 1 if prepend path for "userfiles".
13341:
13342: =item
13343: $alternateRoot - path to prepend in place of path from $uri.
13344:
13345: =back
13346:
13347: Returns: Array of up to two items.
13348:
13349: =over
13350:
13351: a reference to an array of files/subdirectories
13352:
13353: =over
13354:
13355: Each element in the array of files/subdirectories is a & separated list of
13356: item name and the result of running stat on the item. If dirlist was requested
13357: for a file instead of a directory, the item name will be ''. For a directory
13358: listing, if the item is a metadata file, the element will end &N&M
13359: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13360: default copyright set (1).
13361:
13362: =back
13363:
13364: a scalar containing error condition (if encountered).
13365:
13366: =over
13367:
13368: =item
13369: no_host (no homeserver identified for $username:$domain).
13370:
13371: =item
13372: no_such_host (server contacted for listing not identified as valid host).
13373:
13374: =item
13375: con_lost (connection to remote server failed).
13376:
13377: =item
13378: refused (invalid $username:$domain received on lond side).
13379:
13380: =item
13381: no_such_dir (directory at specified path on lond side does not exist).
13382:
13383: =item
13384: empty (directory at specified path on lond side is empty).
13385:
13386: =over
13387:
13388: This is currently not encountered because the &ls3, &ls2,
13389: &ls (_handler) routines on the lond side do not filter out
13390: . and .. from a directory listing.
13391:
13392: =back
13393:
13394: =back
13395:
13396: =back
13397:
13398: =item *
13399:
13400: spareserver() : find server with least workload from spare.tab
13401:
13402:
13403: =item *
13404:
13405: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13406: if there is no corresponding loncapa host.
13407:
13408: =back
13409:
13410:
13411: =head2 Apache Request
13412:
13413: =over 4
13414:
13415: =item *
13416:
13417: ssi($url,%hash) : server side include, does a complete request cycle on url to
13418: localhost, posts hash
13419:
13420: =back
13421:
13422: =head2 Data to String to Data
13423:
13424: =over 4
13425:
13426: =item *
13427:
13428: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13429: and '&' separators, supports elements that are arrayrefs and hashrefs
13430:
13431: =item *
13432:
13433: hashref2str($hashref) : convert a hashref into a string complete with
13434: escaping and '=' and '&' separators, supports elements that are
13435: arrayrefs and hashrefs
13436:
13437: =item *
13438:
13439: arrayref2str($arrayref) : convert an arrayref into a string complete
13440: with escaping and '&' separators, supports elements that are arrayrefs
13441: and hashrefs
13442:
13443: =item *
13444:
13445: str2hash($string) : convert string to hash using unescaping and
13446: splitting on '=' and '&', supports elements that are arrayrefs and
13447: hashrefs
13448:
13449: =item *
13450:
13451: str2array($string) : convert string to hash using unescaping and
13452: splitting on '&', supports elements that are arrayrefs and hashrefs
13453:
13454: =back
13455:
13456: =head2 Logging Routines
13457:
13458:
13459: These routines allow one to make log messages in the lonnet.log and
13460: lonnet.perm logfiles.
13461:
13462: =over 4
13463:
13464: =item *
13465:
13466: logtouch() : make sure the logfile, lonnet.log, exists
13467:
13468: =item *
13469:
13470: logthis() : append message to the normal lonnet.log file, it gets
13471: preiodically rolled over and deleted.
13472:
13473: =item *
13474:
13475: logperm() : append a permanent message to lonnet.perm.log, this log
13476: file never gets deleted by any automated portion of the system, only
13477: messages of critical importance should go in here.
13478:
13479:
13480: =back
13481:
13482: =head2 General File Helper Routines
13483:
13484: =over 4
13485:
13486: =item *
13487:
13488: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13489: (a) files in /uploaded
13490: (i) If a local copy of the file exists -
13491: compares modification date of local copy with last-modified date for
13492: definitive version stored on home server for course. If local copy is
13493: stale, requests a new version from the home server and stores it.
13494: If the original has been removed from the home server, then local copy
13495: is unlinked.
13496: (ii) If local copy does not exist -
13497: requests the file from the home server and stores it.
13498:
13499: If $caller is 'uploadrep':
13500: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13501: for request for files originally uploaded via DOCS.
13502: - returns 'ok' if fresh local copy now available, -1 otherwise.
13503:
13504: Otherwise:
13505: This indicates a call from the content generation phase of the request.
13506: - returns the entire contents of the file or -1.
13507:
13508: (b) files in /res
13509: - returns the entire contents of a file or -1;
13510: it properly subscribes to and replicates the file if neccessary.
13511:
13512:
13513: =item *
13514:
13515: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13516: reference
13517:
13518: returns either a stat() list of data about the file or an empty list
13519: if the file doesn't exist or couldn't find out about it (connection
13520: problems or user unknown)
13521:
13522: =item *
13523:
13524: filelocation($dir,$file) : returns file system location of a file
13525: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13526: directory that relative $file lookups are to looked in ($dir of /a/dir
13527: and a file of ../bob will become /a/bob)
13528:
13529: =item *
13530:
13531: hreflocation($dir,$file) : returns file system location or a URL; same as
13532: filelocation except for hrefs
13533:
13534: =item *
13535:
13536: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13537:
13538: =back
13539:
13540: =head2 Usererfile file routines (/uploaded*)
13541:
13542: =over 4
13543:
13544: =item *
13545:
13546: userfileupload(): main rotine for putting a file in a user or course's
13547: filespace, arguments are,
13548:
13549: formname - required - this is the name of the element in $env where the
13550: filename, and the contents of the file to create/modifed exist
13551: the filename is in $env{'form.'.$formname.'.filename'} and the
13552: contents of the file is located in $env{'form.'.$formname}
13553: context - if coursedoc, store the file in the course of the active role
13554: of the current user;
13555: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13556: if 'canceloverwrite': delete file in tmp/overwrites directory
13557: subdir - required - subdirectory to put the file in under ../userfiles/
13558: if undefined, it will be placed in "unknown"
13559:
13560: (This routine calls clean_filename() to remove any dangerous
13561: characters from the filename, and then calls finuserfileupload() to
13562: complete the transaction)
13563:
13564: returns either the url of the uploaded file (/uploaded/....) if successful
13565: and /adm/notfound.html if unsuccessful
13566:
13567: =item *
13568:
13569: clean_filename(): routine for cleaing a filename up for storage in
13570: userfile space, argument is:
13571:
13572: filename - proposed filename
13573:
13574: returns: the new clean filename
13575:
13576: =item *
13577:
13578: finishuserfileupload(): routine that creates and sends the file to
13579: userspace, probably shouldn't be called directly
13580:
13581: docuname: username or courseid of destination for the file
13582: docudom: domain of user/course of destination for the file
13583: formname: same as for userfileupload()
13584: fname: filename (including subdirectories) for the file
13585: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13586: allfiles: reference to hash used to store objects found by parser
13587: codebase: reference to hash used for codebases of java objects found by parser
13588: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13589: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13590: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13591: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13592: context: if 'overwrite', will move the uploaded file from its temporary location to
13593: userfiles to facilitate overwriting a previously uploaded file with same name.
13594: mimetype: reference to scalar to accommodate mime type determined
13595: from File::MMagic if $parser = parse.
13596:
13597: returns either the url of the uploaded file (/uploaded/....) if successful
13598: and /adm/notfound.html if unsuccessful (or an error message if context
13599: was 'overwrite').
13600:
13601:
13602: =item *
13603:
13604: renameuserfile(): renames an existing userfile to a new name
13605:
13606: Args:
13607: docuname: username or courseid of destination for the file
13608: docudom: domain of user/course of destination for the file
13609: old: current file name (including any subdirs under userfiles)
13610: new: desired file name (including any subdirs under userfiles)
13611:
13612: =item *
13613:
13614: mkdiruserfile(): creates a directory is a userfiles dir
13615:
13616: Args:
13617: docuname: username or courseid of destination for the file
13618: docudom: domain of user/course of destination for the file
13619: dir: dir to create (including any subdirs under userfiles)
13620:
13621: =item *
13622:
13623: removeuserfile(): removes a file that exists in userfiles
13624:
13625: Args:
13626: docuname: username or courseid of destination for the file
13627: docudom: domain of user/course of destination for the file
13628: fname: filname to delete (including any subdirs under userfiles)
13629:
13630: =item *
13631:
13632: removeuploadedurl(): convience function for removeuserfile()
13633:
13634: Args:
13635: url: a full /uploaded/... url to delete
13636:
13637: =item *
13638:
13639: get_portfile_permissions():
13640: Args:
13641: domain: domain of user or course contain the portfolio files
13642: user: name of user or num of course contain the portfolio files
13643: Returns:
13644: hashref of a dump of the proper file_permissions.db
13645:
13646:
13647: =item *
13648:
13649: get_access_controls():
13650:
13651: Args:
13652: current_permissions: the hash ref returned from get_portfile_permissions()
13653: group: (optional) the group you want the files associated with
13654: file: (optional) the file you want access info on
13655:
13656: Returns:
13657: a hash (keys are file names) of hashes containing
13658: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13659: values are XML containing access control settings (see below)
13660:
13661: Internal notes:
13662:
13663: access controls are stored in file_permissions.db as key=value pairs.
13664: key -> path to file/file_name\0uniqueID:scope_end_start
13665: where scope -> public,guest,course,group,domains or users.
13666: end -> UNIX time for end of access (0 -> no end date)
13667: start -> UNIX time for start of access
13668:
13669: value -> XML description of access control
13670: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13671: <start></start>
13672: <end></end>
13673:
13674: <password></password> for scope type = guest
13675:
13676: <domain></domain> for scope type = course or group
13677: <number></number>
13678: <roles id="">
13679: <role></role>
13680: <access></access>
13681: <section></section>
13682: <group></group>
13683: </roles>
13684:
13685: <dom></dom> for scope type = domains
13686:
13687: <users> for scope type = users
13688: <user>
13689: <uname></uname>
13690: <udom></udom>
13691: </user>
13692: </users>
13693: </scope>
13694:
13695: Access data is also aggregated for each file in an additional key=value pair:
13696: key -> path to file/file_name\0accesscontrol
13697: value -> reference to hash
13698: hash contains key = value pairs
13699: where key = uniqueID:scope_end_start
13700: value = UNIX time record was last updated
13701:
13702: Used to improve speed of look-ups of access controls for each file.
13703:
13704: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13705:
13706: =item *
13707:
13708: modify_access_controls():
13709:
13710: Modifies access controls for a portfolio file
13711: Args
13712: 1. file name
13713: 2. reference to hash of required changes,
13714: 3. domain
13715: 4. username
13716: where domain,username are the domain of the portfolio owner
13717: (either a user or a course)
13718:
13719: Returns:
13720: 1. result of additions or updates ('ok' or 'error', with error message).
13721: 2. result of deletions ('ok' or 'error', with error message).
13722: 3. reference to hash of any new or updated access controls.
13723: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13724: key = integer (inbound ID)
13725: value = uniqueID
13726:
13727: =item *
13728:
13729: get_timebased_id():
13730:
13731: Attempts to get a unique timestamp-based suffix for use with items added to a
13732: course via the Course Editor (e.g., folders, composite pages,
13733: group bulletin boards).
13734:
13735: Args: (first three required; six others optional)
13736:
13737: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13738: docssequence, or name of group
13739:
13740: 2. keyid (alphanumeric): name of temporary locking key in hash,
13741: e.g., num, boardids
13742:
13743: 3. namespace: name of gdbm file used to store suffixes already assigned;
13744: file will be named nohist_namespace.db
13745:
13746: 4. cdom: domain of course; default is current course domain from %env
13747:
13748: 5. cnum: course number; default is current course number from %env
13749:
13750: 6. idtype: set to concat if an additional digit is to be appended to the
13751: unix timestamp to form the suffix, if the plain timestamp is already
13752: in use. Default is to not do this, but simply increment the unix
13753: timestamp by 1 until a unique key is obtained.
13754:
13755: 7. who: holder of locking key; defaults to user:domain for user.
13756:
13757: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13758: retrying); default is 3.
13759:
13760: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13761:
13762: Returns:
13763:
13764: 1. suffix obtained (numeric)
13765:
13766: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13767:
13768: 3. error: contains (localized) error message if an error occurred.
13769:
13770:
13771: =back
13772:
13773: =head2 HTTP Helper Routines
13774:
13775: =over 4
13776:
13777: =item *
13778:
13779: escape() : unpack non-word characters into CGI-compatible hex codes
13780:
13781: =item *
13782:
13783: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13784:
13785: =back
13786:
13787: =head1 PRIVATE SUBROUTINES
13788:
13789: =head2 Underlying communication routines (Shouldn't call)
13790:
13791: =over 4
13792:
13793: =item *
13794:
13795: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13796:
13797: =item *
13798:
13799: reply() : uses subreply to send a message to remote machine, logs all failures
13800:
13801: =item *
13802:
13803: critical() : passes a critical message to another server; if cannot
13804: get through then place message in connection buffer directory and
13805: returns con_delayed, if incapable of saving message, returns
13806: con_failed
13807:
13808: =item *
13809:
13810: reconlonc() : tries to reconnect lonc client processes.
13811:
13812: =back
13813:
13814: =head2 Resource Access Logging
13815:
13816: =over 4
13817:
13818: =item *
13819:
13820: flushcourselogs() : flush (save) buffer logs and access logs
13821:
13822: =item *
13823:
13824: courselog($what) : save message for course in hash
13825:
13826: =item *
13827:
13828: courseacclog($what) : save message for course using &courselog(). Perform
13829: special processing for specific resource types (problems, exams, quizzes, etc).
13830:
13831: =item *
13832:
13833: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13834: as a PerlChildExitHandler
13835:
13836: =back
13837:
13838: =head2 Other
13839:
13840: =over 4
13841:
13842: =item *
13843:
13844: symblist($mapname,%newhash) : update symbolic storage links
13845:
13846: =back
13847:
13848: =cut
13849:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>