File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1163:
download - view:
text,
annotated -
select for diffs
Sun Apr 1 16:19:20 2012 UTC (12 years, 4 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Bug 6518.
- Blocking based on timed interval expires when items in the folder or
resource to which the interval applies are no longer answerable (e.g.,
all problems correct, or no tries left).
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1163 2012/04/01 16:19:20 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: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
85: %courseownerbuf, %coursetypebuf,$locknum);
86:
87: use IO::Socket;
88: use GDBM_File;
89: use HTML::LCParser;
90: use Fcntl qw(:flock);
91: use Storable qw(thaw nfreeze);
92: use Time::HiRes qw( gettimeofday tv_interval );
93: use Cache::Memcached;
94: use Digest::MD5;
95: use Math::Random;
96: use File::MMagic;
97: use LONCAPA qw(:DEFAULT :match);
98: use LONCAPA::Configuration;
99: use LONCAPA::lonmetadata;
100:
101: use File::Copy;
102:
103: my $readit;
104: my $max_connection_retries = 10; # Or some such value.
105:
106: require Exporter;
107:
108: our @ISA = qw (Exporter);
109: our @EXPORT = qw(%env);
110:
111:
112: # --------------------------------------------------------------------- Logging
113: {
114: my $logid;
115: sub instructor_log {
116: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if (($cnum eq '') || ($cdom eq '')) {
118: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
119: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
120: }
121: $logid++;
122: my $now = time();
123: my $id=$now.'00000'.$$.'00000'.$logid;
124: return &Apache::lonnet::put('nohist_'.$hash_name,
125: { $id => {
126: 'exe_uname' => $env{'user.name'},
127: 'exe_udom' => $env{'user.domain'},
128: 'exe_time' => $now,
129: 'exe_ip' => $ENV{'REMOTE_ADDR'},
130: 'delflag' => $delflag,
131: 'logentry' => $storehash,
132: 'uname' => $uname,
133: 'udom' => $udom,
134: }
135: },$cdom,$cnum);
136: }
137: }
138:
139: sub logtouch {
140: my $execdir=$perlvar{'lonDaemons'};
141: unless (-e "$execdir/logs/lonnet.log") {
142: open(my $fh,">>$execdir/logs/lonnet.log");
143: close $fh;
144: }
145: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
146: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
147: }
148:
149: sub logthis {
150: my $message=shift;
151: my $execdir=$perlvar{'lonDaemons'};
152: my $now=time;
153: my $local=localtime($now);
154: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
155: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
156: print $fh $logstring;
157: close($fh);
158: }
159: return 1;
160: }
161:
162: sub logperm {
163: my $message=shift;
164: my $execdir=$perlvar{'lonDaemons'};
165: my $now=time;
166: my $local=localtime($now);
167: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
168: print $fh "$now:$message:$local\n";
169: close($fh);
170: }
171: return 1;
172: }
173:
174: sub create_connection {
175: my ($hostname,$lonid) = @_;
176: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
177: Type => SOCK_STREAM,
178: Timeout => 10);
179: return 0 if (!$client);
180: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
181: my $result = <$client>;
182: chomp($result);
183: return 1 if ($result eq 'done');
184: return 0;
185: }
186:
187: sub get_server_timezone {
188: my ($cnum,$cdom) = @_;
189: my $home=&homeserver($cnum,$cdom);
190: if ($home ne 'no_host') {
191: my $cachetime = 24*3600;
192: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
193: if (defined($cached)) {
194: return $timezone;
195: } else {
196: my $timezone = &reply('servertimezone',$home);
197: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
198: }
199: }
200: }
201:
202: sub get_server_distarch {
203: my ($lonhost,$ignore_cache) = @_;
204: if (defined($lonhost)) {
205: if (!defined(&hostname($lonhost))) {
206: return;
207: }
208: my $cachetime = 12*3600;
209: if (!$ignore_cache) {
210: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
211: if (defined($cached)) {
212: return $distarch;
213: }
214: }
215: my $rep = &reply('serverdistarch',$lonhost);
216: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
217: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
218: $rep eq '') {
219: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
220: }
221: }
222: return;
223: }
224:
225: sub get_server_loncaparev {
226: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
227: if (defined($lonhost)) {
228: if (!defined(&hostname($lonhost))) {
229: undef($lonhost);
230: }
231: }
232: if (!defined($lonhost)) {
233: if (defined(&domain($dom,'primary'))) {
234: $lonhost=&domain($dom,'primary');
235: if ($lonhost eq 'no_host') {
236: undef($lonhost);
237: }
238: }
239: }
240: if (defined($lonhost)) {
241: my $cachetime = 12*3600;
242: if (!$ignore_cache) {
243: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
244: if (defined($cached)) {
245: return $loncaparev;
246: }
247: }
248: my ($answer,$loncaparev);
249: my @ids=¤t_machine_ids();
250: if (grep(/^\Q$lonhost\E$/,@ids)) {
251: $answer = $perlvar{'lonVersion'};
252: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
253: $loncaparev = $1;
254: }
255: } else {
256: $answer = &reply('serverloncaparev',$lonhost);
257: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
258: if ($caller eq 'loncron') {
259: my $ua=new LWP::UserAgent;
260: $ua->timeout(4);
261: my $protocol = $protocol{$lonhost};
262: $protocol = 'http' if ($protocol ne 'https');
263: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
264: my $request=new HTTP::Request('GET',$url);
265: my $response=$ua->request($request);
266: unless ($response->is_error()) {
267: my $content = $response->content;
268: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
269: $loncaparev = $1;
270: }
271: }
272: } else {
273: $loncaparev = $loncaparevs{$lonhost};
274: }
275: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
276: $loncaparev = $1;
277: }
278: }
279: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
280: }
281: }
282:
283: sub get_server_homeID {
284: my ($hostname,$ignore_cache,$caller) = @_;
285: unless ($ignore_cache) {
286: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
287: if (defined($cached)) {
288: return $serverhomeID;
289: }
290: }
291: my $cachetime = 12*3600;
292: my $serverhomeID;
293: if ($caller eq 'loncron') {
294: my @machine_ids = &machine_ids($hostname);
295: foreach my $id (@machine_ids) {
296: my $response = &reply('serverhomeID',$id);
297: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
298: $serverhomeID = $response;
299: last;
300: }
301: }
302: if ($serverhomeID eq '') {
303: $serverhomeID = $machine_ids[-1];
304: }
305: } else {
306: $serverhomeID = $serverhomeIDs{$hostname};
307: }
308: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
309: }
310:
311: sub get_remote_globals {
312: my ($lonhost,$whathash,$ignore_cache) = @_;
313: my ($result,%returnhash,%whatneeded);
314: if (ref($whathash) eq 'HASH') {
315: foreach my $what (sort(keys(%{$whathash}))) {
316: my $hashid = $lonhost.'-'.$what;
317: my ($response,$cached);
318: unless ($ignore_cache) {
319: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
320: }
321: if (defined($cached)) {
322: $returnhash{$what} = $response;
323: } else {
324: $whatneeded{$what} = 1;
325: }
326: }
327: if (keys(%whatneeded) == 0) {
328: $result = 'ok';
329: } else {
330: my $requested = &freeze_escape(\%whatneeded);
331: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
332: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
333: ($rep eq 'unknown_cmd')) {
334: $result = $rep;
335: } else {
336: $result = 'ok';
337: my @pairs=split(/\&/,$rep);
338: foreach my $item (@pairs) {
339: my ($key,$value)=split(/=/,$item,2);
340: my $what = &unescape($key);
341: my $hashid = $lonhost.'-'.$what;
342: $returnhash{$what}=&thaw_unescape($value);
343: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
344: }
345: }
346: }
347: }
348: return ($result,\%returnhash);
349: }
350:
351: sub remote_devalidate_cache {
352: my ($lonhost,$name,$id) = @_;
353: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
354: return $response;
355: }
356:
357: # -------------------------------------------------- Non-critical communication
358: sub subreply {
359: my ($cmd,$server)=@_;
360: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
361: #
362: # With loncnew process trimming, there's a timing hole between lonc server
363: # process exit and the master server picking up the listen on the AF_UNIX
364: # socket. In that time interval, a lock file will exist:
365:
366: my $lockfile=$peerfile.".lock";
367: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
368: sleep(1);
369: }
370: # At this point, either a loncnew parent is listening or an old lonc
371: # or loncnew child is listening so we can connect or everything's dead.
372: #
373: # We'll give the connection a few tries before abandoning it. If
374: # connection is not possible, we'll con_lost back to the client.
375: #
376: my $client;
377: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
378: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
379: Type => SOCK_STREAM,
380: Timeout => 10);
381: if ($client) {
382: last; # Connected!
383: } else {
384: &create_connection(&hostname($server),$server);
385: }
386: sleep(1); # Try again later if failed connection.
387: }
388: my $answer;
389: if ($client) {
390: print $client "sethost:$server:$cmd\n";
391: $answer=<$client>;
392: if (!$answer) { $answer="con_lost"; }
393: chomp($answer);
394: } else {
395: $answer = 'con_lost'; # Failed connection.
396: }
397: return $answer;
398: }
399:
400: sub reply {
401: my ($cmd,$server)=@_;
402: unless (defined(&hostname($server))) { return 'no_such_host'; }
403: my $answer=subreply($cmd,$server);
404: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
405: &logthis("<font color=\"blue\">WARNING:".
406: " $cmd to $server returned $answer</font>");
407: }
408: return $answer;
409: }
410:
411: # ----------------------------------------------------------- Send USR1 to lonc
412:
413: sub reconlonc {
414: my ($lonid) = @_;
415: my $hostname = &hostname($lonid);
416: if ($lonid) {
417: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
418: if ($hostname && -e $peerfile) {
419: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
420: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
421: Type => SOCK_STREAM,
422: Timeout => 10);
423: if ($client) {
424: print $client ("reset_retries\n");
425: my $answer=<$client>;
426: #reset just this one.
427: }
428: }
429: return;
430: }
431:
432: &logthis("Trying to reconnect lonc");
433: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
434: if (open(my $fh,"<$loncfile")) {
435: my $loncpid=<$fh>;
436: chomp($loncpid);
437: if (kill 0 => $loncpid) {
438: &logthis("lonc at pid $loncpid responding, sending USR1");
439: kill USR1 => $loncpid;
440: sleep 1;
441: } else {
442: &logthis(
443: "<font color=\"blue\">WARNING:".
444: " lonc at pid $loncpid not responding, giving up</font>");
445: }
446: } else {
447: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
448: }
449: }
450:
451: # ------------------------------------------------------ Critical communication
452:
453: sub critical {
454: my ($cmd,$server)=@_;
455: unless (&hostname($server)) {
456: &logthis("<font color=\"blue\">WARNING:".
457: " Critical message to unknown server ($server)</font>");
458: return 'no_such_host';
459: }
460: my $answer=reply($cmd,$server);
461: if ($answer eq 'con_lost') {
462: &reconlonc("$perlvar{'lonSockDir'}/$server");
463: my $answer=reply($cmd,$server);
464: if ($answer eq 'con_lost') {
465: my $now=time;
466: my $middlename=$cmd;
467: $middlename=substr($middlename,0,16);
468: $middlename=~s/\W//g;
469: my $dfilename=
470: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
471: $dumpcount++;
472: {
473: my $dfh;
474: if (open($dfh,">$dfilename")) {
475: print $dfh "$cmd\n";
476: close($dfh);
477: }
478: }
479: sleep 2;
480: my $wcmd='';
481: {
482: my $dfh;
483: if (open($dfh,"<$dfilename")) {
484: $wcmd=<$dfh>;
485: close($dfh);
486: }
487: }
488: chomp($wcmd);
489: if ($wcmd eq $cmd) {
490: &logthis("<font color=\"blue\">WARNING: ".
491: "Connection buffer $dfilename: $cmd</font>");
492: &logperm("D:$server:$cmd");
493: return 'con_delayed';
494: } else {
495: &logthis("<font color=\"red\">CRITICAL:"
496: ." Critical connection failed: $server $cmd</font>");
497: &logperm("F:$server:$cmd");
498: return 'con_failed';
499: }
500: }
501: }
502: return $answer;
503: }
504:
505: # ------------------------------------------- check if return value is an error
506:
507: sub error {
508: my ($result) = @_;
509: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
510: if ($2 == 2) { return undef; }
511: return $1;
512: }
513: return undef;
514: }
515:
516: sub convert_and_load_session_env {
517: my ($lonidsdir,$handle)=@_;
518: my @profile;
519: {
520: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
521: if (!$opened) {
522: return 0;
523: }
524: flock($idf,LOCK_SH);
525: @profile=<$idf>;
526: close($idf);
527: }
528: my %temp_env;
529: foreach my $line (@profile) {
530: if ($line !~ m/=/) {
531: return 0;
532: }
533: chomp($line);
534: my ($envname,$envvalue)=split(/=/,$line,2);
535: $temp_env{&unescape($envname)} = &unescape($envvalue);
536: }
537: unlink("$lonidsdir/$handle.id");
538: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
539: 0640)) {
540: %disk_env = %temp_env;
541: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
542: untie(%disk_env);
543: }
544: return 1;
545: }
546:
547: # ------------------------------------------- Transfer profile into environment
548: my $env_loaded;
549: sub transfer_profile_to_env {
550: my ($lonidsdir,$handle,$force_transfer) = @_;
551: if (!$force_transfer && $env_loaded) { return; }
552:
553: if (!defined($lonidsdir)) {
554: $lonidsdir = $perlvar{'lonIDsDir'};
555: }
556: if (!defined($handle)) {
557: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
558: }
559:
560: my $convert;
561: {
562: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
563: if (!$opened) {
564: return;
565: }
566: flock($idf,LOCK_SH);
567: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
568: &GDBM_READER(),0640)) {
569: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
570: untie(%disk_env);
571: } else {
572: $convert = 1;
573: }
574: }
575: if ($convert) {
576: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
577: &logthis("Failed to load session, or convert session.");
578: }
579: }
580:
581: my %remove;
582: while ( my $envname = each(%env) ) {
583: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
584: if ($time < time-300) {
585: $remove{$key}++;
586: }
587: }
588: }
589:
590: $env{'user.environment'} = "$lonidsdir/$handle.id";
591: $env_loaded=1;
592: foreach my $expired_key (keys(%remove)) {
593: &delenv($expired_key);
594: }
595: }
596:
597: # ---------------------------------------------------- Check for valid session
598: sub check_for_valid_session {
599: my ($r,$name) = @_;
600: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
601: if ($name eq '') {
602: $name = 'lonID';
603: }
604: my $lonid=$cookies{$name};
605: return undef if (!$lonid);
606:
607: my $handle=&LONCAPA::clean_handle($lonid->value);
608: my $lonidsdir;
609: if ($name eq 'lonDAV') {
610: $lonidsdir=$r->dir_config('lonDAVsessDir');
611: } else {
612: $lonidsdir=$r->dir_config('lonIDsDir');
613: }
614: return undef if (!-e "$lonidsdir/$handle.id");
615:
616: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
617: return undef if (!$opened);
618:
619: flock($idf,LOCK_SH);
620: my %disk_env;
621: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
622: &GDBM_READER(),0640)) {
623: return undef;
624: }
625:
626: if (!defined($disk_env{'user.name'})
627: || !defined($disk_env{'user.domain'})) {
628: return undef;
629: }
630: return $handle;
631: }
632:
633: sub timed_flock {
634: my ($file,$lock_type) = @_;
635: my $failed=0;
636: eval {
637: local $SIG{__DIE__}='DEFAULT';
638: local $SIG{ALRM}=sub {
639: $failed=1;
640: die("failed lock");
641: };
642: alarm(13);
643: flock($file,$lock_type);
644: alarm(0);
645: };
646: if ($failed) {
647: return undef;
648: } else {
649: return 1;
650: }
651: }
652:
653: # ---------------------------------------------------------- Append Environment
654:
655: sub appenv {
656: my ($newenv,$roles) = @_;
657: if (ref($newenv) eq 'HASH') {
658: foreach my $key (keys(%{$newenv})) {
659: my $refused = 0;
660: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
661: $refused = 1;
662: if (ref($roles) eq 'ARRAY') {
663: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
664: if (grep(/^\Q$role\E$/,@{$roles})) {
665: $refused = 0;
666: }
667: }
668: }
669: if ($refused) {
670: &logthis("<font color=\"blue\">WARNING: ".
671: "Attempt to modify environment ".$key." to ".$newenv->{$key}
672: .'</font>');
673: delete($newenv->{$key});
674: } else {
675: $env{$key}=$newenv->{$key};
676: }
677: }
678: my $opened = open(my $env_file,'+<',$env{'user.environment'});
679: if ($opened
680: && &timed_flock($env_file,LOCK_EX)
681: &&
682: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
683: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
684: while (my ($key,$value) = each(%{$newenv})) {
685: $disk_env{$key} = $value;
686: }
687: untie(%disk_env);
688: }
689: }
690: return 'ok';
691: }
692: # ----------------------------------------------------- Delete from Environment
693:
694: sub delenv {
695: my ($delthis,$regexp,$roles) = @_;
696: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
697: my $refused = 1;
698: if (ref($roles) eq 'ARRAY') {
699: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
700: if (grep(/^\Q$role\E$/,@{$roles})) {
701: $refused = 0;
702: }
703: }
704: if ($refused) {
705: &logthis("<font color=\"blue\">WARNING: ".
706: "Attempt to delete from environment ".$delthis);
707: return 'error';
708: }
709: }
710: my $opened = open(my $env_file,'+<',$env{'user.environment'});
711: if ($opened
712: && &timed_flock($env_file,LOCK_EX)
713: &&
714: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
715: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
716: foreach my $key (keys(%disk_env)) {
717: if ($regexp) {
718: if ($key=~/^$delthis/) {
719: delete($env{$key});
720: delete($disk_env{$key});
721: }
722: } else {
723: if ($key=~/^\Q$delthis\E/) {
724: delete($env{$key});
725: delete($disk_env{$key});
726: }
727: }
728: }
729: untie(%disk_env);
730: }
731: return 'ok';
732: }
733:
734: sub get_env_multiple {
735: my ($name) = @_;
736: my @values;
737: if (defined($env{$name})) {
738: # exists is it an array
739: if (ref($env{$name})) {
740: @values=@{ $env{$name} };
741: } else {
742: $values[0]=$env{$name};
743: }
744: }
745: return(@values);
746: }
747:
748: # ------------------------------------------------------------------- Locking
749:
750: sub set_lock {
751: my ($text)=@_;
752: $locknum++;
753: my $id=$$.'-'.$locknum;
754: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
755: 'session.lock.'.$id => $text});
756: return $id;
757: }
758:
759: sub get_locks {
760: my $num=0;
761: my %texts=();
762: foreach my $lock (split(/\,/,$env{'session.locks'})) {
763: if ($lock=~/\w/) {
764: $num++;
765: $texts{$lock}=$env{'session.lock.'.$lock};
766: }
767: }
768: return ($num,%texts);
769: }
770:
771: sub remove_lock {
772: my ($id)=@_;
773: my $newlocks='';
774: foreach my $lock (split(/\,/,$env{'session.locks'})) {
775: if (($lock=~/\w/) && ($lock ne $id)) {
776: $newlocks.=','.$lock;
777: }
778: }
779: &appenv({'session.locks' => $newlocks});
780: &delenv('session.lock.'.$id);
781: }
782:
783: sub remove_all_locks {
784: my $activelocks=$env{'session.locks'};
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if ($lock=~/\w/) {
787: &remove_lock($lock);
788: }
789: }
790: }
791:
792:
793: # ------------------------------------------ Find out current server userload
794: sub userload {
795: my $numusers=0;
796: {
797: opendir(LONIDS,$perlvar{'lonIDsDir'});
798: my $filename;
799: my $curtime=time;
800: while ($filename=readdir(LONIDS)) {
801: next if ($filename eq '.' || $filename eq '..');
802: next if ($filename =~ /publicuser_\d+\.id/);
803: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
804: if ($curtime-$mtime < 1800) { $numusers++; }
805: }
806: closedir(LONIDS);
807: }
808: my $userloadpercent=0;
809: my $maxuserload=$perlvar{'lonUserLoadLim'};
810: if ($maxuserload) {
811: $userloadpercent=100*$numusers/$maxuserload;
812: }
813: $userloadpercent=sprintf("%.2f",$userloadpercent);
814: return $userloadpercent;
815: }
816:
817: # ------------------------------ Find server with least workload from spare.tab
818:
819: sub spareserver {
820: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
821: my $spare_server;
822: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
823: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
824: : $userloadpercent;
825: my ($uint_dom,$remotesessions);
826: if (($udom ne '') && (&domain($udom) ne '')) {
827: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
828: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
829: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
830: $remotesessions = $udomdefaults{'remotesessions'};
831: }
832: my $spareshash = &this_host_spares($udom);
833: if (ref($spareshash) eq 'HASH') {
834: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
835: foreach my $try_server (@{ $spareshash->{'primary'} }) {
836: if ($uint_dom) {
837: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
838: $try_server));
839: }
840: ($spare_server, $lowest_load) =
841: &compare_server_load($try_server, $spare_server, $lowest_load);
842: }
843: }
844:
845: my $found_server = ($spare_server ne '' && $lowest_load < 100);
846:
847: if (!$found_server) {
848: if (ref($spareshash->{'default'}) eq 'ARRAY') {
849: foreach my $try_server (@{ $spareshash->{'default'} }) {
850: if ($uint_dom) {
851: next unless (&spare_can_host($udom,$uint_dom,
852: $remotesessions,$try_server));
853: }
854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
857: }
858: }
859: }
860:
861: if (!$want_server_name) {
862: my $protocol = 'http';
863: if ($protocol{$spare_server} eq 'https') {
864: $protocol = $protocol{$spare_server};
865: }
866: if (defined($spare_server)) {
867: my $hostname = &hostname($spare_server);
868: if (defined($hostname)) {
869: $spare_server = $protocol.'://'.$hostname;
870: }
871: }
872: }
873: return $spare_server;
874: }
875:
876: sub compare_server_load {
877: my ($try_server, $spare_server, $lowest_load) = @_;
878:
879: my $loadans = &reply('load', $try_server);
880: my $userloadans = &reply('userload',$try_server);
881:
882: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
883: return ($spare_server, $lowest_load); #didn't get a number from the server
884: }
885:
886: my $load;
887: if ($loadans =~ /\d/) {
888: if ($userloadans =~ /\d/) {
889: #both are numbers, pick the bigger one
890: $load = ($loadans > $userloadans) ? $loadans
891: : $userloadans;
892: } else {
893: $load = $loadans;
894: }
895: } else {
896: $load = $userloadans;
897: }
898:
899: if (($load =~ /\d/) && ($load < $lowest_load)) {
900: $spare_server = $try_server;
901: $lowest_load = $load;
902: }
903: return ($spare_server,$lowest_load);
904: }
905:
906: # --------------------------- ask offload servers if user already has a session
907: sub find_existing_session {
908: my ($udom,$uname) = @_;
909: my $spareshash = &this_host_spares($udom);
910: if (ref($spareshash) eq 'HASH') {
911: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
912: foreach my $try_server (@{ $spareshash->{'primary'} }) {
913: return $try_server if (&has_user_session($try_server, $udom, $uname));
914: }
915: }
916: if (ref($spareshash->{'default'}) eq 'ARRAY') {
917: foreach my $try_server (@{ $spareshash->{'default'} }) {
918: return $try_server if (&has_user_session($try_server, $udom, $uname));
919: }
920: }
921: }
922: return;
923: }
924:
925: # -------------------------------- ask if server already has a session for user
926: sub has_user_session {
927: my ($lonid,$udom,$uname) = @_;
928: my $result = &reply(join(':','userhassession',
929: map {&escape($_)} ($udom,$uname)),$lonid);
930: return 1 if ($result eq 'ok');
931:
932: return 0;
933: }
934:
935: # --------- determine least loaded server in a user's domain which allows login
936:
937: sub choose_server {
938: my ($udom,$checkloginvia) = @_;
939: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
940: my %servers = &get_servers($udom);
941: my $lowest_load = 30000;
942: my ($login_host,$hostname,$portal_path,$isredirect);
943: foreach my $lonhost (keys(%servers)) {
944: my $loginvia;
945: if ($checkloginvia) {
946: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
947: if ($loginvia) {
948: my ($server,$path) = split(/:/,$loginvia);
949: ($login_host, $lowest_load) =
950: &compare_server_load($server, $login_host, $lowest_load);
951: if ($login_host eq $server) {
952: $portal_path = $path;
953: $isredirect = 1;
954: }
955: } else {
956: ($login_host, $lowest_load) =
957: &compare_server_load($lonhost, $login_host, $lowest_load);
958: if ($login_host eq $lonhost) {
959: $portal_path = '';
960: $isredirect = '';
961: }
962: }
963: } else {
964: ($login_host, $lowest_load) =
965: &compare_server_load($lonhost, $login_host, $lowest_load);
966: }
967: }
968: if ($login_host ne '') {
969: $hostname = &hostname($login_host);
970: }
971: return ($login_host,$hostname,$portal_path,$isredirect);
972: }
973:
974: # --------------------------------------------- Try to change a user's password
975:
976: sub changepass {
977: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
978: $currentpass = &escape($currentpass);
979: $newpass = &escape($newpass);
980: my $lonhost = $perlvar{'lonHostID'};
981: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
982: $server);
983: if (! $answer) {
984: &logthis("No reply on password change request to $server ".
985: "by $uname in domain $udom.");
986: } elsif ($answer =~ "^ok") {
987: &logthis("$uname in $udom successfully changed their password ".
988: "on $server.");
989: } elsif ($answer =~ "^pwchange_failure") {
990: &logthis("$uname in $udom was unable to change their password ".
991: "on $server. The action was blocked by either lcpasswd ".
992: "or pwchange");
993: } elsif ($answer =~ "^non_authorized") {
994: &logthis("$uname in $udom did not get their password correct when ".
995: "attempting to change it on $server.");
996: } elsif ($answer =~ "^auth_mode_error") {
997: &logthis("$uname in $udom attempted to change their password despite ".
998: "not being locally or internally authenticated on $server.");
999: } elsif ($answer =~ "^unknown_user") {
1000: &logthis("$uname in $udom attempted to change their password ".
1001: "on $server but were unable to because $server is not ".
1002: "their home server.");
1003: } elsif ($answer =~ "^refused") {
1004: &logthis("$server refused to change $uname in $udom password because ".
1005: "it was sent an unencrypted request to change the password.");
1006: } elsif ($answer =~ "invalid_client") {
1007: &logthis("$server refused to change $uname in $udom password because ".
1008: "it was a reset by e-mail originating from an invalid server.");
1009: }
1010: return $answer;
1011: }
1012:
1013: # ----------------------- Try to determine user's current authentication scheme
1014:
1015: sub queryauthenticate {
1016: my ($uname,$udom)=@_;
1017: my $uhome=&homeserver($uname,$udom);
1018: if (!$uhome) {
1019: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1020: return 'no_host';
1021: }
1022: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1023: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1024: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1025: }
1026: return $answer;
1027: }
1028:
1029: # --------- Try to authenticate user from domain's lib servers (first this one)
1030:
1031: sub authenticate {
1032: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1033: $upass=&escape($upass);
1034: $uname= &LONCAPA::clean_username($uname);
1035: my $uhome=&homeserver($uname,$udom,1);
1036: my $newhome;
1037: if ((!$uhome) || ($uhome eq 'no_host')) {
1038: # Maybe the machine was offline and only re-appeared again recently?
1039: &reconlonc();
1040: # One more
1041: $uhome=&homeserver($uname,$udom,1);
1042: if (($uhome eq 'no_host') && $checkdefauth) {
1043: if (defined(&domain($udom,'primary'))) {
1044: $newhome=&domain($udom,'primary');
1045: }
1046: if ($newhome ne '') {
1047: $uhome = $newhome;
1048: }
1049: }
1050: if ((!$uhome) || ($uhome eq 'no_host')) {
1051: &logthis("User $uname at $udom is unknown in authenticate");
1052: return 'no_host';
1053: }
1054: }
1055: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1056: if ($answer eq 'authorized') {
1057: if ($newhome) {
1058: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1059: return 'no_account_on_host';
1060: } else {
1061: &logthis("User $uname at $udom authorized by $uhome");
1062: return $uhome;
1063: }
1064: }
1065: if ($answer eq 'non_authorized') {
1066: &logthis("User $uname at $udom rejected by $uhome");
1067: return 'no_host';
1068: }
1069: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1070: return 'no_host';
1071: }
1072:
1073: sub can_host_session {
1074: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1075: my $canhost = 1;
1076: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1077: if (ref($remotesessions) eq 'HASH') {
1078: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1079: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1080: $canhost = 0;
1081: } else {
1082: $canhost = 1;
1083: }
1084: }
1085: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1086: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1087: $canhost = 1;
1088: } else {
1089: $canhost = 0;
1090: }
1091: }
1092: if ($canhost) {
1093: if ($remotesessions->{'version'} ne '') {
1094: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1095: if ($reqmajor ne '' && $reqminor ne '') {
1096: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1097: my $major = $1;
1098: my $minor = $2;
1099: if (($major < $reqmajor ) ||
1100: (($major == $reqmajor) && ($minor < $reqminor))) {
1101: $canhost = 0;
1102: }
1103: } else {
1104: $canhost = 0;
1105: }
1106: }
1107: }
1108: }
1109: }
1110: if ($canhost) {
1111: if (ref($hostedsessions) eq 'HASH') {
1112: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1113: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1114: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1115: if (($uint_dom ne '') &&
1116: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1117: $canhost = 0;
1118: } else {
1119: $canhost = 1;
1120: }
1121: }
1122: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1123: if (($uint_dom ne '') &&
1124: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1125: $canhost = 1;
1126: } else {
1127: $canhost = 0;
1128: }
1129: }
1130: }
1131: }
1132: return $canhost;
1133: }
1134:
1135: sub spare_can_host {
1136: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1137: my $canhost=1;
1138: my @intdoms;
1139: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1140: if (ref($internet_names) eq 'ARRAY') {
1141: @intdoms = @{$internet_names};
1142: }
1143: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1144: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1145: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1146: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1147: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1148: $canhost = &can_host_session($udom,$try_server,$remoterev,
1149: $remotesessions,
1150: $defdomdefaults{'hostedsessions'});
1151: }
1152: return $canhost;
1153: }
1154:
1155: sub this_host_spares {
1156: my ($dom) = @_;
1157: my ($dom_in_use,$lonhost_in_use,$result);
1158: my @hosts = ¤t_machine_ids();
1159: foreach my $lonhost (@hosts) {
1160: if (&host_domain($lonhost) eq $dom) {
1161: $dom_in_use = $dom;
1162: $lonhost_in_use = $lonhost;
1163: last;
1164: }
1165: }
1166: if ($dom_in_use ne '') {
1167: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1168: }
1169: if (ref($result) ne 'HASH') {
1170: $lonhost_in_use = $perlvar{'lonHostID'};
1171: $dom_in_use = &host_domain($lonhost_in_use);
1172: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1173: if (ref($result) ne 'HASH') {
1174: $result = \%spareid;
1175: }
1176: }
1177: return $result;
1178: }
1179:
1180: sub spares_for_offload {
1181: my ($dom_in_use,$lonhost_in_use) = @_;
1182: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1183: if (defined($cached)) {
1184: return $result;
1185: } else {
1186: my $cachetime = 60*60*24;
1187: my %domconfig =
1188: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1189: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1190: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1191: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1192: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1193: }
1194: }
1195: }
1196: }
1197: return;
1198: }
1199:
1200: sub get_lonbalancer_config {
1201: my ($servers) = @_;
1202: my ($currbalancer,$currtargets);
1203: if (ref($servers) eq 'HASH') {
1204: foreach my $server (keys(%{$servers})) {
1205: my %what = (
1206: spareid => 1,
1207: perlvar => 1,
1208: );
1209: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1210: if ($result eq 'ok') {
1211: if (ref($returnhash) eq 'HASH') {
1212: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1213: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1214: $currbalancer = $server;
1215: $currtargets = {};
1216: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1217: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1218: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1219: }
1220: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1221: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1222: }
1223: }
1224: last;
1225: }
1226: }
1227: }
1228: }
1229: }
1230: }
1231: return ($currbalancer,$currtargets);
1232: }
1233:
1234: sub check_loadbalancing {
1235: my ($uname,$udom) = @_;
1236: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1237: $offloadto,$otherserver);
1238: my $lonhost = $perlvar{'lonHostID'};
1239: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1240: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1241: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1242: my $serverhomedom = &host_domain($lonhost);
1243:
1244: my $cachetime = 60*60*24;
1245:
1246: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1247: $dom_in_use = $udom;
1248: $homeintdom = 1;
1249: } else {
1250: $dom_in_use = $serverhomedom;
1251: }
1252: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1253: unless (defined($cached)) {
1254: my %domconfig =
1255: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1256: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1257: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1258: }
1259: }
1260: if (ref($result) eq 'HASH') {
1261: my $currbalancer = $result->{'lonhost'};
1262: my $currtargets = $result->{'targets'};
1263: my $currrules = $result->{'rules'};
1264: if ($currbalancer ne '') {
1265: my @hosts = ¤t_machine_ids();
1266: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1267: $is_balancer = 1;
1268: }
1269: }
1270: if ($is_balancer) {
1271: if (ref($currrules) eq 'HASH') {
1272: if ($homeintdom) {
1273: if ($uname ne '') {
1274: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1275: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1276: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1277: $rule_in_effect = $currrules->{'_LC_author'};
1278: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1279: $rule_in_effect = $currrules->{'_LC_adv'}
1280: }
1281: }
1282: if ($rule_in_effect eq '') {
1283: my %userenv = &userenvironment($udom,$uname,'inststatus');
1284: if ($userenv{'inststatus'} ne '') {
1285: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1286: my ($othertitle,$usertypes,$types) =
1287: &Apache::loncommon::sorted_inst_types($udom);
1288: if (ref($types) eq 'ARRAY') {
1289: foreach my $type (@{$types}) {
1290: if (grep(/^\Q$type\E$/,@statuses)) {
1291: if (exists($currrules->{$type})) {
1292: $rule_in_effect = $currrules->{$type};
1293: }
1294: }
1295: }
1296: }
1297: } else {
1298: if (exists($currrules->{'default'})) {
1299: $rule_in_effect = $currrules->{'default'};
1300: }
1301: }
1302: }
1303: } else {
1304: if (exists($currrules->{'default'})) {
1305: $rule_in_effect = $currrules->{'default'};
1306: }
1307: }
1308: } else {
1309: if ($currrules->{'_LC_external'} ne '') {
1310: $rule_in_effect = $currrules->{'_LC_external'};
1311: }
1312: }
1313: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1314: $uname,$udom);
1315: }
1316: }
1317: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1318: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1319: unless (defined($cached)) {
1320: my %domconfig =
1321: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1322: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1323: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1324: }
1325: }
1326: if (ref($result) eq 'HASH') {
1327: my $currbalancer = $result->{'lonhost'};
1328: my $currtargets = $result->{'targets'};
1329: my $currrules = $result->{'rules'};
1330:
1331: if ($currbalancer eq $lonhost) {
1332: $is_balancer = 1;
1333: if (ref($currrules) eq 'HASH') {
1334: if ($currrules->{'_LC_internetdom'} ne '') {
1335: $rule_in_effect = $currrules->{'_LC_internetdom'};
1336: }
1337: }
1338: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1339: $uname,$udom);
1340: }
1341: } else {
1342: if ($perlvar{'lonBalancer'} eq 'yes') {
1343: $is_balancer = 1;
1344: $offloadto = &this_host_spares($dom_in_use);
1345: }
1346: }
1347: } else {
1348: if ($perlvar{'lonBalancer'} eq 'yes') {
1349: $is_balancer = 1;
1350: $offloadto = &this_host_spares($dom_in_use);
1351: }
1352: }
1353: my $lowest_load = 30000;
1354: if (ref($offloadto) eq 'HASH') {
1355: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1356: foreach my $try_server (@{$offloadto->{'primary'}}) {
1357: ($otherserver,$lowest_load) =
1358: &compare_server_load($try_server,$otherserver,$lowest_load);
1359: }
1360: }
1361: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1362:
1363: if (!$found_server) {
1364: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1365: foreach my $try_server (@{$offloadto->{'default'}}) {
1366: ($otherserver,$lowest_load) =
1367: &compare_server_load($try_server,$otherserver,$lowest_load);
1368: }
1369: }
1370: }
1371: } elsif (ref($offloadto) eq 'ARRAY') {
1372: if (@{$offloadto} == 1) {
1373: $otherserver = $offloadto->[0];
1374: } elsif (@{$offloadto} > 1) {
1375: foreach my $try_server (@{$offloadto}) {
1376: ($otherserver,$lowest_load) =
1377: &compare_server_load($try_server,$otherserver,$lowest_load);
1378: }
1379: }
1380: }
1381: return ($is_balancer,$otherserver);
1382: }
1383:
1384: sub get_loadbalancer_targets {
1385: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1386: my $offloadto;
1387: if ($rule_in_effect eq '') {
1388: $offloadto = $currtargets;
1389: } else {
1390: if ($rule_in_effect eq 'homeserver') {
1391: my $homeserver = &homeserver($uname,$udom);
1392: if ($homeserver ne 'no_host') {
1393: $offloadto = [$homeserver];
1394: }
1395: } elsif ($rule_in_effect eq 'externalbalancer') {
1396: my %domconfig =
1397: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1398: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1399: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1400: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1401: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1402: }
1403: }
1404: } else {
1405: my %servers = &dom_servers($udom);
1406: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1407: if (&hostname($remotebalancer) ne '') {
1408: $offloadto = [$remotebalancer];
1409: }
1410: }
1411: } elsif (&hostname($rule_in_effect) ne '') {
1412: $offloadto = [$rule_in_effect];
1413: }
1414: }
1415: return $offloadto;
1416: }
1417:
1418: sub internet_dom_servers {
1419: my ($dom) = @_;
1420: my (%uniqservers,%servers);
1421: my $primaryserver = &hostname(&domain($dom,'primary'));
1422: my @machinedoms = &machine_domains($primaryserver);
1423: foreach my $mdom (@machinedoms) {
1424: my %currservers = %servers;
1425: my %server = &get_servers($mdom);
1426: %servers = (%currservers,%server);
1427: }
1428: my %by_hostname;
1429: foreach my $id (keys(%servers)) {
1430: push(@{$by_hostname{$servers{$id}}},$id);
1431: }
1432: foreach my $hostname (sort(keys(%by_hostname))) {
1433: if (@{$by_hostname{$hostname}} > 1) {
1434: my $match = 0;
1435: foreach my $id (@{$by_hostname{$hostname}}) {
1436: if (&host_domain($id) eq $dom) {
1437: $uniqservers{$id} = $hostname;
1438: $match = 1;
1439: }
1440: }
1441: unless ($match) {
1442: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1443: }
1444: } else {
1445: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1446: }
1447: }
1448: return %uniqservers;
1449: }
1450:
1451: # ---------------------- Find the homebase for a user from domain's lib servers
1452:
1453: my %homecache;
1454: sub homeserver {
1455: my ($uname,$udom,$ignoreBadCache)=@_;
1456: my $index="$uname:$udom";
1457:
1458: if (exists($homecache{$index})) { return $homecache{$index}; }
1459:
1460: my %servers = &get_servers($udom,'library');
1461: foreach my $tryserver (keys(%servers)) {
1462: next if ($ignoreBadCache ne 'true' &&
1463: exists($badServerCache{$tryserver}));
1464:
1465: my $answer=reply("home:$udom:$uname",$tryserver);
1466: if ($answer eq 'found') {
1467: delete($badServerCache{$tryserver});
1468: return $homecache{$index}=$tryserver;
1469: } elsif ($answer eq 'no_host') {
1470: $badServerCache{$tryserver}=1;
1471: }
1472: }
1473: return 'no_host';
1474: }
1475:
1476: # ------------------------------------- Find the usernames behind a list of IDs
1477:
1478: sub idget {
1479: my ($udom,@ids)=@_;
1480: my %returnhash=();
1481:
1482: my %servers = &get_servers($udom,'library');
1483: foreach my $tryserver (keys(%servers)) {
1484: my $idlist=join('&',@ids);
1485: $idlist=~tr/A-Z/a-z/;
1486: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1487: my @answer=();
1488: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1489: @answer=split(/\&/,$reply);
1490: } ;
1491: my $i;
1492: for ($i=0;$i<=$#ids;$i++) {
1493: if ($answer[$i]) {
1494: $returnhash{$ids[$i]}=$answer[$i];
1495: }
1496: }
1497: }
1498: return %returnhash;
1499: }
1500:
1501: # ------------------------------------- Find the IDs behind a list of usernames
1502:
1503: sub idrget {
1504: my ($udom,@unames)=@_;
1505: my %returnhash=();
1506: foreach my $uname (@unames) {
1507: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1508: }
1509: return %returnhash;
1510: }
1511:
1512: # ------------------------------- Store away a list of names and associated IDs
1513:
1514: sub idput {
1515: my ($udom,%ids)=@_;
1516: my %servers=();
1517: foreach my $uname (keys(%ids)) {
1518: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1519: my $uhom=&homeserver($uname,$udom);
1520: if ($uhom ne 'no_host') {
1521: my $id=&escape($ids{$uname});
1522: $id=~tr/A-Z/a-z/;
1523: my $esc_unam=&escape($uname);
1524: if ($servers{$uhom}) {
1525: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1526: } else {
1527: $servers{$uhom}=$id.'='.$esc_unam;
1528: }
1529: }
1530: }
1531: foreach my $server (keys(%servers)) {
1532: &critical('idput:'.$udom.':'.$servers{$server},$server);
1533: }
1534: }
1535:
1536: # ------------------------------dump from db file owned by domainconfig user
1537: sub dump_dom {
1538: my ($namespace,$udom,$regexp,$range)=@_;
1539: if (!$udom) {
1540: $udom=$env{'user.domain'};
1541: }
1542: my %returnhash;
1543: if ($udom) {
1544: my $uname = &get_domainconfiguser($udom);
1545: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1546: }
1547: return %returnhash;
1548: }
1549:
1550: # ------------------------------------------ get items from domain db files
1551:
1552: sub get_dom {
1553: my ($namespace,$storearr,$udom,$uhome)=@_;
1554: my $items='';
1555: foreach my $item (@$storearr) {
1556: $items.=&escape($item).'&';
1557: }
1558: $items=~s/\&$//;
1559: if (!$udom) {
1560: $udom=$env{'user.domain'};
1561: if (defined(&domain($udom,'primary'))) {
1562: $uhome=&domain($udom,'primary');
1563: } else {
1564: undef($uhome);
1565: }
1566: } else {
1567: if (!$uhome) {
1568: if (defined(&domain($udom,'primary'))) {
1569: $uhome=&domain($udom,'primary');
1570: }
1571: }
1572: }
1573: if ($udom && $uhome && ($uhome ne 'no_host')) {
1574: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1575: my %returnhash;
1576: if ($rep eq '' || $rep =~ /^error: 2 /) {
1577: return %returnhash;
1578: }
1579: my @pairs=split(/\&/,$rep);
1580: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1581: return @pairs;
1582: }
1583: my $i=0;
1584: foreach my $item (@$storearr) {
1585: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1586: $i++;
1587: }
1588: return %returnhash;
1589: } else {
1590: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1591: }
1592: }
1593:
1594: # -------------------------------------------- put items in domain db files
1595:
1596: sub put_dom {
1597: my ($namespace,$storehash,$udom,$uhome)=@_;
1598: if (!$udom) {
1599: $udom=$env{'user.domain'};
1600: if (defined(&domain($udom,'primary'))) {
1601: $uhome=&domain($udom,'primary');
1602: } else {
1603: undef($uhome);
1604: }
1605: } else {
1606: if (!$uhome) {
1607: if (defined(&domain($udom,'primary'))) {
1608: $uhome=&domain($udom,'primary');
1609: }
1610: }
1611: }
1612: if ($udom && $uhome && ($uhome ne 'no_host')) {
1613: my $items='';
1614: foreach my $item (keys(%$storehash)) {
1615: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1616: }
1617: $items=~s/\&$//;
1618: return &reply("putdom:$udom:$namespace:$items",$uhome);
1619: } else {
1620: &logthis("put_dom failed - no homeserver and/or domain");
1621: }
1622: }
1623:
1624: # --------------------- newput for items in db file owned by domainconfig user
1625: sub newput_dom {
1626: my ($namespace,$storehash,$udom) = @_;
1627: my $result;
1628: if (!$udom) {
1629: $udom=$env{'user.domain'};
1630: }
1631: if ($udom) {
1632: my $uname = &get_domainconfiguser($udom);
1633: $result = &newput($namespace,$storehash,$udom,$uname);
1634: }
1635: return $result;
1636: }
1637:
1638: # --------------------- delete for items in db file owned by domainconfig user
1639: sub del_dom {
1640: my ($namespace,$storearr,$udom)=@_;
1641: if (ref($storearr) eq 'ARRAY') {
1642: if (!$udom) {
1643: $udom=$env{'user.domain'};
1644: }
1645: if ($udom) {
1646: my $uname = &get_domainconfiguser($udom);
1647: return &del($namespace,$storearr,$udom,$uname);
1648: }
1649: }
1650: }
1651:
1652: # ----------------------------------construct domainconfig user for a domain
1653: sub get_domainconfiguser {
1654: my ($udom) = @_;
1655: return $udom.'-domainconfig';
1656: }
1657:
1658: sub retrieve_inst_usertypes {
1659: my ($udom) = @_;
1660: my (%returnhash,@order);
1661: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1662: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1663: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1664: %returnhash = %{$domdefs{'inststatustypes'}};
1665: @order = @{$domdefs{'inststatusorder'}};
1666: } else {
1667: if (defined(&domain($udom,'primary'))) {
1668: my $uhome=&domain($udom,'primary');
1669: my $rep=&reply("inst_usertypes:$udom",$uhome);
1670: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1671: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1672: return (\%returnhash,\@order);
1673: }
1674: my ($hashitems,$orderitems) = split(/:/,$rep);
1675: my @pairs=split(/\&/,$hashitems);
1676: foreach my $item (@pairs) {
1677: my ($key,$value)=split(/=/,$item,2);
1678: $key = &unescape($key);
1679: next if ($key =~ /^error: 2 /);
1680: $returnhash{$key}=&thaw_unescape($value);
1681: }
1682: my @esc_order = split(/\&/,$orderitems);
1683: foreach my $item (@esc_order) {
1684: push(@order,&unescape($item));
1685: }
1686: } else {
1687: &logthis("get_dom failed - no primary domain server for $udom");
1688: }
1689: }
1690: return (\%returnhash,\@order);
1691: }
1692:
1693: sub is_domainimage {
1694: my ($url) = @_;
1695: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1696: if (&domain($1) ne '') {
1697: return '1';
1698: }
1699: }
1700: return;
1701: }
1702:
1703: sub inst_directory_query {
1704: my ($srch) = @_;
1705: my $udom = $srch->{'srchdomain'};
1706: my %results;
1707: my $homeserver = &domain($udom,'primary');
1708: my $outcome;
1709: if ($homeserver ne '') {
1710: my $queryid=&reply("querysend:instdirsearch:".
1711: &escape($srch->{'srchby'}).':'.
1712: &escape($srch->{'srchterm'}).':'.
1713: &escape($srch->{'srchtype'}),$homeserver);
1714: my $host=&hostname($homeserver);
1715: if ($queryid !~/^\Q$host\E\_/) {
1716: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1717: return;
1718: }
1719: my $response = &get_query_reply($queryid);
1720: my $maxtries = 5;
1721: my $tries = 1;
1722: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1723: $response = &get_query_reply($queryid);
1724: $tries ++;
1725: }
1726:
1727: if (!&error($response) && $response ne 'refused') {
1728: if ($response eq 'unavailable') {
1729: $outcome = $response;
1730: } else {
1731: $outcome = 'ok';
1732: my @matches = split(/\n/,$response);
1733: foreach my $match (@matches) {
1734: my ($key,$value) = split(/=/,$match);
1735: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1736: }
1737: }
1738: }
1739: }
1740: return ($outcome,%results);
1741: }
1742:
1743: sub usersearch {
1744: my ($srch) = @_;
1745: my $dom = $srch->{'srchdomain'};
1746: my %results;
1747: my %libserv = &all_library();
1748: my $query = 'usersearch';
1749: foreach my $tryserver (keys(%libserv)) {
1750: if (&host_domain($tryserver) eq $dom) {
1751: my $host=&hostname($tryserver);
1752: my $queryid=
1753: &reply("querysend:".&escape($query).':'.
1754: &escape($srch->{'srchby'}).':'.
1755: &escape($srch->{'srchtype'}).':'.
1756: &escape($srch->{'srchterm'}),$tryserver);
1757: if ($queryid !~/^\Q$host\E\_/) {
1758: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1759: next;
1760: }
1761: my $reply = &get_query_reply($queryid);
1762: my $maxtries = 1;
1763: my $tries = 1;
1764: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1765: $reply = &get_query_reply($queryid);
1766: $tries ++;
1767: }
1768: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1769: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1770: } else {
1771: my @matches;
1772: if ($reply =~ /\n/) {
1773: @matches = split(/\n/,$reply);
1774: } else {
1775: @matches = split(/\&/,$reply);
1776: }
1777: foreach my $match (@matches) {
1778: my ($uname,$udom,%userhash);
1779: foreach my $entry (split(/:/,$match)) {
1780: my ($key,$value) =
1781: map {&unescape($_);} split(/=/,$entry);
1782: $userhash{$key} = $value;
1783: if ($key eq 'username') {
1784: $uname = $value;
1785: } elsif ($key eq 'domain') {
1786: $udom = $value;
1787: }
1788: }
1789: $results{$uname.':'.$udom} = \%userhash;
1790: }
1791: }
1792: }
1793: }
1794: return %results;
1795: }
1796:
1797: sub get_instuser {
1798: my ($udom,$uname,$id) = @_;
1799: my $homeserver = &domain($udom,'primary');
1800: my ($outcome,%results);
1801: if ($homeserver ne '') {
1802: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1803: &escape($id).':'.&escape($udom),$homeserver);
1804: my $host=&hostname($homeserver);
1805: if ($queryid !~/^\Q$host\E\_/) {
1806: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1807: return;
1808: }
1809: my $response = &get_query_reply($queryid);
1810: my $maxtries = 5;
1811: my $tries = 1;
1812: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1813: $response = &get_query_reply($queryid);
1814: $tries ++;
1815: }
1816: if (!&error($response) && $response ne 'refused') {
1817: if ($response eq 'unavailable') {
1818: $outcome = $response;
1819: } else {
1820: $outcome = 'ok';
1821: my @matches = split(/\n/,$response);
1822: foreach my $match (@matches) {
1823: my ($key,$value) = split(/=/,$match);
1824: $results{&unescape($key)} = &thaw_unescape($value);
1825: }
1826: }
1827: }
1828: }
1829: my %userinfo;
1830: if (ref($results{$uname}) eq 'HASH') {
1831: %userinfo = %{$results{$uname}};
1832: }
1833: return ($outcome,%userinfo);
1834: }
1835:
1836: sub inst_rulecheck {
1837: my ($udom,$uname,$id,$item,$rules) = @_;
1838: my %returnhash;
1839: if ($udom ne '') {
1840: if (ref($rules) eq 'ARRAY') {
1841: @{$rules} = map {&escape($_);} (@{$rules});
1842: my $rulestr = join(':',@{$rules});
1843: my $homeserver=&domain($udom,'primary');
1844: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1845: my $response;
1846: if ($item eq 'username') {
1847: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1848: ':'.&escape($uname).':'.$rulestr,
1849: $homeserver));
1850: } elsif ($item eq 'id') {
1851: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1852: ':'.&escape($id).':'.$rulestr,
1853: $homeserver));
1854: } elsif ($item eq 'selfcreate') {
1855: $response=&unescape(&reply('instselfcreatecheck:'.
1856: &escape($udom).':'.&escape($uname).
1857: ':'.$rulestr,$homeserver));
1858: }
1859: if ($response ne 'refused') {
1860: my @pairs=split(/\&/,$response);
1861: foreach my $item (@pairs) {
1862: my ($key,$value)=split(/=/,$item,2);
1863: $key = &unescape($key);
1864: next if ($key =~ /^error: 2 /);
1865: $returnhash{$key}=&thaw_unescape($value);
1866: }
1867: }
1868: }
1869: }
1870: }
1871: return %returnhash;
1872: }
1873:
1874: sub inst_userrules {
1875: my ($udom,$check) = @_;
1876: my (%ruleshash,@ruleorder);
1877: if ($udom ne '') {
1878: my $homeserver=&domain($udom,'primary');
1879: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1880: my $response;
1881: if ($check eq 'id') {
1882: $response=&reply('instidrules:'.&escape($udom),
1883: $homeserver);
1884: } elsif ($check eq 'email') {
1885: $response=&reply('instemailrules:'.&escape($udom),
1886: $homeserver);
1887: } else {
1888: $response=&reply('instuserrules:'.&escape($udom),
1889: $homeserver);
1890: }
1891: if (($response ne 'refused') && ($response ne 'error') &&
1892: ($response ne 'unknown_cmd') &&
1893: ($response ne 'no_such_host')) {
1894: my ($hashitems,$orderitems) = split(/:/,$response);
1895: my @pairs=split(/\&/,$hashitems);
1896: foreach my $item (@pairs) {
1897: my ($key,$value)=split(/=/,$item,2);
1898: $key = &unescape($key);
1899: next if ($key =~ /^error: 2 /);
1900: $ruleshash{$key}=&thaw_unescape($value);
1901: }
1902: my @esc_order = split(/\&/,$orderitems);
1903: foreach my $item (@esc_order) {
1904: push(@ruleorder,&unescape($item));
1905: }
1906: }
1907: }
1908: }
1909: return (\%ruleshash,\@ruleorder);
1910: }
1911:
1912: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1913:
1914: sub get_domain_defaults {
1915: my ($domain) = @_;
1916: my $cachetime = 60*60*24;
1917: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1918: if (defined($cached)) {
1919: if (ref($result) eq 'HASH') {
1920: return %{$result};
1921: }
1922: }
1923: my %domdefaults;
1924: my %domconfig =
1925: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1926: 'requestcourses','inststatus',
1927: 'coursedefaults','usersessions'],$domain);
1928: if (ref($domconfig{'defaults'}) eq 'HASH') {
1929: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1930: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1931: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1932: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1933: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1934: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1935: } else {
1936: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1937: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1938: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1939: }
1940: if (ref($domconfig{'quotas'}) eq 'HASH') {
1941: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1942: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1943: } else {
1944: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1945: }
1946: my @usertools = ('aboutme','blog','portfolio');
1947: foreach my $item (@usertools) {
1948: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1949: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1950: }
1951: }
1952: }
1953: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1954: foreach my $item ('official','unofficial','community') {
1955: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1956: }
1957: }
1958: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1959: foreach my $item ('inststatustypes','inststatusorder') {
1960: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1961: }
1962: }
1963: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1964: foreach my $item ('canuse_pdfforms') {
1965: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1966: }
1967: }
1968: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1969: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1970: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1971: }
1972: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1973: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1974: }
1975: }
1976: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1977: $cachetime);
1978: return %domdefaults;
1979: }
1980:
1981: # --------------------------------------------------- Assign a key to a student
1982:
1983: sub assign_access_key {
1984: #
1985: # a valid key looks like uname:udom#comments
1986: # comments are being appended
1987: #
1988: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1989: $kdom=
1990: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1991: $knum=
1992: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1993: $cdom=
1994: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1995: $cnum=
1996: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1997: $udom=$env{'user.name'} unless (defined($udom));
1998: $uname=$env{'user.domain'} unless (defined($uname));
1999: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2000: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2001: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2002: # assigned to this person
2003: # - this should not happen,
2004: # unless something went wrong
2005: # the first time around
2006: # ready to assign
2007: $logentry=$1.'; '.$logentry;
2008: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2009: $kdom,$knum) eq 'ok') {
2010: # key now belongs to user
2011: my $envkey='key.'.$cdom.'_'.$cnum;
2012: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2013: &appenv({'environment.'.$envkey => $ckey});
2014: return 'ok';
2015: } else {
2016: return
2017: 'error: Count not permanently assign key, will need to be re-entered later.';
2018: }
2019: } else {
2020: return 'error: Could not assign key, try again later.';
2021: }
2022: } elsif (!$existing{$ckey}) {
2023: # the key does not exist
2024: return 'error: The key does not exist';
2025: } else {
2026: # the key is somebody else's
2027: return 'error: The key is already in use';
2028: }
2029: }
2030:
2031: # ------------------------------------------ put an additional comment on a key
2032:
2033: sub comment_access_key {
2034: #
2035: # a valid key looks like uname:udom#comments
2036: # comments are being appended
2037: #
2038: my ($ckey,$cdom,$cnum,$logentry)=@_;
2039: $cdom=
2040: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2041: $cnum=
2042: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2043: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2044: if ($existing{$ckey}) {
2045: $existing{$ckey}.='; '.$logentry;
2046: # ready to assign
2047: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2048: $cdom,$cnum) eq 'ok') {
2049: return 'ok';
2050: } else {
2051: return 'error: Count not store comment.';
2052: }
2053: } else {
2054: # the key does not exist
2055: return 'error: The key does not exist';
2056: }
2057: }
2058:
2059: # ------------------------------------------------------ Generate a set of keys
2060:
2061: sub generate_access_keys {
2062: my ($number,$cdom,$cnum,$logentry)=@_;
2063: $cdom=
2064: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2065: $cnum=
2066: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2067: unless (&allowed('mky',$cdom)) { return 0; }
2068: unless (($cdom) && ($cnum)) { return 0; }
2069: if ($number>10000) { return 0; }
2070: sleep(2); # make sure don't get same seed twice
2071: srand(time()^($$+($$<<15))); # from "Programming Perl"
2072: my $total=0;
2073: for (my $i=1;$i<=$number;$i++) {
2074: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2075: sprintf("%lx",int(100000*rand)).'-'.
2076: sprintf("%lx",int(100000*rand));
2077: $newkey=~s/1/g/g; # folks mix up 1 and l
2078: $newkey=~s/0/h/g; # and also 0 and O
2079: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2080: if ($existing{$newkey}) {
2081: $i--;
2082: } else {
2083: if (&put('accesskeys',
2084: { $newkey => '# generated '.localtime().
2085: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2086: '; '.$logentry },
2087: $cdom,$cnum) eq 'ok') {
2088: $total++;
2089: }
2090: }
2091: }
2092: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2093: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2094: return $total;
2095: }
2096:
2097: # ------------------------------------------------------- Validate an accesskey
2098:
2099: sub validate_access_key {
2100: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2101: $cdom=
2102: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2103: $cnum=
2104: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2105: $udom=$env{'user.domain'} unless (defined($udom));
2106: $uname=$env{'user.name'} unless (defined($uname));
2107: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2108: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2109: }
2110:
2111: # ------------------------------------- Find the section of student in a course
2112: sub devalidate_getsection_cache {
2113: my ($udom,$unam,$courseid)=@_;
2114: my $hashid="$udom:$unam:$courseid";
2115: &devalidate_cache_new('getsection',$hashid);
2116: }
2117:
2118: sub courseid_to_courseurl {
2119: my ($courseid) = @_;
2120: #already url style courseid
2121: return $courseid if ($courseid =~ m{^/});
2122:
2123: if (exists($env{'course.'.$courseid.'.num'})) {
2124: my $cnum = $env{'course.'.$courseid.'.num'};
2125: my $cdom = $env{'course.'.$courseid.'.domain'};
2126: return "/$cdom/$cnum";
2127: }
2128:
2129: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2130: if (exists($courseinfo{'num'})) {
2131: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2132: }
2133:
2134: return undef;
2135: }
2136:
2137: sub getsection {
2138: my ($udom,$unam,$courseid)=@_;
2139: my $cachetime=1800;
2140:
2141: my $hashid="$udom:$unam:$courseid";
2142: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2143: if (defined($cached)) { return $result; }
2144:
2145: my %Pending;
2146: my %Expired;
2147: #
2148: # Each role can either have not started yet (pending), be active,
2149: # or have expired.
2150: #
2151: # If there is an active role, we are done.
2152: #
2153: # If there is more than one role which has not started yet,
2154: # choose the one which will start sooner
2155: # If there is one role which has not started yet, return it.
2156: #
2157: # If there is more than one expired role, choose the one which ended last.
2158: # If there is a role which has expired, return it.
2159: #
2160: $courseid = &courseid_to_courseurl($courseid);
2161: my $extra = &freeze_escape({'skipcheck' => 1});
2162: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
2163: foreach my $key (keys(%roleshash)) {
2164: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2165: my $section=$1;
2166: if ($key eq $courseid.'_st') { $section=''; }
2167: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2168: my $now=time;
2169: if (defined($end) && $end && ($now > $end)) {
2170: $Expired{$end}=$section;
2171: next;
2172: }
2173: if (defined($start) && $start && ($now < $start)) {
2174: $Pending{$start}=$section;
2175: next;
2176: }
2177: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2178: }
2179: #
2180: # Presumedly there will be few matching roles from the above
2181: # loop and the sorting time will be negligible.
2182: if (scalar(keys(%Pending))) {
2183: my ($time) = sort {$a <=> $b} keys(%Pending);
2184: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2185: }
2186: if (scalar(keys(%Expired))) {
2187: my @sorted = sort {$a <=> $b} keys(%Expired);
2188: my $time = pop(@sorted);
2189: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2190: }
2191: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2192: }
2193:
2194: sub save_cache {
2195: &purge_remembered();
2196: #&Apache::loncommon::validate_page();
2197: undef(%env);
2198: undef($env_loaded);
2199: }
2200:
2201: my $to_remember=-1;
2202: my %remembered;
2203: my %accessed;
2204: my $kicks=0;
2205: my $hits=0;
2206: sub make_key {
2207: my ($name,$id) = @_;
2208: if (length($id) > 65
2209: && length(&escape($id)) > 200) {
2210: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2211: }
2212: return &escape($name.':'.$id);
2213: }
2214:
2215: sub devalidate_cache_new {
2216: my ($name,$id,$debug) = @_;
2217: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2218: $id=&make_key($name,$id);
2219: $memcache->delete($id);
2220: delete($remembered{$id});
2221: delete($accessed{$id});
2222: }
2223:
2224: sub is_cached_new {
2225: my ($name,$id,$debug) = @_;
2226: $id=&make_key($name,$id);
2227: if (exists($remembered{$id})) {
2228: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2229: $accessed{$id}=[&gettimeofday()];
2230: $hits++;
2231: return ($remembered{$id},1);
2232: }
2233: my $value = $memcache->get($id);
2234: if (!(defined($value))) {
2235: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2236: return (undef,undef);
2237: }
2238: if ($value eq '__undef__') {
2239: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2240: $value=undef;
2241: }
2242: &make_room($id,$value,$debug);
2243: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2244: return ($value,1);
2245: }
2246:
2247: sub do_cache_new {
2248: my ($name,$id,$value,$time,$debug) = @_;
2249: $id=&make_key($name,$id);
2250: my $setvalue=$value;
2251: if (!defined($setvalue)) {
2252: $setvalue='__undef__';
2253: }
2254: if (!defined($time) ) {
2255: $time=600;
2256: }
2257: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2258: my $result = $memcache->set($id,$setvalue,$time);
2259: if (! $result) {
2260: &logthis("caching of id -> $id failed");
2261: $memcache->disconnect_all();
2262: }
2263: # need to make a copy of $value
2264: &make_room($id,$value,$debug);
2265: return $value;
2266: }
2267:
2268: sub make_room {
2269: my ($id,$value,$debug)=@_;
2270:
2271: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2272: : $value;
2273: if ($to_remember<0) { return; }
2274: $accessed{$id}=[&gettimeofday()];
2275: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2276: my $to_kick;
2277: my $max_time=0;
2278: foreach my $other (keys(%accessed)) {
2279: if (&tv_interval($accessed{$other}) > $max_time) {
2280: $to_kick=$other;
2281: $max_time=&tv_interval($accessed{$other});
2282: }
2283: }
2284: delete($remembered{$to_kick});
2285: delete($accessed{$to_kick});
2286: $kicks++;
2287: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2288: return;
2289: }
2290:
2291: sub purge_remembered {
2292: #&logthis("Tossing ".scalar(keys(%remembered)));
2293: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2294: undef(%remembered);
2295: undef(%accessed);
2296: }
2297: # ------------------------------------- Read an entry from a user's environment
2298:
2299: sub userenvironment {
2300: my ($udom,$unam,@what)=@_;
2301: my $items;
2302: foreach my $item (@what) {
2303: $items.=&escape($item).'&';
2304: }
2305: $items=~s/\&$//;
2306: my %returnhash=();
2307: my $uhome = &homeserver($unam,$udom);
2308: unless ($uhome eq 'no_host') {
2309: my @answer=split(/\&/,
2310: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2311: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2312: return %returnhash;
2313: }
2314: my $i;
2315: for ($i=0;$i<=$#what;$i++) {
2316: $returnhash{$what[$i]}=&unescape($answer[$i]);
2317: }
2318: }
2319: return %returnhash;
2320: }
2321:
2322: # ---------------------------------------------------------- Get a studentphoto
2323: sub studentphoto {
2324: my ($udom,$unam,$ext) = @_;
2325: my $home=&Apache::lonnet::homeserver($unam,$udom);
2326: if (defined($env{'request.course.id'})) {
2327: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2328: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2329: return(&retrievestudentphoto($udom,$unam,$ext));
2330: } else {
2331: my ($result,$perm_reqd)=
2332: &Apache::lonnet::auto_photo_permission($unam,$udom);
2333: if ($result eq 'ok') {
2334: if (!($perm_reqd eq 'yes')) {
2335: return(&retrievestudentphoto($udom,$unam,$ext));
2336: }
2337: }
2338: }
2339: }
2340: } else {
2341: my ($result,$perm_reqd) =
2342: &Apache::lonnet::auto_photo_permission($unam,$udom);
2343: if ($result eq 'ok') {
2344: if (!($perm_reqd eq 'yes')) {
2345: return(&retrievestudentphoto($udom,$unam,$ext));
2346: }
2347: }
2348: }
2349: return '/adm/lonKaputt/lonlogo_broken.gif';
2350: }
2351:
2352: sub retrievestudentphoto {
2353: my ($udom,$unam,$ext,$type) = @_;
2354: my $home=&Apache::lonnet::homeserver($unam,$udom);
2355: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2356: if ($ret eq 'ok') {
2357: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2358: if ($type eq 'thumbnail') {
2359: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2360: }
2361: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2362: return $tokenurl;
2363: } else {
2364: if ($type eq 'thumbnail') {
2365: return '/adm/lonKaputt/genericstudent_tn.gif';
2366: } else {
2367: return '/adm/lonKaputt/lonlogo_broken.gif';
2368: }
2369: }
2370: }
2371:
2372: # -------------------------------------------------------------------- New chat
2373:
2374: sub chatsend {
2375: my ($newentry,$anon,$group)=@_;
2376: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2377: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2378: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2379: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2380: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2381: &escape($newentry)).':'.$group,$chome);
2382: }
2383:
2384: # ------------------------------------------ Find current version of a resource
2385:
2386: sub getversion {
2387: my $fname=&clutter(shift);
2388: unless ($fname=~/^\/res\//) { return -1; }
2389: return ¤tversion(&filelocation('',$fname));
2390: }
2391:
2392: sub currentversion {
2393: my $fname=shift;
2394: my $author=$fname;
2395: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2396: my ($udom,$uname)=split(/\//,$author);
2397: my $home=&homeserver($uname,$udom);
2398: if ($home eq 'no_host') {
2399: return -1;
2400: }
2401: my $answer=&reply("currentversion:$fname",$home);
2402: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2403: return -1;
2404: }
2405: return $answer;
2406: }
2407:
2408: #
2409: # Return special version number of resource if set by override, empty otherwise
2410: #
2411: sub usedversion {
2412: my $fname=shift;
2413: unless ($fname) { $fname=$env{'request.uri'}; }
2414: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2415: if ($urlversion) { return $urlversion; }
2416: return '';
2417: }
2418:
2419: # ----------------------------- Subscribe to a resource, return URL if possible
2420:
2421: sub subscribe {
2422: my $fname=shift;
2423: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2424: $fname=~s/[\n\r]//g;
2425: my $author=$fname;
2426: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2427: my ($udom,$uname)=split(/\//,$author);
2428: my $home=homeserver($uname,$udom);
2429: if ($home eq 'no_host') {
2430: return 'not_found';
2431: }
2432: my $answer=reply("sub:$fname",$home);
2433: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2434: $answer.=' by '.$home;
2435: }
2436: return $answer;
2437: }
2438:
2439: # -------------------------------------------------------------- Replicate file
2440:
2441: sub repcopy {
2442: my $filename=shift;
2443: $filename=~s/\/+/\//g;
2444: my $londocroot = $perlvar{'lonDocRoot'};
2445: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2446: if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
2447: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2448: $filename=~m{^/*(uploaded|editupload)/}) {
2449: return &repcopy_userfile($filename);
2450: }
2451: $filename=~s/[\n\r]//g;
2452: my $transname="$filename.in.transfer";
2453: # FIXME: this should flock
2454: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2455: my $remoteurl=subscribe($filename);
2456: if ($remoteurl =~ /^con_lost by/) {
2457: &logthis("Subscribe returned $remoteurl: $filename");
2458: return 'unavailable';
2459: } elsif ($remoteurl eq 'not_found') {
2460: #&logthis("Subscribe returned not_found: $filename");
2461: return 'not_found';
2462: } elsif ($remoteurl =~ /^rejected by/) {
2463: &logthis("Subscribe returned $remoteurl: $filename");
2464: return 'forbidden';
2465: } elsif ($remoteurl eq 'directory') {
2466: return 'ok';
2467: } else {
2468: my $author=$filename;
2469: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2470: my ($udom,$uname)=split(/\//,$author);
2471: my $home=homeserver($uname,$udom);
2472: unless ($home eq $perlvar{'lonHostID'}) {
2473: my @parts=split(/\//,$filename);
2474: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2475: if ($path ne "$londocroot/res") {
2476: &logthis("Malconfiguration for replication: $filename");
2477: return 'bad_request';
2478: }
2479: my $count;
2480: for ($count=5;$count<$#parts;$count++) {
2481: $path.="/$parts[$count]";
2482: if ((-e $path)!=1) {
2483: mkdir($path,0777);
2484: }
2485: }
2486: my $ua=new LWP::UserAgent;
2487: my $request=new HTTP::Request('GET',"$remoteurl");
2488: my $response=$ua->request($request,$transname);
2489: if ($response->is_error()) {
2490: unlink($transname);
2491: my $message=$response->status_line;
2492: &logthis("<font color=\"blue\">WARNING:"
2493: ." LWP get: $message: $filename</font>");
2494: return 'unavailable';
2495: } else {
2496: if ($remoteurl!~/\.meta$/) {
2497: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2498: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2499: if ($mresponse->is_error()) {
2500: unlink($filename.'.meta');
2501: &logthis(
2502: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2503: }
2504: }
2505: rename($transname,$filename);
2506: return 'ok';
2507: }
2508: }
2509: }
2510: }
2511:
2512: # ------------------------------------------------ Get server side include body
2513: sub ssi_body {
2514: my ($filelink,%form)=@_;
2515: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2516: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2517: }
2518: my $output='';
2519: my $response;
2520: if ($filelink=~/^https?\:/) {
2521: ($output,$response)=&externalssi($filelink);
2522: } else {
2523: $filelink .= $filelink=~/\?/ ? '&' : '?';
2524: $filelink .= 'inhibitmenu=yes';
2525: ($output,$response)=&ssi($filelink,%form);
2526: }
2527: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2528: $output=~s/^.*?\<body[^\>]*\>//si;
2529: $output=~s/\<\/body\s*\>.*?$//si;
2530: if (wantarray) {
2531: return ($output, $response);
2532: } else {
2533: return $output;
2534: }
2535: }
2536:
2537: # --------------------------------------------------------- Server Side Include
2538:
2539: sub absolute_url {
2540: my ($host_name) = @_;
2541: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2542: if ($host_name eq '') {
2543: $host_name = $ENV{'SERVER_NAME'};
2544: }
2545: return $protocol.$host_name;
2546: }
2547:
2548: #
2549: # Server side include.
2550: # Parameters:
2551: # fn Possibly encrypted resource name/id.
2552: # form Hash that describes how the rendering should be done
2553: # and other things.
2554: # Returns:
2555: # Scalar context: The content of the response.
2556: # Array context: 2 element list of the content and the full response object.
2557: #
2558: sub ssi {
2559:
2560: my ($fn,%form)=@_;
2561: my $ua=new LWP::UserAgent;
2562: my $request;
2563:
2564: $form{'no_update_last_known'}=1;
2565: &Apache::lonenc::check_encrypt(\$fn);
2566: if (%form) {
2567: $request=new HTTP::Request('POST',&absolute_url().$fn);
2568: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2569: } else {
2570: $request=new HTTP::Request('GET',&absolute_url().$fn);
2571: }
2572:
2573: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2574: my $response=$ua->request($request);
2575:
2576: if (wantarray) {
2577: return ($response->content, $response);
2578: } else {
2579: return $response->content;
2580: }
2581: }
2582:
2583: sub externalssi {
2584: my ($url)=@_;
2585: my $ua=new LWP::UserAgent;
2586: my $request=new HTTP::Request('GET',$url);
2587: my $response=$ua->request($request);
2588: if (wantarray) {
2589: return ($response->content, $response);
2590: } else {
2591: return $response->content;
2592: }
2593: }
2594:
2595: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2596:
2597: sub allowuploaded {
2598: my ($srcurl,$url)=@_;
2599: $url=&clutter(&declutter($url));
2600: my $dir=$url;
2601: $dir=~s/\/[^\/]+$//;
2602: my %httpref=();
2603: my $httpurl=&hreflocation('',$url);
2604: $httpref{'httpref.'.$httpurl}=$srcurl;
2605: &Apache::lonnet::appenv(\%httpref);
2606: }
2607:
2608: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2609: # input: action, courseID, current domain, intended
2610: # path to file, source of file, instruction to parse file for objects,
2611: # ref to hash for embedded objects,
2612: # ref to hash for codebase of java objects.
2613: # reference to scalar to accommodate mime type determined
2614: # from File::MMagic if $parser = parse.
2615: #
2616: # output: url to file (if action was uploaddoc),
2617: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2618: #
2619: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2620: # course.
2621: #
2622: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2623: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2624: # course's home server.
2625: #
2626: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2627: # be copied from $source (current location) to
2628: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2629: # and will then be copied to
2630: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2631: # course's home server.
2632: #
2633: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2634: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2635: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2636: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2637: # in course's home server.
2638: #
2639:
2640: sub process_coursefile {
2641: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2642: $mimetype)=@_;
2643: my $fetchresult;
2644: my $home=&homeserver($docuname,$docudom);
2645: if ($action eq 'propagate') {
2646: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2647: $home);
2648: } else {
2649: my $fpath = '';
2650: my $fname = $file;
2651: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2652: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2653: my $filepath = &build_filepath($fpath);
2654: if ($action eq 'copy') {
2655: if ($source eq '') {
2656: $fetchresult = 'no source file';
2657: return $fetchresult;
2658: } else {
2659: my $destination = $filepath.'/'.$fname;
2660: rename($source,$destination);
2661: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2662: $home);
2663: }
2664: } elsif ($action eq 'uploaddoc') {
2665: open(my $fh,'>'.$filepath.'/'.$fname);
2666: print $fh $env{'form.'.$source};
2667: close($fh);
2668: if ($parser eq 'parse') {
2669: my $mm = new File::MMagic;
2670: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2671: if ($type eq 'text/html') {
2672: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2673: unless ($parse_result eq 'ok') {
2674: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2675: }
2676: }
2677: if (ref($mimetype)) {
2678: $$mimetype = $type;
2679: }
2680: }
2681: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2682: $home);
2683: if ($fetchresult eq 'ok') {
2684: return '/uploaded/'.$fpath.'/'.$fname;
2685: } else {
2686: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2687: ' to host '.$home.': '.$fetchresult);
2688: return '/adm/notfound.html';
2689: }
2690: }
2691: }
2692: unless ( $fetchresult eq 'ok') {
2693: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2694: ' to host '.$home.': '.$fetchresult);
2695: }
2696: return $fetchresult;
2697: }
2698:
2699: sub build_filepath {
2700: my ($fpath) = @_;
2701: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2702: unless ($fpath eq '') {
2703: my @parts=split('/',$fpath);
2704: foreach my $part (@parts) {
2705: $filepath.= '/'.$part;
2706: if ((-e $filepath)!=1) {
2707: mkdir($filepath,0777);
2708: }
2709: }
2710: }
2711: return $filepath;
2712: }
2713:
2714: sub store_edited_file {
2715: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2716: my $file = $primary_url;
2717: $file =~ s#^/uploaded/$docudom/$docuname/##;
2718: my $fpath = '';
2719: my $fname = $file;
2720: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2721: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2722: my $filepath = &build_filepath($fpath);
2723: open(my $fh,'>'.$filepath.'/'.$fname);
2724: print $fh $content;
2725: close($fh);
2726: my $home=&homeserver($docuname,$docudom);
2727: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2728: $home);
2729: if ($$fetchresult eq 'ok') {
2730: return '/uploaded/'.$fpath.'/'.$fname;
2731: } else {
2732: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2733: ' to host '.$home.': '.$$fetchresult);
2734: return '/adm/notfound.html';
2735: }
2736: }
2737:
2738: sub clean_filename {
2739: my ($fname,$args)=@_;
2740: # Replace Windows backslashes by forward slashes
2741: $fname=~s/\\/\//g;
2742: if (!$args->{'keep_path'}) {
2743: # Get rid of everything but the actual filename
2744: $fname=~s/^.*\/([^\/]+)$/$1/;
2745: }
2746: # Replace spaces by underscores
2747: $fname=~s/\s+/\_/g;
2748: # Replace all other weird characters by nothing
2749: $fname=~s{[^/\w\.\-]}{}g;
2750: # Replace all .\d. sequences with _\d. so they no longer look like version
2751: # numbers
2752: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2753: return $fname;
2754: }
2755: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2756: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2757: # image with the same aspect ratio as the original, but with dimensions which do
2758: # not exceed $resizewidth and $resizeheight.
2759:
2760: sub resizeImage {
2761: my ($img_path,$resizewidth,$resizeheight) = @_;
2762: my $ima = Image::Magick->new;
2763: my $resized;
2764: if (-e $img_path) {
2765: $ima->Read($img_path);
2766: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2767: my $width = $ima->Get('width');
2768: my $height = $ima->Get('height');
2769: if ($width > $resizewidth) {
2770: my $factor = $width/$resizewidth;
2771: my $newheight = $height/$factor;
2772: $ima->Scale(width=>$resizewidth,height=>$newheight);
2773: $resized = 1;
2774: }
2775: }
2776: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2777: my $width = $ima->Get('width');
2778: my $height = $ima->Get('height');
2779: if ($height > $resizeheight) {
2780: my $factor = $height/$resizeheight;
2781: my $newwidth = $width/$factor;
2782: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2783: $resized = 1;
2784: }
2785: }
2786: if ($resized) {
2787: $ima->Write($img_path);
2788: }
2789: }
2790: return;
2791: }
2792:
2793: # --------------- Take an uploaded file and put it into the userfiles directory
2794: # input: $formname - the contents of the file are in $env{"form.$formname"}
2795: # the desired filename is in $env{"form.$formname.filename"}
2796: # $context - possible values: coursedoc, existingfile, overwrite,
2797: # canceloverwrite, or ''.
2798: # if 'coursedoc': upload to the current course
2799: # if 'existingfile': write file to tmp/overwrites directory
2800: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2801: # $context is passed as argument to &finishuserfileupload
2802: # $subdir - directory in userfile to store the file into
2803: # $parser - instruction to parse file for objects ($parser = parse)
2804: # $allfiles - reference to hash for embedded objects
2805: # $codebase - reference to hash for codebase of java objects
2806: # $desuname - username for permanent storage of uploaded file
2807: # $dsetudom - domain for permanaent storage of uploaded file
2808: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2809: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2810: # $resizewidth - width (pixels) to which to resize uploaded image
2811: # $resizeheight - height (pixels) to which to resize uploaded image
2812: # $mimetype - reference to scalar to accommodate mime type determined
2813: # from File::MMagic.
2814: #
2815: # output: url of file in userspace, or error: <message>
2816: # or /adm/notfound.html if failure to upload occurse
2817:
2818: sub userfileupload {
2819: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2820: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2821: if (!defined($subdir)) { $subdir='unknown'; }
2822: my $fname=$env{'form.'.$formname.'.filename'};
2823: $fname=&clean_filename($fname);
2824: # See if there is anything left
2825: unless ($fname) { return 'error: no uploaded file'; }
2826: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2827: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2828: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2829: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2830: my $now = time;
2831: my $filepath;
2832: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2833: $filepath = 'tmp/helprequests/'.$now;
2834: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2835: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2836: '_'.$env{'user.domain'}.'/pending';
2837: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2838: my ($docuname,$docudom);
2839: if ($destudom) {
2840: $docudom = $destudom;
2841: } else {
2842: $docudom = $env{'user.domain'};
2843: }
2844: if ($destuname) {
2845: $docuname = $destuname;
2846: } else {
2847: $docuname = $env{'user.name'};
2848: }
2849: if (exists($env{'form.group'})) {
2850: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2851: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2852: }
2853: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2854: if ($context eq 'canceloverwrite') {
2855: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2856: if (-e $tempfile) {
2857: my @info = stat($tempfile);
2858: if ($info[9] eq $env{'form.timestamp'}) {
2859: unlink($tempfile);
2860: }
2861: }
2862: return;
2863: }
2864: }
2865: # Create the directory if not present
2866: my @parts=split(/\//,$filepath);
2867: my $fullpath = $perlvar{'lonDaemons'};
2868: for (my $i=0;$i<@parts;$i++) {
2869: $fullpath .= '/'.$parts[$i];
2870: if ((-e $fullpath)!=1) {
2871: mkdir($fullpath,0777);
2872: }
2873: }
2874: open(my $fh,'>'.$fullpath.'/'.$fname);
2875: print $fh $env{'form.'.$formname};
2876: close($fh);
2877: if ($context eq 'existingfile') {
2878: my @info = stat($fullpath.'/'.$fname);
2879: return ($fullpath.'/'.$fname,$info[9]);
2880: } else {
2881: return $fullpath.'/'.$fname;
2882: }
2883: }
2884: if ($subdir eq 'scantron') {
2885: $fname = 'scantron_orig_'.$fname;
2886: } else {
2887: $fname="$subdir/$fname";
2888: }
2889: if ($context eq 'coursedoc') {
2890: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2891: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2892: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2893: return &finishuserfileupload($docuname,$docudom,
2894: $formname,$fname,$parser,$allfiles,
2895: $codebase,$thumbwidth,$thumbheight,
2896: $resizewidth,$resizeheight,$context,$mimetype);
2897: } else {
2898: $fname=$env{'form.folder'}.'/'.$fname;
2899: return &process_coursefile('uploaddoc',$docuname,$docudom,
2900: $fname,$formname,$parser,
2901: $allfiles,$codebase,$mimetype);
2902: }
2903: } elsif (defined($destuname)) {
2904: my $docuname=$destuname;
2905: my $docudom=$destudom;
2906: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2907: $parser,$allfiles,$codebase,
2908: $thumbwidth,$thumbheight,
2909: $resizewidth,$resizeheight,$context,$mimetype);
2910: } else {
2911: my $docuname=$env{'user.name'};
2912: my $docudom=$env{'user.domain'};
2913: if (exists($env{'form.group'})) {
2914: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2915: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2916: }
2917: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2918: $parser,$allfiles,$codebase,
2919: $thumbwidth,$thumbheight,
2920: $resizewidth,$resizeheight,$context,$mimetype);
2921: }
2922: }
2923:
2924: sub finishuserfileupload {
2925: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2926: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2927: my $path=$docudom.'/'.$docuname.'/';
2928: my $filepath=$perlvar{'lonDocRoot'};
2929:
2930: my ($fnamepath,$file,$fetchthumb);
2931: $file=$fname;
2932: if ($fname=~m|/|) {
2933: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2934: $path.=$fnamepath.'/';
2935: }
2936: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2937: my $count;
2938: for ($count=4;$count<=$#parts;$count++) {
2939: $filepath.="/$parts[$count]";
2940: if ((-e $filepath)!=1) {
2941: mkdir($filepath,0777);
2942: }
2943: }
2944:
2945: # Save the file
2946: {
2947: if (!open(FH,'>'.$filepath.'/'.$file)) {
2948: &logthis('Failed to create '.$filepath.'/'.$file);
2949: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2950: return '/adm/notfound.html';
2951: }
2952: if ($context eq 'overwrite') {
2953: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2954: my $target = $filepath.'/'.$file;
2955: if (-e $source) {
2956: my @info = stat($source);
2957: if ($info[9] eq $env{'form.timestamp'}) {
2958: unless (&File::Copy::move($source,$target)) {
2959: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2960: return "Moving from $source failed";
2961: }
2962: } else {
2963: return "Temporary file: $source had unexpected date/time for last modification";
2964: }
2965: } else {
2966: return "Temporary file: $source missing";
2967: }
2968: } elsif (!print FH ($env{'form.'.$formname})) {
2969: &logthis('Failed to write to '.$filepath.'/'.$file);
2970: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2971: return '/adm/notfound.html';
2972: }
2973: close(FH);
2974: if ($resizewidth && $resizeheight) {
2975: my $mm = new File::MMagic;
2976: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2977: if ($mime_type =~ m{^image/}) {
2978: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2979: }
2980: }
2981: }
2982: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2983: if (ref($mimetype)) {
2984: if ($$mimetype eq '') {
2985: my $mm = new File::MMagic;
2986: my $type = $mm->checktype_filename($filepath.'/'.$file);
2987: $$mimetype = $type;
2988: }
2989: }
2990: }
2991: if ($parser eq 'parse') {
2992: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
2993: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2994: $allfiles,$codebase);
2995: unless ($parse_result eq 'ok') {
2996: &logthis('Failed to parse '.$filepath.$file.
2997: ' for embedded media: '.$parse_result);
2998: }
2999: }
3000: }
3001: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3002: my $input = $filepath.'/'.$file;
3003: my $output = $filepath.'/'.'tn-'.$file;
3004: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3005: system("convert -sample $thumbsize $input $output");
3006: if (-e $filepath.'/'.'tn-'.$file) {
3007: $fetchthumb = 1;
3008: }
3009: }
3010:
3011: # Notify homeserver to grep it
3012: #
3013: my $docuhome=&homeserver($docuname,$docudom);
3014: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3015: if ($fetchresult eq 'ok') {
3016: if ($fetchthumb) {
3017: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3018: if ($thumbresult ne 'ok') {
3019: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3020: $docuhome.': '.$thumbresult);
3021: }
3022: }
3023: #
3024: # Return the URL to it
3025: return '/uploaded/'.$path.$file;
3026: } else {
3027: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3028: ': '.$fetchresult);
3029: return '/adm/notfound.html';
3030: }
3031: }
3032:
3033: sub extract_embedded_items {
3034: my ($fullpath,$allfiles,$codebase,$content) = @_;
3035: my @state = ();
3036: my %javafiles = (
3037: codebase => '',
3038: code => '',
3039: archive => ''
3040: );
3041: my %mediafiles = (
3042: src => '',
3043: movie => '',
3044: );
3045: my $p;
3046: if ($content) {
3047: $p = HTML::LCParser->new($content);
3048: } else {
3049: $p = HTML::LCParser->new($fullpath);
3050: }
3051: while (my $t=$p->get_token()) {
3052: if ($t->[0] eq 'S') {
3053: my ($tagname, $attr) = ($t->[1],$t->[2]);
3054: push(@state, $tagname);
3055: if (lc($tagname) eq 'allow') {
3056: &add_filetype($allfiles,$attr->{'src'},'src');
3057: }
3058: if (lc($tagname) eq 'img') {
3059: &add_filetype($allfiles,$attr->{'src'},'src');
3060: }
3061: if (lc($tagname) eq 'a') {
3062: &add_filetype($allfiles,$attr->{'href'},'href');
3063: }
3064: if (lc($tagname) eq 'script') {
3065: if ($attr->{'archive'} =~ /\.jar$/i) {
3066: &add_filetype($allfiles,$attr->{'archive'},'archive');
3067: } else {
3068: &add_filetype($allfiles,$attr->{'src'},'src');
3069: }
3070: }
3071: if (lc($tagname) eq 'link') {
3072: if (lc($attr->{'rel'}) eq 'stylesheet') {
3073: &add_filetype($allfiles,$attr->{'href'},'href');
3074: }
3075: }
3076: if (lc($tagname) eq 'object' ||
3077: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3078: foreach my $item (keys(%javafiles)) {
3079: $javafiles{$item} = '';
3080: }
3081: }
3082: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3083: my $name = lc($attr->{'name'});
3084: foreach my $item (keys(%javafiles)) {
3085: if ($name eq $item) {
3086: $javafiles{$item} = $attr->{'value'};
3087: last;
3088: }
3089: }
3090: foreach my $item (keys(%mediafiles)) {
3091: if ($name eq $item) {
3092: &add_filetype($allfiles, $attr->{'value'}, 'value');
3093: last;
3094: }
3095: }
3096: }
3097: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3098: foreach my $item (keys(%javafiles)) {
3099: if ($attr->{$item}) {
3100: $javafiles{$item} = $attr->{$item};
3101: last;
3102: }
3103: }
3104: foreach my $item (keys(%mediafiles)) {
3105: if ($attr->{$item}) {
3106: &add_filetype($allfiles,$attr->{$item},$item);
3107: last;
3108: }
3109: }
3110: }
3111: } elsif ($t->[0] eq 'E') {
3112: my ($tagname) = ($t->[1]);
3113: if ($javafiles{'codebase'} ne '') {
3114: $javafiles{'codebase'} .= '/';
3115: }
3116: if (lc($tagname) eq 'applet' ||
3117: lc($tagname) eq 'object' ||
3118: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3119: ) {
3120: foreach my $item (keys(%javafiles)) {
3121: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3122: my $file=$javafiles{'codebase'}.$javafiles{$item};
3123: &add_filetype($allfiles,$file,$item);
3124: }
3125: }
3126: }
3127: pop @state;
3128: }
3129: }
3130: return 'ok';
3131: }
3132:
3133: sub add_filetype {
3134: my ($allfiles,$file,$type)=@_;
3135: if (exists($allfiles->{$file})) {
3136: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3137: push(@{$allfiles->{$file}}, &escape($type));
3138: }
3139: } else {
3140: @{$allfiles->{$file}} = (&escape($type));
3141: }
3142: }
3143:
3144: sub removeuploadedurl {
3145: my ($url)=@_;
3146: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3147: return &removeuserfile($uname,$udom,$fname);
3148: }
3149:
3150: sub removeuserfile {
3151: my ($docuname,$docudom,$fname)=@_;
3152: my $home=&homeserver($docuname,$docudom);
3153: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3154: if ($result eq 'ok') {
3155: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3156: my $metafile = $fname.'.meta';
3157: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3158: my $url = "/uploaded/$docudom/$docuname/$fname";
3159: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3160: my $sqlresult =
3161: &update_portfolio_table($docuname,$docudom,$file,
3162: 'portfolio_metadata',$group,
3163: 'delete');
3164: }
3165: }
3166: return $result;
3167: }
3168:
3169: sub mkdiruserfile {
3170: my ($docuname,$docudom,$dir)=@_;
3171: my $home=&homeserver($docuname,$docudom);
3172: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3173: }
3174:
3175: sub renameuserfile {
3176: my ($docuname,$docudom,$old,$new)=@_;
3177: my $home=&homeserver($docuname,$docudom);
3178: my $result = &reply("renameuserfile:$docudom:$docuname:".
3179: &escape("$old").':'.&escape("$new"),$home);
3180: if ($result eq 'ok') {
3181: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3182: my $oldmeta = $old.'.meta';
3183: my $newmeta = $new.'.meta';
3184: my $metaresult =
3185: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3186: my $url = "/uploaded/$docudom/$docuname/$old";
3187: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3188: my $sqlresult =
3189: &update_portfolio_table($docuname,$docudom,$file,
3190: 'portfolio_metadata',$group,
3191: 'delete');
3192: }
3193: }
3194: return $result;
3195: }
3196:
3197: # ------------------------------------------------------------------------- Log
3198:
3199: sub log {
3200: my ($dom,$nam,$hom,$what)=@_;
3201: return critical("log:$dom:$nam:$what",$hom);
3202: }
3203:
3204: # ------------------------------------------------------------------ Course Log
3205: #
3206: # This routine flushes several buffers of non-mission-critical nature
3207: #
3208:
3209: sub flushcourselogs {
3210: &logthis('Flushing log buffers');
3211: #
3212: # course logs
3213: # This is a log of all transactions in a course, which can be used
3214: # for data mining purposes
3215: #
3216: # It also collects the courseid database, which lists last transaction
3217: # times and course titles for all courseids
3218: #
3219: my %courseidbuffer=();
3220: foreach my $crsid (keys(%courselogs)) {
3221: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3222: &escape($courselogs{$crsid}),
3223: $coursehombuf{$crsid}) eq 'ok') {
3224: delete $courselogs{$crsid};
3225: } else {
3226: &logthis('Failed to flush log buffer for '.$crsid);
3227: if (length($courselogs{$crsid})>40000) {
3228: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3229: " exceeded maximum size, deleting.</font>");
3230: delete $courselogs{$crsid};
3231: }
3232: }
3233: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3234: 'description' => $coursedescrbuf{$crsid},
3235: 'inst_code' => $courseinstcodebuf{$crsid},
3236: 'type' => $coursetypebuf{$crsid},
3237: 'owner' => $courseownerbuf{$crsid},
3238: };
3239: }
3240: #
3241: # Write course id database (reverse lookup) to homeserver of courses
3242: # Is used in pickcourse
3243: #
3244: foreach my $crs_home (keys(%courseidbuffer)) {
3245: my $response = &courseidput(&host_domain($crs_home),
3246: $courseidbuffer{$crs_home},
3247: $crs_home,'timeonly');
3248: }
3249: #
3250: # File accesses
3251: # Writes to the dynamic metadata of resources to get hit counts, etc.
3252: #
3253: foreach my $entry (keys(%accesshash)) {
3254: if ($entry =~ /___count$/) {
3255: my ($dom,$name);
3256: ($dom,$name,undef)=
3257: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3258: if (! defined($dom) || $dom eq '' ||
3259: ! defined($name) || $name eq '') {
3260: my $cid = $env{'request.course.id'};
3261: $dom = $env{'request.'.$cid.'.domain'};
3262: $name = $env{'request.'.$cid.'.num'};
3263: }
3264: my $value = $accesshash{$entry};
3265: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3266: my %temphash=($url => $value);
3267: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3268: if ($result eq 'ok') {
3269: delete $accesshash{$entry};
3270: }
3271: } else {
3272: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3273: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3274: my %temphash=($entry => $accesshash{$entry});
3275: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3276: delete $accesshash{$entry};
3277: }
3278: }
3279: }
3280: #
3281: # Roles
3282: # Reverse lookup of user roles for course faculty/staff and co-authorship
3283: #
3284: foreach my $entry (keys(%userrolehash)) {
3285: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3286: split(/\:/,$entry);
3287: if (&Apache::lonnet::put('nohist_userroles',
3288: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3289: $rudom,$runame) eq 'ok') {
3290: delete $userrolehash{$entry};
3291: }
3292: }
3293: #
3294: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3295: #
3296: my %domrolebuffer = ();
3297: foreach my $entry (keys(%domainrolehash)) {
3298: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3299: if ($domrolebuffer{$rudom}) {
3300: $domrolebuffer{$rudom}.='&'.&escape($entry).
3301: '='.&escape($domainrolehash{$entry});
3302: } else {
3303: $domrolebuffer{$rudom}.=&escape($entry).
3304: '='.&escape($domainrolehash{$entry});
3305: }
3306: delete $domainrolehash{$entry};
3307: }
3308: foreach my $dom (keys(%domrolebuffer)) {
3309: my %servers = &get_servers($dom,'library');
3310: foreach my $tryserver (keys(%servers)) {
3311: unless (&reply('domroleput:'.$dom.':'.
3312: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3313: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3314: }
3315: }
3316: }
3317: $dumpcount++;
3318: }
3319:
3320: sub courselog {
3321: my $what=shift;
3322: $what=time.':'.$what;
3323: unless ($env{'request.course.id'}) { return ''; }
3324: $coursedombuf{$env{'request.course.id'}}=
3325: $env{'course.'.$env{'request.course.id'}.'.domain'};
3326: $coursenumbuf{$env{'request.course.id'}}=
3327: $env{'course.'.$env{'request.course.id'}.'.num'};
3328: $coursehombuf{$env{'request.course.id'}}=
3329: $env{'course.'.$env{'request.course.id'}.'.home'};
3330: $coursedescrbuf{$env{'request.course.id'}}=
3331: $env{'course.'.$env{'request.course.id'}.'.description'};
3332: $courseinstcodebuf{$env{'request.course.id'}}=
3333: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3334: $courseownerbuf{$env{'request.course.id'}}=
3335: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3336: $coursetypebuf{$env{'request.course.id'}}=
3337: $env{'course.'.$env{'request.course.id'}.'.type'};
3338: if (defined $courselogs{$env{'request.course.id'}}) {
3339: $courselogs{$env{'request.course.id'}}.='&'.$what;
3340: } else {
3341: $courselogs{$env{'request.course.id'}}.=$what;
3342: }
3343: if (length($courselogs{$env{'request.course.id'}})>4048) {
3344: &flushcourselogs();
3345: }
3346: }
3347:
3348: sub courseacclog {
3349: my $fnsymb=shift;
3350: unless ($env{'request.course.id'}) { return ''; }
3351: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3352: if ($fnsymb=~/$LONCAPA::assess_re/) {
3353: $what.=':POST';
3354: # FIXME: Probably ought to escape things....
3355: foreach my $key (keys(%env)) {
3356: if ($key=~/^form\.(.*)/) {
3357: my $formitem = $1;
3358: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3359: $what.=':'.$formitem.'='.$env{$key};
3360: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3361: $what.=':'.$formitem.'='.$env{$key};
3362: }
3363: }
3364: }
3365: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3366: # FIXME: We should not be depending on a form parameter that someone
3367: # editing lonsearchcat.pm might change in the future.
3368: if ($env{'form.phase'} eq 'course_search') {
3369: $what.= ':POST';
3370: # FIXME: Probably ought to escape things....
3371: foreach my $element ('courseexp','crsfulltext','crsrelated',
3372: 'crsdiscuss') {
3373: $what.=':'.$element.'='.$env{'form.'.$element};
3374: }
3375: }
3376: }
3377: &courselog($what);
3378: }
3379:
3380: sub countacc {
3381: my $url=&declutter(shift);
3382: return if (! defined($url) || $url eq '');
3383: unless ($env{'request.course.id'}) { return ''; }
3384: #
3385: # Mark that this url was used in this course
3386: #
3387: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3388: #
3389: # Increase the access count for this resource in this child process
3390: #
3391: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3392: $accesshash{$key}++;
3393: }
3394:
3395: sub linklog {
3396: my ($from,$to)=@_;
3397: $from=&declutter($from);
3398: $to=&declutter($to);
3399: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3400: $accesshash{$to.'___'.$from.'___goto'}=1;
3401: }
3402:
3403: sub statslog {
3404: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3405: if ($users<2) { return; }
3406: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3407: 'course' => $env{'request.course.id'},
3408: 'sections' => '"all"',
3409: 'num_students' => $users,
3410: 'part' => $part,
3411: 'symb' => $symb,
3412: 'mean_tries' => $av_attempts,
3413: 'deg_of_diff' => $degdiff});
3414: foreach my $key (keys(%dynstore)) {
3415: $accesshash{$key}=$dynstore{$key};
3416: }
3417: }
3418:
3419: sub userrolelog {
3420: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3421: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
3422: ($trole=~/^in/) || ($trole=~/^cc/) ||
3423: ($trole=~/^ep/) || ($trole=~/^cr/) ||
3424: ($trole=~/^ta/) || ($trole=~/^co/)) {
3425: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3426: $userrolehash
3427: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3428: =$tend.':'.$tstart;
3429: }
3430: if (($env{'request.role'} =~ /dc\./) &&
3431: (($trole=~/^au/) || ($trole=~/^in/) ||
3432: ($trole=~/^cc/) || ($trole=~/^ep/) ||
3433: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3434: ($trole=~/^co/))) {
3435: $userrolehash
3436: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3437: =$tend.':'.$tstart;
3438: }
3439: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3440: ($trole=~/^li/) || ($trole=~/^li/) ||
3441: ($trole=~/^au/) || ($trole=~/^dg/) ||
3442: ($trole=~/^sc/)) {
3443: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3444: $domainrolehash
3445: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3446: = $tend.':'.$tstart;
3447: }
3448: }
3449:
3450: sub courserolelog {
3451: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3452: if (($trole eq 'cc') || ($trole eq 'in') ||
3453: ($trole eq 'ep') || ($trole eq 'ad') ||
3454: ($trole eq 'ta') || ($trole eq 'st') ||
3455: ($trole=~/^cr/) || ($trole eq 'gr') ||
3456: ($trole eq 'co')) {
3457: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3458: my $cdom = $1;
3459: my $cnum = $2;
3460: my $sec = $3;
3461: my $namespace = 'rolelog';
3462: my %storehash = (
3463: role => $trole,
3464: start => $tstart,
3465: end => $tend,
3466: selfenroll => $selfenroll,
3467: context => $context,
3468: );
3469: if ($trole eq 'gr') {
3470: $namespace = 'groupslog';
3471: $storehash{'group'} = $sec;
3472: } else {
3473: $storehash{'section'} = $sec;
3474: }
3475: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3476: if (($trole ne 'st') || ($sec ne '')) {
3477: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3478: }
3479: }
3480: }
3481: return;
3482: }
3483:
3484: sub get_course_adv_roles {
3485: my ($cid,$codes) = @_;
3486: $cid=$env{'request.course.id'} unless (defined($cid));
3487: my %coursehash=&coursedescription($cid);
3488: my $crstype = &Apache::loncommon::course_type($cid);
3489: my %nothide=();
3490: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3491: if ($user !~ /:/) {
3492: $nothide{join(':',split(/[\@]/,$user))}=1;
3493: } else {
3494: $nothide{$user}=1;
3495: }
3496: }
3497: my %returnhash=();
3498: my %dumphash=
3499: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3500: my $now=time;
3501: my %privileged;
3502: foreach my $entry (keys(%dumphash)) {
3503: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3504: if (($tstart) && ($tstart<0)) { next; }
3505: if (($tend) && ($tend<$now)) { next; }
3506: if (($tstart) && ($now<$tstart)) { next; }
3507: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3508: if ($username eq '' || $domain eq '') { next; }
3509: unless (ref($privileged{$domain}) eq 'HASH') {
3510: my %dompersonnel =
3511: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3512: $privileged{$domain} = {};
3513: foreach my $server (keys(%dompersonnel)) {
3514: if (ref($dompersonnel{$server}) eq 'HASH') {
3515: foreach my $user (keys(%{$dompersonnel{$server}})) {
3516: my ($trole,$uname,$udom) = split(/:/,$user);
3517: $privileged{$udom}{$uname} = 1;
3518: }
3519: }
3520: }
3521: }
3522: if ((exists($privileged{$domain}{$username})) &&
3523: (!$nothide{$username.':'.$domain})) { next; }
3524: if ($role eq 'cr') { next; }
3525: if ($codes) {
3526: if ($section) { $role .= ':'.$section; }
3527: if ($returnhash{$role}) {
3528: $returnhash{$role}.=','.$username.':'.$domain;
3529: } else {
3530: $returnhash{$role}=$username.':'.$domain;
3531: }
3532: } else {
3533: my $key=&plaintext($role,$crstype);
3534: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3535: if ($returnhash{$key}) {
3536: $returnhash{$key}.=','.$username.':'.$domain;
3537: } else {
3538: $returnhash{$key}=$username.':'.$domain;
3539: }
3540: }
3541: }
3542: return %returnhash;
3543: }
3544:
3545: sub get_my_roles {
3546: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3547: unless (defined($uname)) { $uname=$env{'user.name'}; }
3548: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3549: my (%dumphash,%nothide);
3550: if ($context eq 'userroles') {
3551: my $extra = &freeze_escape({'skipcheck' => 1});
3552: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
3553: } else {
3554: %dumphash=
3555: &dump('nohist_userroles',$udom,$uname);
3556: if ($hidepriv) {
3557: my %coursehash=&coursedescription($udom.'_'.$uname);
3558: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3559: if ($user !~ /:/) {
3560: $nothide{join(':',split(/[\@]/,$user))} = 1;
3561: } else {
3562: $nothide{$user} = 1;
3563: }
3564: }
3565: }
3566: }
3567: my %returnhash=();
3568: my $now=time;
3569: my %privileged;
3570: foreach my $entry (keys(%dumphash)) {
3571: my ($role,$tend,$tstart);
3572: if ($context eq 'userroles') {
3573: next if ($entry =~ /^rolesdef/);
3574: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3575: } else {
3576: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3577: }
3578: if (($tstart) && ($tstart<0)) { next; }
3579: my $status = 'active';
3580: if (($tend) && ($tend<=$now)) {
3581: $status = 'previous';
3582: }
3583: if (($tstart) && ($now<$tstart)) {
3584: $status = 'future';
3585: }
3586: if (ref($types) eq 'ARRAY') {
3587: if (!grep(/^\Q$status\E$/,@{$types})) {
3588: next;
3589: }
3590: } else {
3591: if ($status ne 'active') {
3592: next;
3593: }
3594: }
3595: my ($rolecode,$username,$domain,$section,$area);
3596: if ($context eq 'userroles') {
3597: ($area,$rolecode) = split(/_/,$entry);
3598: (undef,$domain,$username,$section) = split(/\//,$area);
3599: } else {
3600: ($role,$username,$domain,$section) = split(/\:/,$entry);
3601: }
3602: if (ref($roledoms) eq 'ARRAY') {
3603: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3604: next;
3605: }
3606: }
3607: if (ref($roles) eq 'ARRAY') {
3608: if (!grep(/^\Q$role\E$/,@{$roles})) {
3609: if ($role =~ /^cr\//) {
3610: if (!grep(/^cr$/,@{$roles})) {
3611: next;
3612: }
3613: } elsif ($role =~ /^gr\//) {
3614: if (!grep(/^gr$/,@{$roles})) {
3615: next;
3616: }
3617: } else {
3618: next;
3619: }
3620: }
3621: }
3622: if ($hidepriv) {
3623: if ($context eq 'userroles') {
3624: if ((&privileged($username,$domain)) &&
3625: (!$nothide{$username.':'.$domain})) {
3626: next;
3627: }
3628: } else {
3629: unless (ref($privileged{$domain}) eq 'HASH') {
3630: my %dompersonnel =
3631: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3632: $privileged{$domain} = {};
3633: if (keys(%dompersonnel)) {
3634: foreach my $server (keys(%dompersonnel)) {
3635: if (ref($dompersonnel{$server}) eq 'HASH') {
3636: foreach my $user (keys(%{$dompersonnel{$server}})) {
3637: my ($trole,$uname,$udom) = split(/:/,$user);
3638: $privileged{$udom}{$uname} = $trole;
3639: }
3640: }
3641: }
3642: }
3643: }
3644: if (exists($privileged{$domain}{$username})) {
3645: if (!$nothide{$username.':'.$domain}) {
3646: next;
3647: }
3648: }
3649: }
3650: }
3651: if ($withsec) {
3652: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3653: $tstart.':'.$tend;
3654: } else {
3655: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3656: }
3657: }
3658: return %returnhash;
3659: }
3660:
3661: # ----------------------------------------------------- Frontpage Announcements
3662: #
3663: #
3664:
3665: sub postannounce {
3666: my ($server,$text)=@_;
3667: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3668: unless ($text=~/\w/) { $text=''; }
3669: return &reply('setannounce:'.&escape($text),$server);
3670: }
3671:
3672: sub getannounce {
3673:
3674: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3675: my $announcement='';
3676: while (my $line = <$fh>) { $announcement .= $line; }
3677: close($fh);
3678: if ($announcement=~/\w/) {
3679: return
3680: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3681: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3682: } else {
3683: return '';
3684: }
3685: } else {
3686: return '';
3687: }
3688: }
3689:
3690: # ---------------------------------------------------------- Course ID routines
3691: # Deal with domain's nohist_courseid.db files
3692: #
3693:
3694: sub courseidput {
3695: my ($domain,$storehash,$coursehome,$caller) = @_;
3696: return unless (ref($storehash) eq 'HASH');
3697: my $outcome;
3698: if ($caller eq 'timeonly') {
3699: my $cids = '';
3700: foreach my $item (keys(%$storehash)) {
3701: $cids.=&escape($item).'&';
3702: }
3703: $cids=~s/\&$//;
3704: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3705: $coursehome);
3706: } else {
3707: my $items = '';
3708: foreach my $item (keys(%$storehash)) {
3709: $items.= &escape($item).'='.
3710: &freeze_escape($$storehash{$item}).'&';
3711: }
3712: $items=~s/\&$//;
3713: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3714: $coursehome);
3715: }
3716: if ($outcome eq 'unknown_cmd') {
3717: my $what;
3718: foreach my $cid (keys(%$storehash)) {
3719: $what .= &escape($cid).'=';
3720: foreach my $item ('description','inst_code','owner','type') {
3721: $what .= &escape($storehash->{$cid}{$item}).':';
3722: }
3723: $what =~ s/\:$/&/;
3724: }
3725: $what =~ s/\&$//;
3726: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3727: } else {
3728: return $outcome;
3729: }
3730: }
3731:
3732: sub courseiddump {
3733: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3734: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3735: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3736: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3737: my $as_hash = 1;
3738: my %returnhash;
3739: if (!$domfilter) { $domfilter=''; }
3740: my %libserv = &all_library();
3741: foreach my $tryserver (keys(%libserv)) {
3742: if ( ( $hostidflag == 1
3743: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3744: || (!defined($hostidflag)) ) {
3745:
3746: if (($domfilter eq '') ||
3747: (&host_domain($tryserver) eq $domfilter)) {
3748: my $rep =
3749: &reply('courseiddump:'.&host_domain($tryserver).':'.
3750: $sincefilter.':'.&escape($descfilter).':'.
3751: &escape($instcodefilter).':'.&escape($ownerfilter).
3752: ':'.&escape($coursefilter).':'.&escape($typefilter).
3753: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3754: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3755: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3756: &escape($cc_clone).':'.$cloneonly.':'.
3757: &escape($createdbefore).':'.&escape($createdafter).':'.
3758: &escape($creationcontext).':'.$domcloner,
3759: $tryserver);
3760: my @pairs=split(/\&/,$rep);
3761: foreach my $item (@pairs) {
3762: my ($key,$value)=split(/\=/,$item,2);
3763: $key = &unescape($key);
3764: next if ($key =~ /^error: 2 /);
3765: my $result = &thaw_unescape($value);
3766: if (ref($result) eq 'HASH') {
3767: $returnhash{$key}=$result;
3768: } else {
3769: my @responses = split(/:/,$value);
3770: my @items = ('description','inst_code','owner','type');
3771: for (my $i=0; $i<@responses; $i++) {
3772: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3773: }
3774: }
3775: }
3776: }
3777: }
3778: }
3779: return %returnhash;
3780: }
3781:
3782: sub courselastaccess {
3783: my ($cdom,$cnum,$hostidref) = @_;
3784: my %returnhash;
3785: if ($cdom && $cnum) {
3786: my $chome = &homeserver($cnum,$cdom);
3787: if ($chome ne 'no_host') {
3788: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3789: &extract_lastaccess(\%returnhash,$rep);
3790: }
3791: } else {
3792: if (!$cdom) { $cdom=''; }
3793: my %libserv = &all_library();
3794: foreach my $tryserver (keys(%libserv)) {
3795: if (ref($hostidref) eq 'ARRAY') {
3796: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3797: }
3798: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3799: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3800: &extract_lastaccess(\%returnhash,$rep);
3801: }
3802: }
3803: }
3804: return %returnhash;
3805: }
3806:
3807: sub extract_lastaccess {
3808: my ($returnhash,$rep) = @_;
3809: if (ref($returnhash) eq 'HASH') {
3810: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3811: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3812: $rep eq '') {
3813: my @pairs=split(/\&/,$rep);
3814: foreach my $item (@pairs) {
3815: my ($key,$value)=split(/\=/,$item,2);
3816: $key = &unescape($key);
3817: next if ($key =~ /^error: 2 /);
3818: $returnhash->{$key} = &thaw_unescape($value);
3819: }
3820: }
3821: }
3822: return;
3823: }
3824:
3825: # ---------------------------------------------------------- DC e-mail
3826:
3827: sub dcmailput {
3828: my ($domain,$msgid,$message,$server)=@_;
3829: my $status = &Apache::lonnet::critical(
3830: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3831: &escape($message),$server);
3832: return $status;
3833: }
3834:
3835: sub dcmaildump {
3836: my ($dom,$startdate,$enddate,$senders) = @_;
3837: my %returnhash=();
3838:
3839: if (defined(&domain($dom,'primary'))) {
3840: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3841: &escape($enddate).':';
3842: my @esc_senders=map { &escape($_)} @$senders;
3843: $cmd.=&escape(join('&',@esc_senders));
3844: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3845: my ($key,$value) = split(/\=/,$line,2);
3846: if (($key) && ($value)) {
3847: $returnhash{&unescape($key)} = &unescape($value);
3848: }
3849: }
3850: }
3851: return %returnhash;
3852: }
3853: # ---------------------------------------------------------- Domain roles
3854:
3855: sub get_domain_roles {
3856: my ($dom,$roles,$startdate,$enddate)=@_;
3857: if ((!defined($startdate)) || ($startdate eq '')) {
3858: $startdate = '.';
3859: }
3860: if ((!defined($enddate)) || ($enddate eq '')) {
3861: $enddate = '.';
3862: }
3863: my $rolelist;
3864: if (ref($roles) eq 'ARRAY') {
3865: $rolelist = join(':',@{$roles});
3866: }
3867: my %personnel = ();
3868:
3869: my %servers = &get_servers($dom,'library');
3870: foreach my $tryserver (keys(%servers)) {
3871: %{$personnel{$tryserver}}=();
3872: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3873: &escape($startdate).':'.
3874: &escape($enddate).':'.
3875: &escape($rolelist), $tryserver))) {
3876: my ($key,$value) = split(/\=/,$line,2);
3877: if (($key) && ($value)) {
3878: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3879: }
3880: }
3881: }
3882: return %personnel;
3883: }
3884:
3885: # ----------------------------------------------------------- Interval timing
3886:
3887: {
3888: # Caches needed for speedup of navmaps
3889: # We don't want to cache this for very long at all (5 seconds at most)
3890: #
3891: # The user for whom we cache
3892: my $cachedkey='';
3893: # The cached times for this user
3894: my %cachedtimes=();
3895: # When this was last done
3896: my $cachedtime=();
3897:
3898: sub load_all_first_access {
3899: my ($uname,$udom)=@_;
3900: if (($cachedkey eq $uname.':'.$udom) &&
3901: (abs($cachedtime-time)<5)) {
3902: return;
3903: }
3904: $cachedtime=time;
3905: $cachedkey=$uname.':'.$udom;
3906: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
3907: }
3908:
3909: sub get_first_access {
3910: my ($type,$argsymb,$argmap)=@_;
3911: my ($symb,$courseid,$udom,$uname)=&whichuser();
3912: if ($argsymb) { $symb=$argsymb; }
3913: my ($map,$id,$res)=&decode_symb($symb);
3914: if ($argmap) { $map = $argmap; }
3915: if ($type eq 'course') {
3916: $res='course';
3917: } elsif ($type eq 'map') {
3918: $res=&symbread($map);
3919: } else {
3920: $res=$symb;
3921: }
3922: &load_all_first_access($uname,$udom);
3923: return $cachedtimes{"$courseid\0$res"};
3924: }
3925:
3926: sub set_first_access {
3927: my ($type,$interval)=@_;
3928: my ($symb,$courseid,$udom,$uname)=&whichuser();
3929: my ($map,$id,$res)=&decode_symb($symb);
3930: if ($type eq 'course') {
3931: $res='course';
3932: } elsif ($type eq 'map') {
3933: $res=&symbread($map);
3934: } else {
3935: $res=$symb;
3936: }
3937: $cachedkey='';
3938: my $firstaccess=&get_first_access($type,$symb,$map);
3939: if (!$firstaccess) {
3940: my $start = time;
3941: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
3942: $udom,$uname);
3943: if ($putres eq 'ok') {
3944: &put('timerinterval',{"$courseid\0$res"=>$interval},
3945: $udom,$uname);
3946: &appenv(
3947: {
3948: 'course.'.$courseid.'.firstaccess.'.$res => $start,
3949: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
3950: }
3951: );
3952: }
3953: return $putres;
3954: }
3955: return 'already_set';
3956: }
3957: }
3958: # --------------------------------------------- Set Expire Date for Spreadsheet
3959:
3960: sub expirespread {
3961: my ($uname,$udom,$stype,$usymb)=@_;
3962: my $cid=$env{'request.course.id'};
3963: if ($cid) {
3964: my $now=time;
3965: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3966: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3967: $env{'course.'.$cid.'.num'}.
3968: ':nohist_expirationdates:'.
3969: &escape($key).'='.$now,
3970: $env{'course.'.$cid.'.home'})
3971: }
3972: return 'ok';
3973: }
3974:
3975: # ----------------------------------------------------- Devalidate Spreadsheets
3976:
3977: sub devalidate {
3978: my ($symb,$uname,$udom)=@_;
3979: my $cid=$env{'request.course.id'};
3980: if ($cid) {
3981: # delete the stored spreadsheets for
3982: # - the student level sheet of this user in course's homespace
3983: # - the assessment level sheet for this resource
3984: # for this user in user's homespace
3985: # - current conditional state info
3986: my $key=$uname.':'.$udom.':';
3987: my $status=
3988: &del('nohist_calculatedsheets',
3989: [$key.'studentcalc:'],
3990: $env{'course.'.$cid.'.domain'},
3991: $env{'course.'.$cid.'.num'})
3992: .' '.
3993: &del('nohist_calculatedsheets_'.$cid,
3994: [$key.'assesscalc:'.$symb],$udom,$uname);
3995: unless ($status eq 'ok ok') {
3996: &logthis('Could not devalidate spreadsheet '.
3997: $uname.' at '.$udom.' for '.
3998: $symb.': '.$status);
3999: }
4000: &delenv('user.state.'.$cid);
4001: }
4002: }
4003:
4004: sub get_scalar {
4005: my ($string,$end) = @_;
4006: my $value;
4007: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4008: $value = $1;
4009: } elsif ($$string =~ s/^([^&]*?)&//) {
4010: $value = $1;
4011: }
4012: return &unescape($value);
4013: }
4014:
4015: sub array2str {
4016: my (@array) = @_;
4017: my $result=&arrayref2str(\@array);
4018: $result=~s/^__ARRAY_REF__//;
4019: $result=~s/__END_ARRAY_REF__$//;
4020: return $result;
4021: }
4022:
4023: sub arrayref2str {
4024: my ($arrayref) = @_;
4025: my $result='__ARRAY_REF__';
4026: foreach my $elem (@$arrayref) {
4027: if(ref($elem) eq 'ARRAY') {
4028: $result.=&arrayref2str($elem).'&';
4029: } elsif(ref($elem) eq 'HASH') {
4030: $result.=&hashref2str($elem).'&';
4031: } elsif(ref($elem)) {
4032: #print("Got a ref of ".(ref($elem))." skipping.");
4033: } else {
4034: $result.=&escape($elem).'&';
4035: }
4036: }
4037: $result=~s/\&$//;
4038: $result .= '__END_ARRAY_REF__';
4039: return $result;
4040: }
4041:
4042: sub hash2str {
4043: my (%hash) = @_;
4044: my $result=&hashref2str(\%hash);
4045: $result=~s/^__HASH_REF__//;
4046: $result=~s/__END_HASH_REF__$//;
4047: return $result;
4048: }
4049:
4050: sub hashref2str {
4051: my ($hashref)=@_;
4052: my $result='__HASH_REF__';
4053: foreach my $key (sort(keys(%$hashref))) {
4054: if (ref($key) eq 'ARRAY') {
4055: $result.=&arrayref2str($key).'=';
4056: } elsif (ref($key) eq 'HASH') {
4057: $result.=&hashref2str($key).'=';
4058: } elsif (ref($key)) {
4059: $result.='=';
4060: #print("Got a ref of ".(ref($key))." skipping.");
4061: } else {
4062: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4063: }
4064:
4065: if(ref($hashref->{$key}) eq 'ARRAY') {
4066: $result.=&arrayref2str($hashref->{$key}).'&';
4067: } elsif(ref($hashref->{$key}) eq 'HASH') {
4068: $result.=&hashref2str($hashref->{$key}).'&';
4069: } elsif(ref($hashref->{$key})) {
4070: $result.='&';
4071: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4072: } else {
4073: $result.=&escape($hashref->{$key}).'&';
4074: }
4075: }
4076: $result=~s/\&$//;
4077: $result .= '__END_HASH_REF__';
4078: return $result;
4079: }
4080:
4081: sub str2hash {
4082: my ($string)=@_;
4083: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4084: return %$hash;
4085: }
4086:
4087: sub str2hashref {
4088: my ($string) = @_;
4089:
4090: my %hash;
4091:
4092: if($string !~ /^__HASH_REF__/) {
4093: if (! ($string eq '' || !defined($string))) {
4094: $hash{'error'}='Not hash reference';
4095: }
4096: return (\%hash, $string);
4097: }
4098:
4099: $string =~ s/^__HASH_REF__//;
4100:
4101: while($string !~ /^__END_HASH_REF__/) {
4102: #key
4103: my $key='';
4104: if($string =~ /^__HASH_REF__/) {
4105: ($key, $string)=&str2hashref($string);
4106: if(defined($key->{'error'})) {
4107: $hash{'error'}='Bad data';
4108: return (\%hash, $string);
4109: }
4110: } elsif($string =~ /^__ARRAY_REF__/) {
4111: ($key, $string)=&str2arrayref($string);
4112: if($key->[0] eq 'Array reference error') {
4113: $hash{'error'}='Bad data';
4114: return (\%hash, $string);
4115: }
4116: } else {
4117: $string =~ s/^(.*?)=//;
4118: $key=&unescape($1);
4119: }
4120: $string =~ s/^=//;
4121:
4122: #value
4123: my $value='';
4124: if($string =~ /^__HASH_REF__/) {
4125: ($value, $string)=&str2hashref($string);
4126: if(defined($value->{'error'})) {
4127: $hash{'error'}='Bad data';
4128: return (\%hash, $string);
4129: }
4130: } elsif($string =~ /^__ARRAY_REF__/) {
4131: ($value, $string)=&str2arrayref($string);
4132: if($value->[0] eq 'Array reference error') {
4133: $hash{'error'}='Bad data';
4134: return (\%hash, $string);
4135: }
4136: } else {
4137: $value=&get_scalar(\$string,'__END_HASH_REF__');
4138: }
4139: $string =~ s/^&//;
4140:
4141: $hash{$key}=$value;
4142: }
4143:
4144: $string =~ s/^__END_HASH_REF__//;
4145:
4146: return (\%hash, $string);
4147: }
4148:
4149: sub str2array {
4150: my ($string)=@_;
4151: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4152: return @$array;
4153: }
4154:
4155: sub str2arrayref {
4156: my ($string) = @_;
4157: my @array;
4158:
4159: if($string !~ /^__ARRAY_REF__/) {
4160: if (! ($string eq '' || !defined($string))) {
4161: $array[0]='Array reference error';
4162: }
4163: return (\@array, $string);
4164: }
4165:
4166: $string =~ s/^__ARRAY_REF__//;
4167:
4168: while($string !~ /^__END_ARRAY_REF__/) {
4169: my $value='';
4170: if($string =~ /^__HASH_REF__/) {
4171: ($value, $string)=&str2hashref($string);
4172: if(defined($value->{'error'})) {
4173: $array[0] ='Array reference error';
4174: return (\@array, $string);
4175: }
4176: } elsif($string =~ /^__ARRAY_REF__/) {
4177: ($value, $string)=&str2arrayref($string);
4178: if($value->[0] eq 'Array reference error') {
4179: $array[0] ='Array reference error';
4180: return (\@array, $string);
4181: }
4182: } else {
4183: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4184: }
4185: $string =~ s/^&//;
4186:
4187: push(@array, $value);
4188: }
4189:
4190: $string =~ s/^__END_ARRAY_REF__//;
4191:
4192: return (\@array, $string);
4193: }
4194:
4195: # -------------------------------------------------------------------Temp Store
4196:
4197: sub tmpreset {
4198: my ($symb,$namespace,$domain,$stuname) = @_;
4199: if (!$symb) {
4200: $symb=&symbread();
4201: if (!$symb) { $symb= $env{'request.url'}; }
4202: }
4203: $symb=escape($symb);
4204:
4205: if (!$namespace) { $namespace=$env{'request.state'}; }
4206: $namespace=~s/\//\_/g;
4207: $namespace=~s/\W//g;
4208:
4209: if (!$domain) { $domain=$env{'user.domain'}; }
4210: if (!$stuname) { $stuname=$env{'user.name'}; }
4211: if ($domain eq 'public' && $stuname eq 'public') {
4212: $stuname=$ENV{'REMOTE_ADDR'};
4213: }
4214: my $path=LONCAPA::tempdir();
4215: my %hash;
4216: if (tie(%hash,'GDBM_File',
4217: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4218: &GDBM_WRCREAT(),0640)) {
4219: foreach my $key (keys(%hash)) {
4220: if ($key=~ /:$symb/) {
4221: delete($hash{$key});
4222: }
4223: }
4224: }
4225: }
4226:
4227: sub tmpstore {
4228: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4229:
4230: if (!$symb) {
4231: $symb=&symbread();
4232: if (!$symb) { $symb= $env{'request.url'}; }
4233: }
4234: $symb=escape($symb);
4235:
4236: if (!$namespace) {
4237: # I don't think we would ever want to store this for a course.
4238: # it seems this will only be used if we don't have a course.
4239: #$namespace=$env{'request.course.id'};
4240: #if (!$namespace) {
4241: $namespace=$env{'request.state'};
4242: #}
4243: }
4244: $namespace=~s/\//\_/g;
4245: $namespace=~s/\W//g;
4246: if (!$domain) { $domain=$env{'user.domain'}; }
4247: if (!$stuname) { $stuname=$env{'user.name'}; }
4248: if ($domain eq 'public' && $stuname eq 'public') {
4249: $stuname=$ENV{'REMOTE_ADDR'};
4250: }
4251: my $now=time;
4252: my %hash;
4253: my $path=LONCAPA::tempdir();
4254: if (tie(%hash,'GDBM_File',
4255: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4256: &GDBM_WRCREAT(),0640)) {
4257: $hash{"version:$symb"}++;
4258: my $version=$hash{"version:$symb"};
4259: my $allkeys='';
4260: foreach my $key (keys(%$storehash)) {
4261: $allkeys.=$key.':';
4262: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4263: }
4264: $hash{"$version:$symb:timestamp"}=$now;
4265: $allkeys.='timestamp';
4266: $hash{"$version:keys:$symb"}=$allkeys;
4267: if (untie(%hash)) {
4268: return 'ok';
4269: } else {
4270: return "error:$!";
4271: }
4272: } else {
4273: return "error:$!";
4274: }
4275: }
4276:
4277: # -----------------------------------------------------------------Temp Restore
4278:
4279: sub tmprestore {
4280: my ($symb,$namespace,$domain,$stuname) = @_;
4281:
4282: if (!$symb) {
4283: $symb=&symbread();
4284: if (!$symb) { $symb= $env{'request.url'}; }
4285: }
4286: $symb=escape($symb);
4287:
4288: if (!$namespace) { $namespace=$env{'request.state'}; }
4289:
4290: if (!$domain) { $domain=$env{'user.domain'}; }
4291: if (!$stuname) { $stuname=$env{'user.name'}; }
4292: if ($domain eq 'public' && $stuname eq 'public') {
4293: $stuname=$ENV{'REMOTE_ADDR'};
4294: }
4295: my %returnhash;
4296: $namespace=~s/\//\_/g;
4297: $namespace=~s/\W//g;
4298: my %hash;
4299: my $path=LONCAPA::tempdir();
4300: if (tie(%hash,'GDBM_File',
4301: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4302: &GDBM_READER(),0640)) {
4303: my $version=$hash{"version:$symb"};
4304: $returnhash{'version'}=$version;
4305: my $scope;
4306: for ($scope=1;$scope<=$version;$scope++) {
4307: my $vkeys=$hash{"$scope:keys:$symb"};
4308: my @keys=split(/:/,$vkeys);
4309: my $key;
4310: $returnhash{"$scope:keys"}=$vkeys;
4311: foreach $key (@keys) {
4312: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4313: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4314: }
4315: }
4316: if (!(untie(%hash))) {
4317: return "error:$!";
4318: }
4319: } else {
4320: return "error:$!";
4321: }
4322: return %returnhash;
4323: }
4324:
4325: # ----------------------------------------------------------------------- Store
4326:
4327: sub store {
4328: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4329: my $home='';
4330:
4331: if ($stuname) { $home=&homeserver($stuname,$domain); }
4332:
4333: $symb=&symbclean($symb);
4334: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4335:
4336: if (!$domain) { $domain=$env{'user.domain'}; }
4337: if (!$stuname) { $stuname=$env{'user.name'}; }
4338:
4339: &devalidate($symb,$stuname,$domain);
4340:
4341: $symb=escape($symb);
4342: if (!$namespace) {
4343: unless ($namespace=$env{'request.course.id'}) {
4344: return '';
4345: }
4346: }
4347: if (!$home) { $home=$env{'user.home'}; }
4348:
4349: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4350: $$storehash{'host'}=$perlvar{'lonHostID'};
4351:
4352: my $namevalue='';
4353: foreach my $key (keys(%$storehash)) {
4354: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4355: }
4356: $namevalue=~s/\&$//;
4357: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4358: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4359: }
4360:
4361: # -------------------------------------------------------------- Critical Store
4362:
4363: sub cstore {
4364: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4365: my $home='';
4366:
4367: if ($stuname) { $home=&homeserver($stuname,$domain); }
4368:
4369: $symb=&symbclean($symb);
4370: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4371:
4372: if (!$domain) { $domain=$env{'user.domain'}; }
4373: if (!$stuname) { $stuname=$env{'user.name'}; }
4374:
4375: &devalidate($symb,$stuname,$domain);
4376:
4377: $symb=escape($symb);
4378: if (!$namespace) {
4379: unless ($namespace=$env{'request.course.id'}) {
4380: return '';
4381: }
4382: }
4383: if (!$home) { $home=$env{'user.home'}; }
4384:
4385: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4386: $$storehash{'host'}=$perlvar{'lonHostID'};
4387:
4388: my $namevalue='';
4389: foreach my $key (keys(%$storehash)) {
4390: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4391: }
4392: $namevalue=~s/\&$//;
4393: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4394: return critical
4395: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4396: }
4397:
4398: # --------------------------------------------------------------------- Restore
4399:
4400: sub restore {
4401: my ($symb,$namespace,$domain,$stuname) = @_;
4402: my $home='';
4403:
4404: if ($stuname) { $home=&homeserver($stuname,$domain); }
4405:
4406: if (!$symb) {
4407: unless ($symb=escape(&symbread())) { return ''; }
4408: } else {
4409: $symb=&escape(&symbclean($symb));
4410: }
4411: if (!$namespace) {
4412: unless ($namespace=$env{'request.course.id'}) {
4413: return '';
4414: }
4415: }
4416: if (!$domain) { $domain=$env{'user.domain'}; }
4417: if (!$stuname) { $stuname=$env{'user.name'}; }
4418: if (!$home) { $home=$env{'user.home'}; }
4419: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4420:
4421: my %returnhash=();
4422: foreach my $line (split(/\&/,$answer)) {
4423: my ($name,$value)=split(/\=/,$line);
4424: $returnhash{&unescape($name)}=&thaw_unescape($value);
4425: }
4426: my $version;
4427: for ($version=1;$version<=$returnhash{'version'};$version++) {
4428: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4429: $returnhash{$item}=$returnhash{$version.':'.$item};
4430: }
4431: }
4432: return %returnhash;
4433: }
4434:
4435: # ---------------------------------------------------------- Course Description
4436: #
4437: #
4438:
4439: sub coursedescription {
4440: my ($courseid,$args)=@_;
4441: $courseid=~s/^\///;
4442: $courseid=~s/\_/\//g;
4443: my ($cdomain,$cnum)=split(/\//,$courseid);
4444: my $chome=&homeserver($cnum,$cdomain);
4445: my $normalid=$cdomain.'_'.$cnum;
4446: # need to always cache even if we get errors otherwise we keep
4447: # trying and trying and trying to get the course description.
4448: my %envhash=();
4449: my %returnhash=();
4450:
4451: my $expiretime=600;
4452: if ($env{'request.course.id'} eq $normalid) {
4453: $expiretime=120;
4454: }
4455:
4456: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4457: if (!$args->{'freshen_cache'}
4458: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4459: foreach my $key (keys(%env)) {
4460: next if ($key !~ /^\Q$prefix\E(.*)/);
4461: my ($setting) = $1;
4462: $returnhash{$setting} = $env{$key};
4463: }
4464: return %returnhash;
4465: }
4466:
4467: # get the data again
4468:
4469: if (!$args->{'one_time'}) {
4470: $envhash{'course.'.$normalid.'.last_cache'}=time;
4471: }
4472:
4473: if ($chome ne 'no_host') {
4474: %returnhash=&dump('environment',$cdomain,$cnum);
4475: if (!exists($returnhash{'con_lost'})) {
4476: my $username = $env{'user.name'}; # Defult username
4477: if(defined $args->{'user'}) {
4478: $username = $args->{'user'};
4479: }
4480: $returnhash{'home'}= $chome;
4481: $returnhash{'domain'} = $cdomain;
4482: $returnhash{'num'} = $cnum;
4483: if (!defined($returnhash{'type'})) {
4484: $returnhash{'type'} = 'Course';
4485: }
4486: while (my ($name,$value) = each %returnhash) {
4487: $envhash{'course.'.$normalid.'.'.$name}=$value;
4488: }
4489: $returnhash{'url'}=&clutter($returnhash{'url'});
4490: $returnhash{'fn'}=LONCAPA::tempdir() .
4491: $username.'_'.$cdomain.'_'.$cnum;
4492: $envhash{'course.'.$normalid.'.home'}=$chome;
4493: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4494: $envhash{'course.'.$normalid.'.num'}=$cnum;
4495: }
4496: }
4497: if (!$args->{'one_time'}) {
4498: &appenv(\%envhash);
4499: }
4500: return %returnhash;
4501: }
4502:
4503: sub update_released_required {
4504: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4505: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4506: $cid = $env{'request.course.id'};
4507: $cdom = $env{'course.'.$cid.'.domain'};
4508: $cnum = $env{'course.'.$cid.'.num'};
4509: $chome = $env{'course.'.$cid.'.home'};
4510: }
4511: if ($needsrelease) {
4512: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4513: my $needsupdate;
4514: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4515: $needsupdate = 1;
4516: } else {
4517: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4518: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4519: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4520: $needsupdate = 1;
4521: }
4522: }
4523: if ($needsupdate) {
4524: my %needshash = (
4525: 'internal.releaserequired' => $needsrelease,
4526: );
4527: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4528: if ($putresult eq 'ok') {
4529: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4530: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4531: if (ref($crsinfo{$cid}) eq 'HASH') {
4532: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4533: &courseidput($cdom,\%crsinfo,$chome,'notime');
4534: }
4535: }
4536: }
4537: }
4538: return;
4539: }
4540:
4541: # -------------------------------------------------See if a user is privileged
4542:
4543: sub privileged {
4544: my ($username,$domain)=@_;
4545: my $rolesdump=&reply("dump:$domain:$username:roles",
4546: &homeserver($username,$domain));
4547: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4548: ($rolesdump =~ /^error:/)) {
4549: return 0;
4550: }
4551: my $now=time;
4552: if ($rolesdump ne '') {
4553: foreach my $entry (split(/&/,$rolesdump)) {
4554: if ($entry!~/^rolesdef_/) {
4555: my ($area,$role)=split(/=/,$entry);
4556: $area=~s/\_\w\w$//;
4557: my ($trole,$tend,$tstart)=split(/_/,$role);
4558: if (($trole eq 'dc') || ($trole eq 'su')) {
4559: my $active=1;
4560: if ($tend) {
4561: if ($tend<$now) { $active=0; }
4562: }
4563: if ($tstart) {
4564: if ($tstart>$now) { $active=0; }
4565: }
4566: if ($active) { return 1; }
4567: }
4568: }
4569: }
4570: }
4571: return 0;
4572: }
4573:
4574: # -------------------------------------------------------- Get user privileges
4575:
4576: sub rolesinit {
4577: my ($domain,$username,$authhost)=@_;
4578: my $now=time;
4579: my %userroles = ('user.login.time' => $now);
4580: my $extra = &freeze_escape({'skipcheck' => 1});
4581: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
4582: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4583: ($rolesdump =~ /^error:/)) {
4584: return \%userroles;
4585: }
4586: my %firstaccess = &dump('firstaccesstimes',$domain,$username);
4587: my %timerinterval = &dump('timerinterval',$domain,$username);
4588: my (%coursetimerstarts,%firstaccchk,%firstaccenv,
4589: %coursetimerintervals,%timerintchk,%timerintenv);
4590: foreach my $key (keys(%firstaccess)) {
4591: my ($cid,$rest) = split(/\0/,$key);
4592: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4593: }
4594: foreach my $key (keys(%timerinterval)) {
4595: my ($cid,$rest) = split(/\0/,$key);
4596: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4597: }
4598: my %allroles=();
4599: my %allgroups=();
4600:
4601: if ($rolesdump ne '') {
4602: foreach my $entry (split(/&/,$rolesdump)) {
4603: if ($entry!~/^rolesdef_/) {
4604: my ($area,$role)=split(/=/,$entry);
4605: $area=~s/\_\w\w$//;
4606: my ($trole,$tend,$tstart,$group_privs);
4607: if ($role=~/^cr/) {
4608: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4609: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
4610: ($tend,$tstart)=split('_',$trest);
4611: } else {
4612: $trole=$role;
4613: }
4614: } elsif ($role =~ m|^gr/|) {
4615: ($trole,$tend,$tstart) = split(/_/,$role);
4616: next if ($tstart eq '-1');
4617: ($trole,$group_privs) = split(/\//,$trole);
4618: $group_privs = &unescape($group_privs);
4619: } else {
4620: ($trole,$tend,$tstart)=split(/_/,$role);
4621: }
4622: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4623: $username);
4624: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4625: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4626: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
4627: if (($area ne '') && ($trole ne '')) {
4628: my $spec=$trole.'.'.$area;
4629: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4630: if ($trole =~ /^cr\//) {
4631: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4632: } elsif ($trole eq 'gr') {
4633: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4634: } else {
4635: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4636: }
4637: if ($trole ne 'gr') {
4638: my $cid = $tdomain.'_'.$trest;
4639: unless ($firstaccchk{$cid}) {
4640: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4641: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4642: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4643: $coursetimerstarts{$cid}{$item};
4644: }
4645: }
4646: $firstaccchk{$cid} = 1;
4647: }
4648: unless ($timerintchk{$cid}) {
4649: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4650: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4651: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4652: $coursetimerintervals{$cid}{$item};
4653: }
4654: }
4655: $timerintchk{$cid} = 1;
4656: }
4657: }
4658: }
4659: }
4660: }
4661: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4662: $userroles{'user.adv'} = $adv;
4663: $userroles{'user.author'} = $author;
4664: $env{'user.adv'}=$adv;
4665: }
4666: return (\%userroles,\%firstaccenv,\%timerintenv);
4667: }
4668:
4669: sub set_arearole {
4670: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4671: # log the associated role with the area
4672: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4673: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4674: }
4675:
4676: sub custom_roleprivs {
4677: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4678: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4679: my $homsvr=homeserver($rauthor,$rdomain);
4680: if (&hostname($homsvr) ne '') {
4681: my ($rdummy,$roledef)=
4682: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4683: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4684: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4685: if (defined($syspriv)) {
4686: if ($trest =~ /^$match_community$/) {
4687: $syspriv =~ s/bre\&S//;
4688: }
4689: $$allroles{'cm./'}.=':'.$syspriv;
4690: $$allroles{$spec.'./'}.=':'.$syspriv;
4691: }
4692: if ($tdomain ne '') {
4693: if (defined($dompriv)) {
4694: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4695: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4696: }
4697: if (($trest ne '') && (defined($coursepriv))) {
4698: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4699: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4700: }
4701: }
4702: }
4703: }
4704: }
4705:
4706: sub group_roleprivs {
4707: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4708: my $access = 1;
4709: my $now = time;
4710: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4711: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4712: if ($access) {
4713: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4714: $$allgroups{$course}{$group} .=':'.$group_privs;
4715: }
4716: }
4717:
4718: sub standard_roleprivs {
4719: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4720: if (defined($pr{$trole.':s'})) {
4721: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4722: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4723: }
4724: if ($tdomain ne '') {
4725: if (defined($pr{$trole.':d'})) {
4726: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4727: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4728: }
4729: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4730: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4731: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4732: }
4733: }
4734: }
4735:
4736: sub set_userprivs {
4737: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4738: my $author=0;
4739: my $adv=0;
4740: my %grouproles = ();
4741: if (keys(%{$allgroups}) > 0) {
4742: my @groupkeys;
4743: foreach my $role (keys(%{$allroles})) {
4744: push(@groupkeys,$role);
4745: }
4746: if (ref($groups_roles) eq 'HASH') {
4747: foreach my $key (keys(%{$groups_roles})) {
4748: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4749: push(@groupkeys,$key);
4750: }
4751: }
4752: }
4753: if (@groupkeys > 0) {
4754: foreach my $role (@groupkeys) {
4755: my ($trole,$area,$sec,$extendedarea);
4756: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4757: $trole = $1;
4758: $area = $2;
4759: $sec = $3;
4760: $extendedarea = $area.$sec;
4761: if (exists($$allgroups{$area})) {
4762: foreach my $group (keys(%{$$allgroups{$area}})) {
4763: my $spec = $trole.'.'.$extendedarea;
4764: $grouproles{$spec.'.'.$area.'/'.$group} =
4765: $$allgroups{$area}{$group};
4766: }
4767: }
4768: }
4769: }
4770: }
4771: }
4772: foreach my $group (keys(%grouproles)) {
4773: $$allroles{$group} = $grouproles{$group};
4774: }
4775: foreach my $role (keys(%{$allroles})) {
4776: my %thesepriv;
4777: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4778: foreach my $item (split(/:/,$$allroles{$role})) {
4779: if ($item ne '') {
4780: my ($privilege,$restrictions)=split(/&/,$item);
4781: if ($restrictions eq '') {
4782: $thesepriv{$privilege}='F';
4783: } elsif ($thesepriv{$privilege} ne 'F') {
4784: $thesepriv{$privilege}.=$restrictions;
4785: }
4786: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4787: }
4788: }
4789: my $thesestr='';
4790: foreach my $priv (sort(keys(%thesepriv))) {
4791: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4792: }
4793: $userroles->{'user.priv.'.$role} = $thesestr;
4794: }
4795: return ($author,$adv);
4796: }
4797:
4798: sub role_status {
4799: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4800: my @pwhere = ();
4801: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4802: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4803: unless (!defined($$role) || $$role eq '') {
4804: $$where=join('.',@pwhere);
4805: $$trolecode=$$role.'.'.$$where;
4806: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4807: $$tstatus='is';
4808: if ($$tstart && $$tstart>$update) {
4809: $$tstatus='future';
4810: if ($$tstart<$now) {
4811: if ($$tstart && $$tstart>$refresh) {
4812: if (($$where ne '') && ($$role ne '')) {
4813: my (%allroles,%allgroups,$group_privs,
4814: %groups_roles,@rolecodes);
4815: my %userroles = (
4816: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4817: );
4818: @rolecodes = ('cm');
4819: my $spec=$$role.'.'.$$where;
4820: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4821: if ($$role =~ /^cr\//) {
4822: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4823: push(@rolecodes,'cr');
4824: } elsif ($$role eq 'gr') {
4825: push(@rolecodes,$$role);
4826: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4827: $env{'user.name'});
4828: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4829: (undef,my $group_privs) = split(/\//,$trole);
4830: $group_privs = &unescape($group_privs);
4831: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4832: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4833: &get_groups_roles($tdomain,$trest,
4834: \%course_roles,\@rolecodes,
4835: \%groups_roles);
4836: } else {
4837: push(@rolecodes,$$role);
4838: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4839: }
4840: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4841: &appenv(\%userroles,\@rolecodes);
4842: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4843: }
4844: }
4845: $$tstatus = 'is';
4846: }
4847: }
4848: if ($$tend) {
4849: if ($$tend<$update) {
4850: $$tstatus='expired';
4851: } elsif ($$tend<$now) {
4852: $$tstatus='will_not';
4853: }
4854: }
4855: }
4856: }
4857: }
4858:
4859: sub get_groups_roles {
4860: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4861: return unless((ref($cdom_courseroles) eq 'HASH') &&
4862: (ref($rolecodes) eq 'ARRAY') &&
4863: (ref($groups_roles) eq 'HASH'));
4864: if (keys(%{$cdom_courseroles}) > 0) {
4865: my ($cnum) = ($rest =~ /^($match_courseid)/);
4866: if ($cdom ne '' && $cnum ne '') {
4867: foreach my $key (keys(%{$cdom_courseroles})) {
4868: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4869: my $crsrole = $1;
4870: my $crssec = $2;
4871: if ($crsrole =~ /^cr/) {
4872: unless (grep(/^cr$/,@{$rolecodes})) {
4873: push(@{$rolecodes},'cr');
4874: }
4875: } else {
4876: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4877: push(@{$rolecodes},$crsrole);
4878: }
4879: }
4880: my $rolekey = "$crsrole./$cdom/$cnum";
4881: if ($crssec ne '') {
4882: $rolekey .= "/$crssec";
4883: }
4884: $rolekey .= './';
4885: $groups_roles->{$rolekey} = $rolecodes;
4886: }
4887: }
4888: }
4889: }
4890: return;
4891: }
4892:
4893: sub delete_env_groupprivs {
4894: my ($where,$courseroles,$possroles) = @_;
4895: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4896: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4897: unless (ref($courseroles->{$udom}) eq 'HASH') {
4898: %{$courseroles->{$udom}} =
4899: &get_my_roles('','','userroles',['active'],
4900: $possroles,[$udom],1);
4901: }
4902: if (ref($courseroles->{$udom}) eq 'HASH') {
4903: foreach my $item (keys(%{$courseroles->{$udom}})) {
4904: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4905: my $area = '/'.$cdom.'/'.$cnum;
4906: my $privkey = "user.priv.$crsrole.$area";
4907: if ($crssec ne '') {
4908: $privkey .= '/'.$crssec;
4909: }
4910: $privkey .= ".$area/$group";
4911: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4912: }
4913: }
4914: return;
4915: }
4916:
4917: sub check_adhoc_privs {
4918: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
4919: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4920: if ($env{$cckey}) {
4921: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4922: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4923: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4924: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4925: }
4926: } else {
4927: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4928: }
4929: }
4930:
4931: sub set_adhoc_privileges {
4932: # role can be cc or ca
4933: my ($dcdom,$pickedcourse,$role,$caller) = @_;
4934: my $area = '/'.$dcdom.'/'.$pickedcourse;
4935: my $spec = $role.'.'.$area;
4936: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4937: $env{'user.name'});
4938: my %ccrole = ();
4939: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4940: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4941: &appenv(\%userroles,[$role,'cm']);
4942: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4943: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4944: &appenv( {'request.role' => $spec,
4945: 'request.role.domain' => $dcdom,
4946: 'request.course.sec' => ''
4947: }
4948: );
4949: my $tadv=0;
4950: if (&allowed('adv') eq 'F') { $tadv=1; }
4951: &appenv({'request.role.adv' => $tadv});
4952: }
4953: }
4954:
4955: # --------------------------------------------------------------- get interface
4956:
4957: sub get {
4958: my ($namespace,$storearr,$udomain,$uname)=@_;
4959: my $items='';
4960: foreach my $item (@$storearr) {
4961: $items.=&escape($item).'&';
4962: }
4963: $items=~s/\&$//;
4964: if (!$udomain) { $udomain=$env{'user.domain'}; }
4965: if (!$uname) { $uname=$env{'user.name'}; }
4966: my $uhome=&homeserver($uname,$udomain);
4967:
4968: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4969: my @pairs=split(/\&/,$rep);
4970: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4971: return @pairs;
4972: }
4973: my %returnhash=();
4974: my $i=0;
4975: foreach my $item (@$storearr) {
4976: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4977: $i++;
4978: }
4979: return %returnhash;
4980: }
4981:
4982: # --------------------------------------------------------------- del interface
4983:
4984: sub del {
4985: my ($namespace,$storearr,$udomain,$uname)=@_;
4986: my $items='';
4987: foreach my $item (@$storearr) {
4988: $items.=&escape($item).'&';
4989: }
4990:
4991: $items=~s/\&$//;
4992: if (!$udomain) { $udomain=$env{'user.domain'}; }
4993: if (!$uname) { $uname=$env{'user.name'}; }
4994: my $uhome=&homeserver($uname,$udomain);
4995: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4996: }
4997:
4998: # -------------------------------------------------------------- dump interface
4999:
5000: sub dump {
5001: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
5002: if (!$udomain) { $udomain=$env{'user.domain'}; }
5003: if (!$uname) { $uname=$env{'user.name'}; }
5004: my $uhome=&homeserver($uname,$udomain);
5005: if ($regexp) {
5006: $regexp=&escape($regexp);
5007: } else {
5008: $regexp='.';
5009: }
5010: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
5011: my @pairs=split(/\&/,$rep);
5012: my %returnhash=();
5013: if (!($rep =~ /^error/ )) {
5014: foreach my $item (@pairs) {
5015: my ($key,$value)=split(/=/,$item,2);
5016: $key = &unescape($key);
5017: next if ($key =~ /^error: 2 /);
5018: $returnhash{$key}=&thaw_unescape($value);
5019: }
5020: }
5021: return %returnhash;
5022: }
5023:
5024:
5025: # --------------------------------------------------------- dumpstore interface
5026:
5027: sub dumpstore {
5028: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5029: if (!$udomain) { $udomain=$env{'user.domain'}; }
5030: if (!$uname) { $uname=$env{'user.name'}; }
5031: my $uhome=&homeserver($uname,$udomain);
5032: if ($regexp) {
5033: $regexp=&escape($regexp);
5034: } else {
5035: $regexp='.';
5036: }
5037: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5038: my @pairs=split(/\&/,$rep);
5039: my %returnhash=();
5040: foreach my $item (@pairs) {
5041: my ($key,$value)=split(/=/,$item,2);
5042: next if ($key =~ /^error: 2 /);
5043: $returnhash{$key}=&thaw_unescape($value);
5044: }
5045: return %returnhash;
5046: }
5047:
5048: # -------------------------------------------------------------- keys interface
5049:
5050: sub getkeys {
5051: my ($namespace,$udomain,$uname)=@_;
5052: if (!$udomain) { $udomain=$env{'user.domain'}; }
5053: if (!$uname) { $uname=$env{'user.name'}; }
5054: my $uhome=&homeserver($uname,$udomain);
5055: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5056: my @keyarray=();
5057: foreach my $key (split(/\&/,$rep)) {
5058: next if ($key =~ /^error: 2 /);
5059: push(@keyarray,&unescape($key));
5060: }
5061: return @keyarray;
5062: }
5063:
5064: # --------------------------------------------------------------- currentdump
5065: sub currentdump {
5066: my ($courseid,$sdom,$sname)=@_;
5067: $courseid = $env{'request.course.id'} if (! defined($courseid));
5068: $sdom = $env{'user.domain'} if (! defined($sdom));
5069: $sname = $env{'user.name'} if (! defined($sname));
5070: my $uhome = &homeserver($sname,$sdom);
5071: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5072: return if ($rep =~ /^(error:|no_such_host)/);
5073: #
5074: my %returnhash=();
5075: #
5076: if ($rep eq "unknown_cmd") {
5077: # an old lond will not know currentdump
5078: # Do a dump and make it look like a currentdump
5079: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5080: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5081: my %hash = @tmp;
5082: @tmp=();
5083: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5084: } else {
5085: my @pairs=split(/\&/,$rep);
5086: foreach my $pair (@pairs) {
5087: my ($key,$value)=split(/=/,$pair,2);
5088: my ($symb,$param) = split(/:/,$key);
5089: $returnhash{&unescape($symb)}->{&unescape($param)} =
5090: &thaw_unescape($value);
5091: }
5092: }
5093: return %returnhash;
5094: }
5095:
5096: sub convert_dump_to_currentdump{
5097: my %hash = %{shift()};
5098: my %returnhash;
5099: # Code ripped from lond, essentially. The only difference
5100: # here is the unescaping done by lonnet::dump(). Conceivably
5101: # we might run in to problems with parameter names =~ /^v\./
5102: while (my ($key,$value) = each(%hash)) {
5103: my ($v,$symb,$param) = split(/:/,$key);
5104: $symb = &unescape($symb);
5105: $param = &unescape($param);
5106: next if ($v eq 'version' || $symb eq 'keys');
5107: next if (exists($returnhash{$symb}) &&
5108: exists($returnhash{$symb}->{$param}) &&
5109: $returnhash{$symb}->{'v.'.$param} > $v);
5110: $returnhash{$symb}->{$param}=$value;
5111: $returnhash{$symb}->{'v.'.$param}=$v;
5112: }
5113: #
5114: # Remove all of the keys in the hashes which keep track of
5115: # the version of the parameter.
5116: while (my ($symb,$param_hash) = each(%returnhash)) {
5117: # use a foreach because we are going to delete from the hash.
5118: foreach my $key (keys(%$param_hash)) {
5119: delete($param_hash->{$key}) if ($key =~ /^v\./);
5120: }
5121: }
5122: return \%returnhash;
5123: }
5124:
5125: # ------------------------------------------------------ critical inc interface
5126:
5127: sub cinc {
5128: return &inc(@_,'critical');
5129: }
5130:
5131: # --------------------------------------------------------------- inc interface
5132:
5133: sub inc {
5134: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5135: if (!$udomain) { $udomain=$env{'user.domain'}; }
5136: if (!$uname) { $uname=$env{'user.name'}; }
5137: my $uhome=&homeserver($uname,$udomain);
5138: my $items='';
5139: if (! ref($store)) {
5140: # got a single value, so use that instead
5141: $items = &escape($store).'=&';
5142: } elsif (ref($store) eq 'SCALAR') {
5143: $items = &escape($$store).'=&';
5144: } elsif (ref($store) eq 'ARRAY') {
5145: $items = join('=&',map {&escape($_);} @{$store});
5146: } elsif (ref($store) eq 'HASH') {
5147: while (my($key,$value) = each(%{$store})) {
5148: $items.= &escape($key).'='.&escape($value).'&';
5149: }
5150: }
5151: $items=~s/\&$//;
5152: if ($critical) {
5153: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5154: } else {
5155: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5156: }
5157: }
5158:
5159: # --------------------------------------------------------------- put interface
5160:
5161: sub put {
5162: my ($namespace,$storehash,$udomain,$uname)=@_;
5163: if (!$udomain) { $udomain=$env{'user.domain'}; }
5164: if (!$uname) { $uname=$env{'user.name'}; }
5165: my $uhome=&homeserver($uname,$udomain);
5166: my $items='';
5167: foreach my $item (keys(%$storehash)) {
5168: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5169: }
5170: $items=~s/\&$//;
5171: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5172: }
5173:
5174: # ------------------------------------------------------------ newput interface
5175:
5176: sub newput {
5177: my ($namespace,$storehash,$udomain,$uname)=@_;
5178: if (!$udomain) { $udomain=$env{'user.domain'}; }
5179: if (!$uname) { $uname=$env{'user.name'}; }
5180: my $uhome=&homeserver($uname,$udomain);
5181: my $items='';
5182: foreach my $key (keys(%$storehash)) {
5183: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5184: }
5185: $items=~s/\&$//;
5186: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5187: }
5188:
5189: # --------------------------------------------------------- putstore interface
5190:
5191: sub putstore {
5192: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5193: if (!$udomain) { $udomain=$env{'user.domain'}; }
5194: if (!$uname) { $uname=$env{'user.name'}; }
5195: my $uhome=&homeserver($uname,$udomain);
5196: my $items='';
5197: foreach my $key (keys(%$storehash)) {
5198: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5199: }
5200: $items=~s/\&$//;
5201: my $esc_symb=&escape($symb);
5202: my $esc_v=&escape($version);
5203: my $reply =
5204: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5205: $uhome);
5206: if ($reply eq 'unknown_cmd') {
5207: # gfall back to way things use to be done
5208: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5209: $uname);
5210: }
5211: return $reply;
5212: }
5213:
5214: sub old_putstore {
5215: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5216: if (!$udomain) { $udomain=$env{'user.domain'}; }
5217: if (!$uname) { $uname=$env{'user.name'}; }
5218: my $uhome=&homeserver($uname,$udomain);
5219: my %newstorehash;
5220: foreach my $item (keys(%$storehash)) {
5221: my $key = $version.':'.&escape($symb).':'.$item;
5222: $newstorehash{$key} = $storehash->{$item};
5223: }
5224: my $items='';
5225: my %allitems = ();
5226: foreach my $item (keys(%newstorehash)) {
5227: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5228: my $key = $1.':keys:'.$2;
5229: $allitems{$key} .= $3.':';
5230: }
5231: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5232: }
5233: foreach my $item (keys(%allitems)) {
5234: $allitems{$item} =~ s/\:$//;
5235: $items.= $item.'='.$allitems{$item}.'&';
5236: }
5237: $items=~s/\&$//;
5238: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5239: }
5240:
5241: # ------------------------------------------------------ critical put interface
5242:
5243: sub cput {
5244: my ($namespace,$storehash,$udomain,$uname)=@_;
5245: if (!$udomain) { $udomain=$env{'user.domain'}; }
5246: if (!$uname) { $uname=$env{'user.name'}; }
5247: my $uhome=&homeserver($uname,$udomain);
5248: my $items='';
5249: foreach my $item (keys(%$storehash)) {
5250: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5251: }
5252: $items=~s/\&$//;
5253: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5254: }
5255:
5256: # -------------------------------------------------------------- eget interface
5257:
5258: sub eget {
5259: my ($namespace,$storearr,$udomain,$uname)=@_;
5260: my $items='';
5261: foreach my $item (@$storearr) {
5262: $items.=&escape($item).'&';
5263: }
5264: $items=~s/\&$//;
5265: if (!$udomain) { $udomain=$env{'user.domain'}; }
5266: if (!$uname) { $uname=$env{'user.name'}; }
5267: my $uhome=&homeserver($uname,$udomain);
5268: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5269: my @pairs=split(/\&/,$rep);
5270: my %returnhash=();
5271: my $i=0;
5272: foreach my $item (@$storearr) {
5273: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5274: $i++;
5275: }
5276: return %returnhash;
5277: }
5278:
5279: # ------------------------------------------------------------ tmpput interface
5280: sub tmpput {
5281: my ($storehash,$server,$context)=@_;
5282: my $items='';
5283: foreach my $item (keys(%$storehash)) {
5284: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5285: }
5286: $items=~s/\&$//;
5287: if (defined($context)) {
5288: $items .= ':'.&escape($context);
5289: }
5290: return &reply("tmpput:$items",$server);
5291: }
5292:
5293: # ------------------------------------------------------------ tmpget interface
5294: sub tmpget {
5295: my ($token,$server)=@_;
5296: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5297: my $rep=&reply("tmpget:$token",$server);
5298: my %returnhash;
5299: foreach my $item (split(/\&/,$rep)) {
5300: my ($key,$value)=split(/=/,$item);
5301: next if ($key =~ /^error: 2 /);
5302: $returnhash{&unescape($key)}=&thaw_unescape($value);
5303: }
5304: return %returnhash;
5305: }
5306:
5307: # ------------------------------------------------------------ tmpdel interface
5308: sub tmpdel {
5309: my ($token,$server)=@_;
5310: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5311: return &reply("tmpdel:$token",$server);
5312: }
5313:
5314: # -------------------------------------------------- portfolio access checking
5315:
5316: sub portfolio_access {
5317: my ($requrl) = @_;
5318: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5319: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5320: if ($result) {
5321: my %setters;
5322: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5323: my ($startblock,$endblock) =
5324: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5325: if ($startblock && $endblock) {
5326: return 'B';
5327: }
5328: } else {
5329: my ($startblock,$endblock) =
5330: &Apache::loncommon::blockcheck(\%setters,'port');
5331: if ($startblock && $endblock) {
5332: return 'B';
5333: }
5334: }
5335: }
5336: if ($result eq 'ok') {
5337: return 'F';
5338: } elsif ($result =~ /^[^:]+:guest_/) {
5339: return 'A';
5340: }
5341: return '';
5342: }
5343:
5344: sub get_portfolio_access {
5345: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5346:
5347: if (!ref($access_hash)) {
5348: my $current_perms = &get_portfile_permissions($udom,$unum);
5349: my %access_controls = &get_access_controls($current_perms,$group,
5350: $file_name);
5351: $access_hash = $access_controls{$file_name};
5352: }
5353:
5354: my ($public,$guest,@domains,@users,@courses,@groups);
5355: my $now = time;
5356: if (ref($access_hash) eq 'HASH') {
5357: foreach my $key (keys(%{$access_hash})) {
5358: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5359: if ($start > $now) {
5360: next;
5361: }
5362: if ($end && $end<$now) {
5363: next;
5364: }
5365: if ($scope eq 'public') {
5366: $public = $key;
5367: last;
5368: } elsif ($scope eq 'guest') {
5369: $guest = $key;
5370: } elsif ($scope eq 'domains') {
5371: push(@domains,$key);
5372: } elsif ($scope eq 'users') {
5373: push(@users,$key);
5374: } elsif ($scope eq 'course') {
5375: push(@courses,$key);
5376: } elsif ($scope eq 'group') {
5377: push(@groups,$key);
5378: }
5379: }
5380: if ($public) {
5381: return 'ok';
5382: }
5383: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5384: if ($guest) {
5385: return $guest;
5386: }
5387: } else {
5388: if (@domains > 0) {
5389: foreach my $domkey (@domains) {
5390: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5391: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5392: return 'ok';
5393: }
5394: }
5395: }
5396: }
5397: if (@users > 0) {
5398: foreach my $userkey (@users) {
5399: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5400: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5401: if (ref($item) eq 'HASH') {
5402: if (($item->{'uname'} eq $env{'user.name'}) &&
5403: ($item->{'udom'} eq $env{'user.domain'})) {
5404: return 'ok';
5405: }
5406: }
5407: }
5408: }
5409: }
5410: }
5411: my %roleshash;
5412: my @courses_and_groups = @courses;
5413: push(@courses_and_groups,@groups);
5414: if (@courses_and_groups > 0) {
5415: my (%allgroups,%allroles);
5416: my ($start,$end,$role,$sec,$group);
5417: foreach my $envkey (%env) {
5418: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5419: my $cid = $2.'_'.$3;
5420: if ($1 eq 'gr') {
5421: $group = $4;
5422: $allgroups{$cid}{$group} = $env{$envkey};
5423: } else {
5424: if ($4 eq '') {
5425: $sec = 'none';
5426: } else {
5427: $sec = $4;
5428: }
5429: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5430: }
5431: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5432: my $cid = $2.'_'.$3;
5433: if ($4 eq '') {
5434: $sec = 'none';
5435: } else {
5436: $sec = $4;
5437: }
5438: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5439: }
5440: }
5441: if (keys(%allroles) == 0) {
5442: return;
5443: }
5444: foreach my $key (@courses_and_groups) {
5445: my %content = %{$$access_hash{$key}};
5446: my $cnum = $content{'number'};
5447: my $cdom = $content{'domain'};
5448: my $cid = $cdom.'_'.$cnum;
5449: if (!exists($allroles{$cid})) {
5450: next;
5451: }
5452: foreach my $role_id (keys(%{$content{'roles'}})) {
5453: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5454: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5455: my @status = @{$content{'roles'}{$role_id}{'access'}};
5456: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5457: foreach my $role (keys(%{$allroles{$cid}})) {
5458: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5459: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5460: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5461: if (grep/^all$/,@sections) {
5462: return 'ok';
5463: } else {
5464: if (grep/^$sec$/,@sections) {
5465: return 'ok';
5466: }
5467: }
5468: }
5469: }
5470: if (keys(%{$allgroups{$cid}}) == 0) {
5471: if (grep/^none$/,@groups) {
5472: return 'ok';
5473: }
5474: } else {
5475: if (grep/^all$/,@groups) {
5476: return 'ok';
5477: }
5478: foreach my $group (keys(%{$allgroups{$cid}})) {
5479: if (grep/^$group$/,@groups) {
5480: return 'ok';
5481: }
5482: }
5483: }
5484: }
5485: }
5486: }
5487: }
5488: }
5489: if ($guest) {
5490: return $guest;
5491: }
5492: }
5493: }
5494: return;
5495: }
5496:
5497: sub course_group_datechecker {
5498: my ($dates,$now,$status) = @_;
5499: my ($start,$end) = split(/\./,$dates);
5500: if (!$start && !$end) {
5501: return 'ok';
5502: }
5503: if (grep/^active$/,@{$status}) {
5504: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5505: return 'ok';
5506: }
5507: }
5508: if (grep/^previous$/,@{$status}) {
5509: if ($end > $now ) {
5510: return 'ok';
5511: }
5512: }
5513: if (grep/^future$/,@{$status}) {
5514: if ($start > $now) {
5515: return 'ok';
5516: }
5517: }
5518: return;
5519: }
5520:
5521: sub parse_portfolio_url {
5522: my ($url) = @_;
5523:
5524: my ($type,$udom,$unum,$group,$file_name);
5525:
5526: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5527: $type = 1;
5528: $udom = $1;
5529: $unum = $2;
5530: $file_name = $3;
5531: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5532: $type = 2;
5533: $udom = $1;
5534: $unum = $2;
5535: $group = $3;
5536: $file_name = $3.'/'.$4;
5537: }
5538: if (wantarray) {
5539: return ($type,$udom,$unum,$file_name,$group);
5540: }
5541: return $type;
5542: }
5543:
5544: sub is_portfolio_url {
5545: my ($url) = @_;
5546: return scalar(&parse_portfolio_url($url));
5547: }
5548:
5549: sub is_portfolio_file {
5550: my ($file) = @_;
5551: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5552: return 1;
5553: }
5554: return;
5555: }
5556:
5557: sub usertools_access {
5558: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
5559: my ($access,%tools);
5560: if ($context eq '') {
5561: $context = 'tools';
5562: }
5563: if ($context eq 'requestcourses') {
5564: %tools = (
5565: official => 1,
5566: unofficial => 1,
5567: community => 1,
5568: );
5569: } else {
5570: %tools = (
5571: aboutme => 1,
5572: blog => 1,
5573: portfolio => 1,
5574: );
5575: }
5576: return if (!defined($tools{$tool}));
5577:
5578: if ((!defined($udom)) || (!defined($uname))) {
5579: $udom = $env{'user.domain'};
5580: $uname = $env{'user.name'};
5581: }
5582:
5583: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5584: if ($action ne 'reload') {
5585: if ($context eq 'requestcourses') {
5586: return $env{'environment.canrequest.'.$tool};
5587: } else {
5588: return $env{'environment.availabletools.'.$tool};
5589: }
5590: }
5591: }
5592:
5593: my ($toolstatus,$inststatus);
5594:
5595: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5596: ($action ne 'reload')) {
5597: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5598: $inststatus = $env{'environment.inststatus'};
5599: } else {
5600: if (ref($userenvref) eq 'HASH') {
5601: $toolstatus = $userenvref->{$context.'.'.$tool};
5602: $inststatus = $userenvref->{'inststatus'};
5603: } else {
5604: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5605: $toolstatus = $userenv{$context.'.'.$tool};
5606: $inststatus = $userenv{'inststatus'};
5607: }
5608: }
5609:
5610: if ($toolstatus ne '') {
5611: if ($toolstatus) {
5612: $access = 1;
5613: } else {
5614: $access = 0;
5615: }
5616: return $access;
5617: }
5618:
5619: my ($is_adv,%domdef);
5620: if (ref($is_advref) eq 'HASH') {
5621: $is_adv = $is_advref->{'is_adv'};
5622: } else {
5623: $is_adv = &is_advanced_user($udom,$uname);
5624: }
5625: if (ref($domdefref) eq 'HASH') {
5626: %domdef = %{$domdefref};
5627: } else {
5628: %domdef = &get_domain_defaults($udom);
5629: }
5630: if (ref($domdef{$tool}) eq 'HASH') {
5631: if ($is_adv) {
5632: if ($domdef{$tool}{'_LC_adv'} ne '') {
5633: if ($domdef{$tool}{'_LC_adv'}) {
5634: $access = 1;
5635: } else {
5636: $access = 0;
5637: }
5638: return $access;
5639: }
5640: }
5641: if ($inststatus ne '') {
5642: my ($hasaccess,$hasnoaccess);
5643: foreach my $affiliation (split(/:/,$inststatus)) {
5644: if ($domdef{$tool}{$affiliation} ne '') {
5645: if ($domdef{$tool}{$affiliation}) {
5646: $hasaccess = 1;
5647: } else {
5648: $hasnoaccess = 1;
5649: }
5650: }
5651: }
5652: if ($hasaccess || $hasnoaccess) {
5653: if ($hasaccess) {
5654: $access = 1;
5655: } elsif ($hasnoaccess) {
5656: $access = 0;
5657: }
5658: return $access;
5659: }
5660: } else {
5661: if ($domdef{$tool}{'default'} ne '') {
5662: if ($domdef{$tool}{'default'}) {
5663: $access = 1;
5664: } elsif ($domdef{$tool}{'default'} == 0) {
5665: $access = 0;
5666: }
5667: return $access;
5668: }
5669: }
5670: } else {
5671: if ($context eq 'tools') {
5672: $access = 1;
5673: } else {
5674: $access = 0;
5675: }
5676: return $access;
5677: }
5678: }
5679:
5680: sub is_course_owner {
5681: my ($cdom,$cnum,$udom,$uname) = @_;
5682: if (($udom eq '') || ($uname eq '')) {
5683: $udom = $env{'user.domain'};
5684: $uname = $env{'user.name'};
5685: }
5686: unless (($udom eq '') || ($uname eq '')) {
5687: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5688: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5689: return 1;
5690: } else {
5691: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5692: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5693: return 1;
5694: }
5695: }
5696: }
5697: }
5698: return;
5699: }
5700:
5701: sub is_advanced_user {
5702: my ($udom,$uname) = @_;
5703: if ($udom ne '' && $uname ne '') {
5704: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5705: if (wantarray) {
5706: return ($env{'user.adv'},$env{'user.author'});
5707: } else {
5708: return $env{'user.adv'};
5709: }
5710: }
5711: }
5712: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5713: my %allroles;
5714: my ($is_adv,$is_author);
5715: foreach my $role (keys(%roleshash)) {
5716: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5717: my $area = '/'.$tdomain.'/'.$trest;
5718: if ($sec ne '') {
5719: $area .= '/'.$sec;
5720: }
5721: if (($area ne '') && ($trole ne '')) {
5722: my $spec=$trole.'.'.$area;
5723: if ($trole =~ /^cr\//) {
5724: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5725: } elsif ($trole ne 'gr') {
5726: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5727: }
5728: if ($trole eq 'au') {
5729: $is_author = 1;
5730: }
5731: }
5732: }
5733: foreach my $role (keys(%allroles)) {
5734: last if ($is_adv);
5735: foreach my $item (split(/:/,$allroles{$role})) {
5736: if ($item ne '') {
5737: my ($privilege,$restrictions)=split(/&/,$item);
5738: if ($privilege eq 'adv') {
5739: $is_adv = 1;
5740: last;
5741: }
5742: }
5743: }
5744: }
5745: if (wantarray) {
5746: return ($is_adv,$is_author);
5747: }
5748: return $is_adv;
5749: }
5750:
5751: sub check_can_request {
5752: my ($dom,$can_request,$request_domains) = @_;
5753: my $canreq = 0;
5754: my ($types,$typename) = &Apache::loncommon::course_types();
5755: my @options = ('approval','validate','autolimit');
5756: my $optregex = join('|',@options);
5757: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5758: foreach my $type (@{$types}) {
5759: if (&usertools_access($env{'user.name'},
5760: $env{'user.domain'},
5761: $type,undef,'requestcourses')) {
5762: $canreq ++;
5763: if (ref($request_domains) eq 'HASH') {
5764: push(@{$request_domains->{$type}},$env{'user.domain'});
5765: }
5766: if ($dom eq $env{'user.domain'}) {
5767: $can_request->{$type} = 1;
5768: }
5769: }
5770: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5771: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5772: if (@curr > 0) {
5773: foreach my $item (@curr) {
5774: if (ref($request_domains) eq 'HASH') {
5775: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5776: if ($otherdom ne '') {
5777: if (ref($request_domains->{$type}) eq 'ARRAY') {
5778: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5779: push(@{$request_domains->{$type}},$otherdom);
5780: }
5781: } else {
5782: push(@{$request_domains->{$type}},$otherdom);
5783: }
5784: }
5785: }
5786: }
5787: unless($dom eq $env{'user.domain'}) {
5788: $canreq ++;
5789: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5790: $can_request->{$type} = 1;
5791: }
5792: }
5793: }
5794: }
5795: }
5796: }
5797: return $canreq;
5798: }
5799:
5800: # ---------------------------------------------- Custom access rule evaluation
5801:
5802: sub customaccess {
5803: my ($priv,$uri)=@_;
5804: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5805: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5806: $udom = &LONCAPA::clean_domain($udom);
5807: $ucrs = &LONCAPA::clean_username($ucrs);
5808: my $access=0;
5809: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5810: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5811: if ($type eq 'user') {
5812: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5813: my ($tdom,$tuname)=split(m{/},$scope);
5814: if ($tdom) {
5815: if ($tdom ne $env{'user.domain'}) { next; }
5816: }
5817: if ($tuname) {
5818: if ($tuname ne $env{'user.name'}) { next; }
5819: }
5820: $access=($effect eq 'allow');
5821: last;
5822: }
5823: } else {
5824: if ($role) {
5825: if ($role ne $urole) { next; }
5826: }
5827: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5828: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5829: if ($tdom) {
5830: if ($tdom ne $udom) { next; }
5831: }
5832: if ($tcrs) {
5833: if ($tcrs ne $ucrs) { next; }
5834: }
5835: if ($tsec) {
5836: if ($tsec ne $usec) { next; }
5837: }
5838: $access=($effect eq 'allow');
5839: last;
5840: }
5841: if ($realm eq '' && $role eq '') {
5842: $access=($effect eq 'allow');
5843: }
5844: }
5845: }
5846: return $access;
5847: }
5848:
5849: # ------------------------------------------------- Check for a user privilege
5850:
5851: sub allowed {
5852: my ($priv,$uri,$symb,$role)=@_;
5853: my $ver_orguri=$uri;
5854: $uri=&deversion($uri);
5855: my $orguri=$uri;
5856: $uri=&declutter($uri);
5857:
5858: if ($priv eq 'evb') {
5859: # Evade communication block restrictions for specified role in a course
5860: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5861: return $1;
5862: } else {
5863: return;
5864: }
5865: }
5866:
5867: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5868: # Free bre access to adm and meta resources
5869: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5870: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5871: && ($priv eq 'bre')) {
5872: return 'F';
5873: }
5874:
5875: # Free bre access to user's own portfolio contents
5876: my ($space,$domain,$name,@dir)=split('/',$uri);
5877: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5878: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5879: my %setters;
5880: my ($startblock,$endblock) =
5881: &Apache::loncommon::blockcheck(\%setters,'port');
5882: if ($startblock && $endblock) {
5883: return 'B';
5884: } else {
5885: return 'F';
5886: }
5887: }
5888:
5889: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5890: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5891: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5892: if (exists($env{'request.course.id'})) {
5893: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5894: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5895: if (($domain eq $cdom) && ($name eq $cnum)) {
5896: my $courseprivid=$env{'request.course.id'};
5897: $courseprivid=~s/\_/\//;
5898: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5899: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5900: return $1;
5901: } else {
5902: if ($env{'request.course.sec'}) {
5903: $courseprivid.='/'.$env{'request.course.sec'};
5904: }
5905: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5906: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5907: return $2;
5908: }
5909: }
5910: }
5911: }
5912: }
5913:
5914: # Free bre to public access
5915:
5916: if ($priv eq 'bre') {
5917: my $copyright=&metadata($uri,'copyright');
5918: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5919: return 'F';
5920: }
5921: if ($copyright eq 'priv') {
5922: $uri=~/([^\/]+)\/([^\/]+)\//;
5923: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5924: return '';
5925: }
5926: }
5927: if ($copyright eq 'domain') {
5928: $uri=~/([^\/]+)\/([^\/]+)\//;
5929: unless (($env{'user.domain'} eq $1) ||
5930: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5931: return '';
5932: }
5933: }
5934: if ($env{'request.role'}=~ /li\.\//) {
5935: # Library role, so allow browsing of resources in this domain.
5936: return 'F';
5937: }
5938: if ($copyright eq 'custom') {
5939: unless (&customaccess($priv,$uri)) { return ''; }
5940: }
5941: }
5942: # Domain coordinator is trying to create a course
5943: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5944: # uri is the requested domain in this case.
5945: # comparison to 'request.role.domain' shows if the user has selected
5946: # a role of dc for the domain in question.
5947: return 'F' if ($uri eq $env{'request.role.domain'});
5948: }
5949:
5950: my $thisallowed='';
5951: my $statecond=0;
5952: my $courseprivid='';
5953:
5954: my $ownaccess;
5955: # Community Coordinator or Assistant Co-author browsing resource space.
5956: if (($priv eq 'bro') && ($env{'user.author'})) {
5957: if ($uri eq '') {
5958: $ownaccess = 1;
5959: } else {
5960: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5961: my $udom = $env{'user.domain'};
5962: my $uname = $env{'user.name'};
5963: if ($uri =~ m{^\Q$udom\E/?$}) {
5964: $ownaccess = 1;
5965: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
5966: unless ($uri =~ m{\.\./}) {
5967: $ownaccess = 1;
5968: }
5969: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5970: my $now = time;
5971: if ($uri =~ m{^([^/]+)/?$}) {
5972: my $adom = $1;
5973: foreach my $key (keys(%env)) {
5974: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
5975: my ($start,$end) = split('.',$env{$key});
5976: if (($now >= $start) && (!$end || $end < $now)) {
5977: $ownaccess = 1;
5978: last;
5979: }
5980: }
5981: }
5982: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5983: my $adom = $1;
5984: my $aname = $2;
5985: foreach my $role ('ca','aa') {
5986: if ($env{"user.role.$role./$adom/$aname"}) {
5987: my ($start,$end) =
5988: split('.',$env{"user.role.$role./$adom/$aname"});
5989: if (($now >= $start) && (!$end || $end < $now)) {
5990: $ownaccess = 1;
5991: last;
5992: }
5993: }
5994: }
5995: }
5996: }
5997: }
5998: }
5999: }
6000:
6001: # Course
6002:
6003: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6004: unless (($priv eq 'bro') && (!$ownaccess)) {
6005: $thisallowed.=$1;
6006: }
6007: }
6008:
6009: # Domain
6010:
6011: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6012: =~/\Q$priv\E\&([^\:]*)/) {
6013: unless (($priv eq 'bro') && (!$ownaccess)) {
6014: $thisallowed.=$1;
6015: }
6016: }
6017:
6018: # User who is not author or co-author might still be able to edit
6019: # resource of an author in the domain (e.g., if Domain Coordinator).
6020: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6021: (&allowed('mdc',$env{'request.course.id'}))) {
6022: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6023: $thisallowed.=$1;
6024: }
6025: }
6026:
6027: # Course: uri itself is a course
6028: my $courseuri=$uri;
6029: $courseuri=~s/\_(\d)/\/$1/;
6030: $courseuri=~s/^([^\/])/\/$1/;
6031:
6032: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6033: =~/\Q$priv\E\&([^\:]*)/) {
6034: unless (($priv eq 'bro') && (!$ownaccess)) {
6035: $thisallowed.=$1;
6036: }
6037: }
6038:
6039: # URI is an uploaded document for this course, default permissions don't matter
6040: # not allowing 'edit' access (editupload) to uploaded course docs
6041: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6042: $thisallowed='';
6043: my ($match)=&is_on_map($uri);
6044: if ($match) {
6045: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6046: =~/\Q$priv\E\&([^\:]*)/) {
6047: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6048: if (@blockers > 0) {
6049: $thisallowed = 'B';
6050: } else {
6051: $thisallowed.=$1;
6052: }
6053: }
6054: } else {
6055: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6056: if ($refuri) {
6057: if ($refuri =~ m|^/adm/|) {
6058: $thisallowed='F';
6059: } else {
6060: $refuri=&declutter($refuri);
6061: my ($match) = &is_on_map($refuri);
6062: if ($match) {
6063: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6064: if (@blockers > 0) {
6065: $thisallowed = 'B';
6066: } else {
6067: $thisallowed='F';
6068: }
6069: }
6070: }
6071: }
6072: }
6073: }
6074:
6075: if ($priv eq 'bre'
6076: && $thisallowed ne 'F'
6077: && $thisallowed ne '2'
6078: && &is_portfolio_url($uri)) {
6079: $thisallowed = &portfolio_access($uri);
6080: }
6081:
6082: # Full access at system, domain or course-wide level? Exit.
6083: if ($thisallowed=~/F/) {
6084: return 'F';
6085: }
6086:
6087: # If this is generating or modifying users, exit with special codes
6088:
6089: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6090: if (($priv eq 'cca') || ($priv eq 'caa')) {
6091: my ($audom,$auname)=split('/',$uri);
6092: # no author name given, so this just checks on the general right to make a co-author in this domain
6093: unless ($auname) { return $thisallowed; }
6094: # an author name is given, so we are about to actually make a co-author for a certain account
6095: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6096: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6097: ($audom ne $env{'request.role.domain'}))) { return ''; }
6098: }
6099: return $thisallowed;
6100: }
6101: #
6102: # Gathered so far: system, domain and course wide privileges
6103: #
6104: # Course: See if uri or referer is an individual resource that is part of
6105: # the course
6106:
6107: if ($env{'request.course.id'}) {
6108:
6109: $courseprivid=$env{'request.course.id'};
6110: if ($env{'request.course.sec'}) {
6111: $courseprivid.='/'.$env{'request.course.sec'};
6112: }
6113: $courseprivid=~s/\_/\//;
6114: my $checkreferer=1;
6115: my ($match,$cond)=&is_on_map($uri);
6116: if ($match) {
6117: $statecond=$cond;
6118: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6119: =~/\Q$priv\E\&([^\:]*)/) {
6120: my $value = $1;
6121: if ($priv eq 'bre') {
6122: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6123: if (@blockers > 0) {
6124: $thisallowed = 'B';
6125: } else {
6126: $thisallowed.=$value;
6127: }
6128: } else {
6129: $thisallowed.=$value;
6130: }
6131: $checkreferer=0;
6132: }
6133: }
6134:
6135: if ($checkreferer) {
6136: my $refuri=$env{'httpref.'.$orguri};
6137: unless ($refuri) {
6138: foreach my $key (keys(%env)) {
6139: if ($key=~/^httpref\..*\*/) {
6140: my $pattern=$key;
6141: $pattern=~s/^httpref\.\/res\///;
6142: $pattern=~s/\*/\[\^\/\]\+/g;
6143: $pattern=~s/\//\\\//g;
6144: if ($orguri=~/$pattern/) {
6145: $refuri=$env{$key};
6146: }
6147: }
6148: }
6149: }
6150:
6151: if ($refuri) {
6152: $refuri=&declutter($refuri);
6153: my ($match,$cond)=&is_on_map($refuri);
6154: if ($match) {
6155: my $refstatecond=$cond;
6156: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6157: =~/\Q$priv\E\&([^\:]*)/) {
6158: my $value = $1;
6159: if ($priv eq 'bre') {
6160: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6161: if (@blockers > 0) {
6162: $thisallowed = 'B';
6163: } else {
6164: $thisallowed.=$value;
6165: }
6166: } else {
6167: $thisallowed.=$value;
6168: }
6169: $uri=$refuri;
6170: $statecond=$refstatecond;
6171: }
6172: }
6173: }
6174: }
6175: }
6176:
6177: #
6178: # Gathered now: all privileges that could apply, and condition number
6179: #
6180: #
6181: # Full or no access?
6182: #
6183:
6184: if ($thisallowed=~/F/) {
6185: return 'F';
6186: }
6187:
6188: unless ($thisallowed) {
6189: return '';
6190: }
6191:
6192: # Restrictions exist, deal with them
6193: #
6194: # C:according to course preferences
6195: # R:according to resource settings
6196: # L:unless locked
6197: # X:according to user session state
6198: #
6199:
6200: # Possibly locked functionality, check all courses
6201: # Locks might take effect only after 10 minutes cache expiration for other
6202: # courses, and 2 minutes for current course
6203:
6204: my $envkey;
6205: if ($thisallowed=~/L/) {
6206: foreach $envkey (keys(%env)) {
6207: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6208: my $courseid=$2;
6209: my $roleid=$1.'.'.$2;
6210: $courseid=~s/^\///;
6211: my $expiretime=600;
6212: if ($env{'request.role'} eq $roleid) {
6213: $expiretime=120;
6214: }
6215: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6216: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6217: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6218: &coursedescription($courseid,{'freshen_cache' => 1});
6219: }
6220: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6221: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6222: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6223: &log($env{'user.domain'},$env{'user.name'},
6224: $env{'user.home'},
6225: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6226: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6227: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6228: return '';
6229: }
6230: }
6231: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6232: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6233: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6234: &log($env{'user.domain'},$env{'user.name'},
6235: $env{'user.home'},
6236: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6237: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6238: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6239: return '';
6240: }
6241: }
6242: }
6243: }
6244: }
6245:
6246: #
6247: # Rest of the restrictions depend on selected course
6248: #
6249:
6250: unless ($env{'request.course.id'}) {
6251: if ($thisallowed eq 'A') {
6252: return 'A';
6253: } elsif ($thisallowed eq 'B') {
6254: return 'B';
6255: } else {
6256: return '1';
6257: }
6258: }
6259:
6260: #
6261: # Now user is definitely in a course
6262: #
6263:
6264:
6265: # Course preferences
6266:
6267: if ($thisallowed=~/C/) {
6268: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6269: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6270: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6271: =~/\Q$rolecode\E/) {
6272: if (($priv ne 'pch') && ($priv ne 'plc')) {
6273: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6274: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6275: $env{'request.course.id'});
6276: }
6277: return '';
6278: }
6279:
6280: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6281: =~/\Q$unamedom\E/) {
6282: if (($priv ne 'pch') && ($priv ne 'plc')) {
6283: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6284: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6285: $env{'request.course.id'});
6286: }
6287: return '';
6288: }
6289: }
6290:
6291: # Resource preferences
6292:
6293: if ($thisallowed=~/R/) {
6294: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6295: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6296: if (($priv ne 'pch') && ($priv ne 'plc')) {
6297: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6298: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6299: }
6300: return '';
6301: }
6302: }
6303:
6304: # Restricted by state or randomout?
6305:
6306: if ($thisallowed=~/X/) {
6307: if ($env{'acc.randomout'}) {
6308: if (!$symb) { $symb=&symbread($uri,1); }
6309: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6310: return '';
6311: }
6312: }
6313: if (&condval($statecond)) {
6314: return '2';
6315: } else {
6316: return '';
6317: }
6318: }
6319:
6320: if ($thisallowed eq 'A') {
6321: return 'A';
6322: } elsif ($thisallowed eq 'B') {
6323: return 'B';
6324: }
6325: return 'F';
6326: }
6327:
6328: sub get_comm_blocks {
6329: my ($cdom,$cnum) = @_;
6330: if ($cdom eq '' || $cnum eq '') {
6331: return unless ($env{'request.course.id'});
6332: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6333: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6334: }
6335: my %commblocks;
6336: my $hashid=$cdom.'_'.$cnum;
6337: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6338: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6339: %commblocks = %{$blocksref};
6340: } else {
6341: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6342: my $cachetime = 600;
6343: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6344: }
6345: return %commblocks;
6346: }
6347:
6348: sub has_comm_blocking {
6349: my ($priv,$symb,$uri,$blocks) = @_;
6350: return unless ($env{'request.course.id'});
6351: return unless ($priv eq 'bre');
6352: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6353: my %commblocks;
6354: if (ref($blocks) eq 'HASH') {
6355: %commblocks = %{$blocks};
6356: } else {
6357: %commblocks = &get_comm_blocks();
6358: }
6359: return unless (keys(%commblocks) > 0);
6360: if (!$symb) { $symb=&symbread($uri,1); }
6361: my ($map,$resid,undef)=&decode_symb($symb);
6362: my %tocheck = (
6363: maps => $map,
6364: resources => $symb,
6365: );
6366: my @blockers;
6367: my $now = time;
6368: my $navmap = Apache::lonnavmaps::navmap->new();
6369: foreach my $block (keys(%commblocks)) {
6370: if ($block =~ /^(\d+)____(\d+)$/) {
6371: my ($start,$end) = ($1,$2);
6372: if ($start <= $now && $end >= $now) {
6373: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6374: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6375: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6376: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6377: unless (grep(/^\Q$block\E$/,@blockers)) {
6378: push(@blockers,$block);
6379: }
6380: }
6381: }
6382: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6383: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6384: unless (grep(/^\Q$block\E$/,@blockers)) {
6385: push(@blockers,$block);
6386: }
6387: }
6388: }
6389: }
6390: }
6391: }
6392: } elsif ($block =~ /^firstaccess____(.+)$/) {
6393: my $item = $1;
6394: my @to_test;
6395: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6396: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6397: my $check_interval;
6398: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6399: my @interval;
6400: my $type = 'map';
6401: if ($item eq 'course') {
6402: $type = 'course';
6403: @interval=&EXT("resource.0.interval");
6404: } else {
6405: if ($item =~ /___\d+___/) {
6406: $type = 'resource';
6407: @interval=&EXT("resource.0.interval",$item);
6408: if (ref($navmap)) {
6409: my $res = $navmap->getBySymb($item);
6410: push(@to_test,$res);
6411: }
6412: } else {
6413: my $mapsymb = &symbread($item,1);
6414: if ($mapsymb) {
6415: if (ref($navmap)) {
6416: my $mapres = $navmap->getBySymb($mapsymb);
6417: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6418: foreach my $res (@to_test) {
6419: my $symb = $res->symb();
6420: next if ($symb eq $mapsymb);
6421: if ($symb ne '') {
6422: @interval=&EXT("resource.0.interval",$symb);
6423: last;
6424: }
6425: }
6426: }
6427: }
6428: }
6429: }
6430: if ($interval[0] =~ /\d+/) {
6431: my $first_access;
6432: if ($type eq 'resource') {
6433: $first_access=&get_first_access($interval[1],$item);
6434: } elsif ($type eq 'map') {
6435: $first_access=&get_first_access($interval[1],undef,$item);
6436: } else {
6437: $first_access=&get_first_access($interval[1]);
6438: }
6439: if ($first_access) {
6440: my $timesup = $first_access+$interval[0];
6441: if ($timesup > $now) {
6442: foreach my $res (@to_test) {
6443: if ($res->is_problem()) {
6444: if ($res->completable()) {
6445: unless (grep(/^\Q$block\E$/,@blockers)) {
6446: push(@blockers,$block);
6447: }
6448: last;
6449: }
6450: }
6451: }
6452: }
6453: }
6454: }
6455: }
6456: }
6457: }
6458: }
6459: }
6460: return @blockers;
6461: }
6462:
6463: sub check_docs_block {
6464: my ($docsblock,$tocheck) =@_;
6465: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6466: return;
6467: }
6468: if (ref($docsblock->{'maps'}) eq 'HASH') {
6469: if ($tocheck->{'maps'}) {
6470: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6471: return 1;
6472: }
6473: }
6474: }
6475: if (ref($docsblock->{'resources'}) eq 'HASH') {
6476: if ($tocheck->{'resources'}) {
6477: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6478: return 1;
6479: }
6480: }
6481: }
6482: return;
6483: }
6484:
6485: #
6486: # Removes the versino from a URI and
6487: # splits it in to its filename and path to the filename.
6488: # Seems like File::Basename could have done this more clearly.
6489: # Parameters:
6490: # $uri - input URI
6491: # Returns:
6492: # Two element list consisting of
6493: # $pathname - the URI up to and excluding the trailing /
6494: # $filename - The part of the URI following the last /
6495: # NOTE:
6496: # Another realization of this is simply:
6497: # use File::Basename;
6498: # ...
6499: # $uri = shift;
6500: # $filename = basename($uri);
6501: # $path = dirname($uri);
6502: # return ($filename, $path);
6503: #
6504: # The implementation below is probably faster however.
6505: #
6506: sub split_uri_for_cond {
6507: my $uri=&deversion(&declutter(shift));
6508: my @uriparts=split(/\//,$uri);
6509: my $filename=pop(@uriparts);
6510: my $pathname=join('/',@uriparts);
6511: return ($pathname,$filename);
6512: }
6513: # --------------------------------------------------- Is a resource on the map?
6514:
6515: sub is_on_map {
6516: my ($pathname,$filename) = &split_uri_for_cond(shift);
6517: #Trying to find the conditional for the file
6518: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
6519: /\&\Q$filename\E\:([\d\|]+)\&/);
6520: if ($match) {
6521: return (1,$1);
6522: } else {
6523: return (0,0);
6524: }
6525: }
6526:
6527: # --------------------------------------------------------- Get symb from alias
6528:
6529: sub get_symb_from_alias {
6530: my $symb=shift;
6531: my ($map,$resid,$url)=&decode_symb($symb);
6532: # Already is a symb
6533: if ($url) { return $symb; }
6534: # Must be an alias
6535: my $aliassymb='';
6536: my %bighash;
6537: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6538: &GDBM_READER(),0640)) {
6539: my $rid=$bighash{'mapalias_'.$symb};
6540: if ($rid) {
6541: my ($mapid,$resid)=split(/\./,$rid);
6542: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6543: $resid,$bighash{'src_'.$rid});
6544: }
6545: untie %bighash;
6546: }
6547: return $aliassymb;
6548: }
6549:
6550: # ----------------------------------------------------------------- Define Role
6551:
6552: sub definerole {
6553: if (allowed('mcr','/')) {
6554: my ($rolename,$sysrole,$domrole,$courole)=@_;
6555: foreach my $role (split(':',$sysrole)) {
6556: my ($crole,$cqual)=split(/\&/,$role);
6557: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6558: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6559: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6560: return "refused:s:$crole&$cqual";
6561: }
6562: }
6563: }
6564: foreach my $role (split(':',$domrole)) {
6565: my ($crole,$cqual)=split(/\&/,$role);
6566: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6567: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6568: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
6569: return "refused:d:$crole&$cqual";
6570: }
6571: }
6572: }
6573: foreach my $role (split(':',$courole)) {
6574: my ($crole,$cqual)=split(/\&/,$role);
6575: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6576: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6577: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6578: return "refused:c:$crole&$cqual";
6579: }
6580: }
6581: }
6582: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6583: "$env{'user.domain'}:$env{'user.name'}:".
6584: "rolesdef_$rolename=".
6585: escape($sysrole.'_'.$domrole.'_'.$courole);
6586: return reply($command,$env{'user.home'});
6587: } else {
6588: return 'refused';
6589: }
6590: }
6591:
6592: # ---------------- Make a metadata query against the network of library servers
6593:
6594: sub metadata_query {
6595: my ($query,$custom,$customshow,$server_array)=@_;
6596: my %rhash;
6597: my %libserv = &all_library();
6598: my @server_list = (defined($server_array) ? @$server_array
6599: : keys(%libserv) );
6600: for my $server (@server_list) {
6601: unless ($custom or $customshow) {
6602: my $reply=&reply("querysend:".&escape($query),$server);
6603: $rhash{$server}=$reply;
6604: }
6605: else {
6606: my $reply=&reply("querysend:".&escape($query).':'.
6607: &escape($custom).':'.&escape($customshow),
6608: $server);
6609: $rhash{$server}=$reply;
6610: }
6611: }
6612: return \%rhash;
6613: }
6614:
6615: # ----------------------------------------- Send log queries and wait for reply
6616:
6617: sub log_query {
6618: my ($uname,$udom,$query,%filters)=@_;
6619: my $uhome=&homeserver($uname,$udom);
6620: if ($uhome eq 'no_host') { return 'error: no_host'; }
6621: my $uhost=&hostname($uhome);
6622: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
6623: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6624: $uhome);
6625: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
6626: return get_query_reply($queryid);
6627: }
6628:
6629: # -------------------------- Update MySQL table for portfolio file
6630:
6631: sub update_portfolio_table {
6632: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
6633: if ($group ne '') {
6634: $file_name =~s /^\Q$group\E//;
6635: }
6636: my $homeserver = &homeserver($uname,$udom);
6637: my $queryid=
6638: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6639: ':'.&escape($file_name).':'.$action,$homeserver);
6640: my $reply = &get_query_reply($queryid);
6641: return $reply;
6642: }
6643:
6644: # -------------------------- Update MySQL allusers table
6645:
6646: sub update_allusers_table {
6647: my ($uname,$udom,$names) = @_;
6648: my $homeserver = &homeserver($uname,$udom);
6649: my $queryid=
6650: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6651: 'lastname='.&escape($names->{'lastname'}).'%%'.
6652: 'firstname='.&escape($names->{'firstname'}).'%%'.
6653: 'middlename='.&escape($names->{'middlename'}).'%%'.
6654: 'generation='.&escape($names->{'generation'}).'%%'.
6655: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6656: 'id='.&escape($names->{'id'}),$homeserver);
6657: return;
6658: }
6659:
6660: # ------- Request retrieval of institutional classlists for course(s)
6661:
6662: sub fetch_enrollment_query {
6663: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6664: my $homeserver;
6665: my $maxtries = 1;
6666: if ($context eq 'automated') {
6667: $homeserver = $perlvar{'lonHostID'};
6668: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6669: } else {
6670: $homeserver = &homeserver($cnum,$dom);
6671: }
6672: my $host=&hostname($homeserver);
6673: my $cmd = '';
6674: foreach my $affiliate (keys(%{$affiliatesref})) {
6675: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6676: }
6677: $cmd =~ s/%%$//;
6678: $cmd = &escape($cmd);
6679: my $query = 'fetchenrollment';
6680: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6681: unless ($queryid=~/^\Q$host\E\_/) {
6682: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6683: return 'error: '.$queryid;
6684: }
6685: my $reply = &get_query_reply($queryid);
6686: my $tries = 1;
6687: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6688: $reply = &get_query_reply($queryid);
6689: $tries ++;
6690: }
6691: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6692: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6693: } else {
6694: my @responses = split(/:/,$reply);
6695: if ($homeserver eq $perlvar{'lonHostID'}) {
6696: foreach my $line (@responses) {
6697: my ($key,$value) = split(/=/,$line,2);
6698: $$replyref{$key} = $value;
6699: }
6700: } else {
6701: my $pathname = LONCAPA::tempdir();
6702: foreach my $line (@responses) {
6703: my ($key,$value) = split(/=/,$line);
6704: $$replyref{$key} = $value;
6705: if ($value > 0) {
6706: foreach my $item (@{$$affiliatesref{$key}}) {
6707: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6708: my $destname = $pathname.'/'.$filename;
6709: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6710: if ($xml_classlist =~ /^error/) {
6711: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6712: } else {
6713: if ( open(FILE,">$destname") ) {
6714: print FILE &unescape($xml_classlist);
6715: close(FILE);
6716: } else {
6717: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6718: }
6719: }
6720: }
6721: }
6722: }
6723: }
6724: return 'ok';
6725: }
6726: return 'error';
6727: }
6728:
6729: sub get_query_reply {
6730: my $queryid=shift;
6731: my $replyfile=LONCAPA::tempdir().$queryid;
6732: my $reply='';
6733: for (1..100) {
6734: sleep 2;
6735: if (-e $replyfile.'.end') {
6736: if (open(my $fh,$replyfile)) {
6737: $reply = join('',<$fh>);
6738: close($fh);
6739: } else { return 'error: reply_file_error'; }
6740: return &unescape($reply);
6741: }
6742: }
6743: return 'timeout:'.$queryid;
6744: }
6745:
6746: sub courselog_query {
6747: #
6748: # possible filters:
6749: # url: url or symb
6750: # username
6751: # domain
6752: # action: view, submit, grade
6753: # start: timestamp
6754: # end: timestamp
6755: #
6756: my (%filters)=@_;
6757: unless ($env{'request.course.id'}) { return 'no_course'; }
6758: if ($filters{'url'}) {
6759: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6760: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6761: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6762: }
6763: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6764: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6765: return &log_query($cname,$cdom,'courselog',%filters);
6766: }
6767:
6768: sub userlog_query {
6769: #
6770: # possible filters:
6771: # action: log check role
6772: # start: timestamp
6773: # end: timestamp
6774: #
6775: my ($uname,$udom,%filters)=@_;
6776: return &log_query($uname,$udom,'userlog',%filters);
6777: }
6778:
6779: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6780:
6781: sub auto_run {
6782: my ($cnum,$cdom) = @_;
6783: my $response = 0;
6784: my $settings;
6785: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6786: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6787: $settings = $domconfig{'autoenroll'};
6788: if ($settings->{'run'} eq '1') {
6789: $response = 1;
6790: }
6791: } else {
6792: my $homeserver;
6793: if (&is_course($cdom,$cnum)) {
6794: $homeserver = &homeserver($cnum,$cdom);
6795: } else {
6796: $homeserver = &domain($cdom,'primary');
6797: }
6798: if ($homeserver ne 'no_host') {
6799: $response = &reply('autorun:'.$cdom,$homeserver);
6800: }
6801: }
6802: return $response;
6803: }
6804:
6805: sub auto_get_sections {
6806: my ($cnum,$cdom,$inst_coursecode) = @_;
6807: my $homeserver;
6808: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6809: $homeserver = &homeserver($cnum,$cdom);
6810: }
6811: if (!defined($homeserver)) {
6812: if ($cdom =~ /^$match_domain$/) {
6813: $homeserver = &domain($cdom,'primary');
6814: }
6815: }
6816: my @secs;
6817: if (defined($homeserver)) {
6818: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6819: unless ($response eq 'refused') {
6820: @secs = split(/:/,$response);
6821: }
6822: }
6823: return @secs;
6824: }
6825:
6826: sub auto_new_course {
6827: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6828: my $homeserver = &homeserver($cnum,$cdom);
6829: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6830: return $response;
6831: }
6832:
6833: sub auto_validate_courseID {
6834: my ($cnum,$cdom,$inst_course_id) = @_;
6835: my $homeserver = &homeserver($cnum,$cdom);
6836: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6837: return $response;
6838: }
6839:
6840: sub auto_validate_instcode {
6841: my ($cnum,$cdom,$instcode,$owner) = @_;
6842: my ($homeserver,$response);
6843: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6844: $homeserver = &homeserver($cnum,$cdom);
6845: }
6846: if (!defined($homeserver)) {
6847: if ($cdom =~ /^$match_domain$/) {
6848: $homeserver = &domain($cdom,'primary');
6849: }
6850: }
6851: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6852: &escape($instcode).':'.&escape($owner),$homeserver));
6853: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6854: return ($outcome,$description);
6855: }
6856:
6857: sub auto_create_password {
6858: my ($cnum,$cdom,$authparam,$udom) = @_;
6859: my ($homeserver,$response);
6860: my $create_passwd = 0;
6861: my $authchk = '';
6862: if ($udom =~ /^$match_domain$/) {
6863: $homeserver = &domain($udom,'primary');
6864: }
6865: if ($homeserver eq '') {
6866: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6867: $homeserver = &homeserver($cnum,$cdom);
6868: }
6869: }
6870: if ($homeserver eq '') {
6871: $authchk = 'nodomain';
6872: } else {
6873: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6874: if ($response eq 'refused') {
6875: $authchk = 'refused';
6876: } else {
6877: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6878: }
6879: }
6880: return ($authparam,$create_passwd,$authchk);
6881: }
6882:
6883: sub auto_photo_permission {
6884: my ($cnum,$cdom,$students) = @_;
6885: my $homeserver = &homeserver($cnum,$cdom);
6886: my ($outcome,$perm_reqd,$conditions) =
6887: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6888: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6889: return (undef,undef);
6890: }
6891: return ($outcome,$perm_reqd,$conditions);
6892: }
6893:
6894: sub auto_checkphotos {
6895: my ($uname,$udom,$pid) = @_;
6896: my $homeserver = &homeserver($uname,$udom);
6897: my ($result,$resulttype);
6898: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6899: &escape($uname).':'.&escape($pid),
6900: $homeserver));
6901: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6902: return (undef,undef);
6903: }
6904: if ($outcome) {
6905: ($result,$resulttype) = split(/:/,$outcome);
6906: }
6907: return ($result,$resulttype);
6908: }
6909:
6910: sub auto_photochoice {
6911: my ($cnum,$cdom) = @_;
6912: my $homeserver = &homeserver($cnum,$cdom);
6913: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6914: &escape($cdom),
6915: $homeserver)));
6916: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6917: return (undef,undef);
6918: }
6919: return ($update,$comment);
6920: }
6921:
6922: sub auto_photoupdate {
6923: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6924: my $homeserver = &homeserver($cnum,$dom);
6925: my $host=&hostname($homeserver);
6926: my $cmd = '';
6927: my $maxtries = 1;
6928: foreach my $affiliate (keys(%{$affiliatesref})) {
6929: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6930: }
6931: $cmd =~ s/%%$//;
6932: $cmd = &escape($cmd);
6933: my $query = 'institutionalphotos';
6934: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6935: unless ($queryid=~/^\Q$host\E\_/) {
6936: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6937: return 'error: '.$queryid;
6938: }
6939: my $reply = &get_query_reply($queryid);
6940: my $tries = 1;
6941: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6942: $reply = &get_query_reply($queryid);
6943: $tries ++;
6944: }
6945: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6946: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6947: } else {
6948: my @responses = split(/:/,$reply);
6949: my $outcome = shift(@responses);
6950: foreach my $item (@responses) {
6951: my ($key,$value) = split(/=/,$item);
6952: $$photo{$key} = $value;
6953: }
6954: return $outcome;
6955: }
6956: return 'error';
6957: }
6958:
6959: sub auto_instcode_format {
6960: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6961: $cat_order) = @_;
6962: my $courses = '';
6963: my @homeservers;
6964: if ($caller eq 'global') {
6965: my %servers = &get_servers($codedom,'library');
6966: foreach my $tryserver (keys(%servers)) {
6967: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6968: push(@homeservers,$tryserver);
6969: }
6970: }
6971: } elsif ($caller eq 'requests') {
6972: if ($codedom =~ /^$match_domain$/) {
6973: my $chome = &domain($codedom,'primary');
6974: unless ($chome eq 'no_host') {
6975: push(@homeservers,$chome);
6976: }
6977: }
6978: } else {
6979: push(@homeservers,&homeserver($caller,$codedom));
6980: }
6981: foreach my $code (keys(%{$instcodes})) {
6982: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
6983: }
6984: chop($courses);
6985: my $ok_response = 0;
6986: my $response;
6987: while (@homeservers > 0 && $ok_response == 0) {
6988: my $server = shift(@homeservers);
6989: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6990: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6991: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
6992: split(/:/,$response);
6993: %{$codes} = (%{$codes},&str2hash($codes_str));
6994: push(@{$codetitles},&str2array($codetitles_str));
6995: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6996: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6997: $ok_response = 1;
6998: }
6999: }
7000: if ($ok_response) {
7001: return 'ok';
7002: } else {
7003: return $response;
7004: }
7005: }
7006:
7007: sub auto_instcode_defaults {
7008: my ($domain,$returnhash,$code_order) = @_;
7009: my @homeservers;
7010:
7011: my %servers = &get_servers($domain,'library');
7012: foreach my $tryserver (keys(%servers)) {
7013: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7014: push(@homeservers,$tryserver);
7015: }
7016: }
7017:
7018: my $response;
7019: foreach my $server (@homeservers) {
7020: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7021: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7022:
7023: foreach my $pair (split(/\&/,$response)) {
7024: my ($name,$value)=split(/\=/,$pair);
7025: if ($name eq 'code_order') {
7026: @{$code_order} = split(/\&/,&unescape($value));
7027: } else {
7028: $returnhash->{&unescape($name)}=&unescape($value);
7029: }
7030: }
7031: return 'ok';
7032: }
7033:
7034: return $response;
7035: }
7036:
7037: sub auto_possible_instcodes {
7038: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7039: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7040: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7041: return;
7042: }
7043: my (@homeservers,$uhome);
7044: if (defined(&domain($domain,'primary'))) {
7045: $uhome=&domain($domain,'primary');
7046: push(@homeservers,&domain($domain,'primary'));
7047: } else {
7048: my %servers = &get_servers($domain,'library');
7049: foreach my $tryserver (keys(%servers)) {
7050: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7051: push(@homeservers,$tryserver);
7052: }
7053: }
7054: }
7055: my $response;
7056: foreach my $server (@homeservers) {
7057: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7058: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7059: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7060: split(':',$response);
7061: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7062: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7063: foreach my $item (split('&',$cat_title)) {
7064: my ($name,$value)=split('=',$item);
7065: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7066: }
7067: foreach my $item (split('&',$cat_order)) {
7068: my ($name,$value)=split('=',$item);
7069: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7070: }
7071: return 'ok';
7072: }
7073: return $response;
7074: }
7075:
7076: sub auto_courserequest_checks {
7077: my ($dom) = @_;
7078: my ($homeserver,%validations);
7079: if ($dom =~ /^$match_domain$/) {
7080: $homeserver = &domain($dom,'primary');
7081: }
7082: unless ($homeserver eq 'no_host') {
7083: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7084: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7085: my @items = split(/&/,$response);
7086: foreach my $item (@items) {
7087: my ($key,$value) = split('=',$item);
7088: $validations{&unescape($key)} = &thaw_unescape($value);
7089: }
7090: }
7091: }
7092: return %validations;
7093: }
7094:
7095: sub auto_courserequest_validation {
7096: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7097: my ($homeserver,$response);
7098: if ($dom =~ /^$match_domain$/) {
7099: $homeserver = &domain($dom,'primary');
7100: }
7101: unless ($homeserver eq 'no_host') {
7102:
7103: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7104: ':'.&escape($crstype).':'.&escape($inststatuslist).
7105: ':'.&escape($instcode).':'.&escape($instseclist),
7106: $homeserver));
7107: }
7108: return $response;
7109: }
7110:
7111: sub auto_validate_class_sec {
7112: my ($cdom,$cnum,$owners,$inst_class) = @_;
7113: my $homeserver = &homeserver($cnum,$cdom);
7114: my $ownerlist;
7115: if (ref($owners) eq 'ARRAY') {
7116: $ownerlist = join(',',@{$owners});
7117: } else {
7118: $ownerlist = $owners;
7119: }
7120: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7121: &escape($ownerlist).':'.$cdom,$homeserver);
7122: return $response;
7123: }
7124:
7125: # ------------------------------------------------------- Course Group routines
7126:
7127: sub get_coursegroups {
7128: my ($cdom,$cnum,$group,$namespace) = @_;
7129: return(&dump($namespace,$cdom,$cnum,$group));
7130: }
7131:
7132: sub modify_coursegroup {
7133: my ($cdom,$cnum,$groupsettings) = @_;
7134: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7135: }
7136:
7137: sub toggle_coursegroup_status {
7138: my ($cdom,$cnum,$group,$action) = @_;
7139: my ($from_namespace,$to_namespace);
7140: if ($action eq 'delete') {
7141: $from_namespace = 'coursegroups';
7142: $to_namespace = 'deleted_groups';
7143: } else {
7144: $from_namespace = 'deleted_groups';
7145: $to_namespace = 'coursegroups';
7146: }
7147: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
7148: if (my $tmp = &error(%curr_group)) {
7149: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7150: return ('read error',$tmp);
7151: } else {
7152: my %savedsettings = %curr_group;
7153: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
7154: my $deloutcome;
7155: if ($result eq 'ok') {
7156: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
7157: } else {
7158: return ('write error',$result);
7159: }
7160: if ($deloutcome eq 'ok') {
7161: return 'ok';
7162: } else {
7163: return ('delete error',$deloutcome);
7164: }
7165: }
7166: }
7167:
7168: sub modify_group_roles {
7169: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
7170: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7171: my $role = 'gr/'.&escape($userprivs);
7172: my ($uname,$udom) = split(/:/,$user);
7173: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
7174: if ($result eq 'ok') {
7175: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7176: }
7177: return $result;
7178: }
7179:
7180: sub modify_coursegroup_membership {
7181: my ($cdom,$cnum,$membership) = @_;
7182: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7183: return $result;
7184: }
7185:
7186: sub get_active_groups {
7187: my ($udom,$uname,$cdom,$cnum) = @_;
7188: my $now = time;
7189: my %groups = ();
7190: foreach my $key (keys(%env)) {
7191: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
7192: my ($start,$end) = split(/\./,$env{$key});
7193: if (($end!=0) && ($end<$now)) { next; }
7194: if (($start!=0) && ($start>$now)) { next; }
7195: if ($1 eq $cdom && $2 eq $cnum) {
7196: $groups{$3} = $env{$key} ;
7197: }
7198: }
7199: }
7200: return %groups;
7201: }
7202:
7203: sub get_group_membership {
7204: my ($cdom,$cnum,$group) = @_;
7205: return(&dump('groupmembership',$cdom,$cnum,$group));
7206: }
7207:
7208: sub get_users_groups {
7209: my ($udom,$uname,$courseid) = @_;
7210: my @usersgroups;
7211: my $cachetime=1800;
7212:
7213: my $hashid="$udom:$uname:$courseid";
7214: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7215: if (defined($cached)) {
7216: @usersgroups = split(/:/,$grouplist);
7217: } else {
7218: $grouplist = '';
7219: my $courseurl = &courseid_to_courseurl($courseid);
7220: my $extra = &freeze_escape({'skipcheck' => 1});
7221: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
7222: my $access_end = $env{'course.'.$courseid.
7223: '.default_enrollment_end_date'};
7224: my $now = time;
7225: foreach my $key (keys(%roleshash)) {
7226: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7227: my $group = $1;
7228: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7229: my $start = $2;
7230: my $end = $1;
7231: if ($start == -1) { next; } # deleted from group
7232: if (($start!=0) && ($start>$now)) { next; }
7233: if (($end!=0) && ($end<$now)) {
7234: if ($access_end && $access_end < $now) {
7235: if ($access_end - $end < 86400) {
7236: push(@usersgroups,$group);
7237: }
7238: }
7239: next;
7240: }
7241: push(@usersgroups,$group);
7242: }
7243: }
7244: }
7245: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7246: $grouplist = join(':',@usersgroups);
7247: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
7248: }
7249: return @usersgroups;
7250: }
7251:
7252: sub devalidate_getgroups_cache {
7253: my ($udom,$uname,$cdom,$cnum)=@_;
7254: my $courseid = $cdom.'_'.$cnum;
7255:
7256: my $hashid="$udom:$uname:$courseid";
7257: &devalidate_cache_new('getgroups',$hashid);
7258: }
7259:
7260: # ------------------------------------------------------------------ Plain Text
7261:
7262: sub plaintext {
7263: my ($short,$type,$cid,$forcedefault) = @_;
7264: if ($short =~ m{^cr/}) {
7265: return (split('/',$short))[-1];
7266: }
7267: if (!defined($cid)) {
7268: $cid = $env{'request.course.id'};
7269: }
7270: my %rolenames = (
7271: Course => 'std',
7272: Community => 'alt1',
7273: );
7274: if ($cid ne '') {
7275: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7276: unless ($forcedefault) {
7277: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7278: &Apache::lonlocal::mt_escape(\$roletext);
7279: return &Apache::lonlocal::mt($roletext);
7280: }
7281: }
7282: }
7283: if ((defined($type)) && (defined($rolenames{$type})) &&
7284: (defined($rolenames{$type})) &&
7285: (defined($prp{$short}{$rolenames{$type}}))) {
7286: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
7287: } elsif ($cid ne '') {
7288: my $crstype = $env{'course.'.$cid.'.type'};
7289: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7290: (defined($prp{$short}{$rolenames{$crstype}}))) {
7291: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7292: }
7293: }
7294: return &Apache::lonlocal::mt($prp{$short}{'std'});
7295: }
7296:
7297: # ----------------------------------------------------------------- Assign Role
7298:
7299: sub assignrole {
7300: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7301: $context)=@_;
7302: my $mrole;
7303: if ($role =~ /^cr\//) {
7304: my $cwosec=$url;
7305: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7306: unless (&allowed('ccr',$cwosec)) {
7307: my $refused = 1;
7308: if ($context eq 'requestcourses') {
7309: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7310: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7311: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7312: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7313: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7314: if ($crsenv{'internal.courseowner'} eq
7315: $env{'user.name'}.':'.$env{'user.domain'}) {
7316: $refused = '';
7317: }
7318: }
7319: }
7320: }
7321: }
7322: if ($refused) {
7323: &logthis('Refused custom assignrole: '.
7324: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7325: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7326: return 'refused';
7327: }
7328: }
7329: $mrole='cr';
7330: } elsif ($role =~ /^gr\//) {
7331: my $cwogrp=$url;
7332: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7333: unless (&allowed('mdg',$cwogrp)) {
7334: &logthis('Refused group assignrole: '.
7335: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7336: $env{'user.name'}.' at '.$env{'user.domain'});
7337: return 'refused';
7338: }
7339: $mrole='gr';
7340: } else {
7341: my $cwosec=$url;
7342: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7343: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7344: my $refused;
7345: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7346: if (!(&allowed('c'.$role,$url))) {
7347: $refused = 1;
7348: }
7349: } else {
7350: $refused = 1;
7351: }
7352: if ($refused) {
7353: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7354: if (!$selfenroll && $context eq 'course') {
7355: my %crsenv;
7356: if ($role eq 'cc' || $role eq 'co') {
7357: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7358: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7359: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7360: if ($crsenv{'internal.courseowner'} eq
7361: $env{'user.name'}.':'.$env{'user.domain'}) {
7362: $refused = '';
7363: }
7364: }
7365: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7366: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7367: if ($crsenv{'internal.courseowner'} eq
7368: $env{'user.name'}.':'.$env{'user.domain'}) {
7369: $refused = '';
7370: }
7371: }
7372: }
7373: }
7374: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7375: $refused = '';
7376: } elsif ($context eq 'requestcourses') {
7377: my @possroles = ('st','ta','ep','in','cc','co');
7378: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7379: my $wrongcc;
7380: if ($cnum =~ /^$match_community$/) {
7381: $wrongcc = 1 if ($role eq 'cc');
7382: } else {
7383: $wrongcc = 1 if ($role eq 'co');
7384: }
7385: unless ($wrongcc) {
7386: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7387: if ($crsenv{'internal.courseowner'} eq
7388: $env{'user.name'}.':'.$env{'user.domain'}) {
7389: $refused = '';
7390: }
7391: }
7392: }
7393: }
7394: if ($refused) {
7395: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7396: ' '.$role.' '.$end.' '.$start.' by '.
7397: $env{'user.name'}.' at '.$env{'user.domain'});
7398: return 'refused';
7399: }
7400: }
7401: } elsif ($role eq 'au') {
7402: if ($url ne '/'.$udom.'/') {
7403: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7404: ' to assign author role for '.$uname.':'.$udom.
7405: ' in domain: '.$url.' refused (wrong domain).');
7406: return 'refused';
7407: }
7408: }
7409: $mrole=$role;
7410: }
7411: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7412: "$udom:$uname:$url".'_'."$mrole=$role";
7413: if ($end) { $command.='_'.$end; }
7414: if ($start) {
7415: if ($end) {
7416: $command.='_'.$start;
7417: } else {
7418: $command.='_0_'.$start;
7419: }
7420: }
7421: my $origstart = $start;
7422: my $origend = $end;
7423: my $delflag;
7424: # actually delete
7425: if ($deleteflag) {
7426: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
7427: # modify command to delete the role
7428: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
7429: "$udom:$uname:$url".'_'."$mrole";
7430: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
7431: # set start and finish to negative values for userrolelog
7432: $start=-1;
7433: $end=-1;
7434: $delflag = 1;
7435: }
7436: }
7437: # send command
7438: my $answer=&reply($command,&homeserver($uname,$udom));
7439: # log new user role if status is ok
7440: if ($answer eq 'ok') {
7441: &userrolelog($role,$uname,$udom,$url,$start,$end);
7442: # for course roles, perform group memberships changes triggered by role change.
7443: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
7444: unless ($role =~ /^gr/) {
7445: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
7446: $origstart,$selfenroll,$context);
7447: }
7448: if ($role eq 'cc') {
7449: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7450: }
7451: }
7452: return $answer;
7453: }
7454:
7455: sub autoupdate_coowners {
7456: my ($url,$end,$start,$uname,$udom) = @_;
7457: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7458: if (($cdom ne '') && ($cnum ne '')) {
7459: my $now = time;
7460: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7461: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7462: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7463: my $instcode = $coursehash{'internal.coursecode'};
7464: if ($instcode ne '') {
7465: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7466: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
7467: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
7468: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7469: if ($result eq 'valid') {
7470: if ($coursehash{'internal.co-owners'}) {
7471: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7472: push(@newcoowners,$coowner);
7473: }
7474: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7475: push(@newcoowners,$uname.':'.$udom);
7476: }
7477: @newcoowners = sort(@newcoowners);
7478: } else {
7479: push(@newcoowners,$uname.':'.$udom);
7480: }
7481: } else {
7482: if ($coursehash{'internal.co-owners'}) {
7483: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7484: unless ($coowner eq $uname.':'.$udom) {
7485: push(@newcoowners,$coowner);
7486: }
7487: }
7488: unless (@newcoowners > 0) {
7489: $delcoowners = 1;
7490: $coowners = '';
7491: }
7492: }
7493: }
7494: if (@newcoowners || $delcoowners) {
7495: &store_coowners($cdom,$cnum,$coursehash{'home'},
7496: $delcoowners,@newcoowners);
7497: }
7498: }
7499: }
7500: }
7501: }
7502: }
7503: }
7504:
7505: sub store_coowners {
7506: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7507: my $cid = $cdom.'_'.$cnum;
7508: my ($coowners,$delresult,$putresult);
7509: if (@newcoowners) {
7510: $coowners = join(',',@newcoowners);
7511: my %coownershash = (
7512: 'internal.co-owners' => $coowners,
7513: );
7514: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7515: if ($putresult eq 'ok') {
7516: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7517: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7518: }
7519: }
7520: }
7521: if ($delcoowners) {
7522: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7523: if ($delresult eq 'ok') {
7524: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7525: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7526: }
7527: }
7528: }
7529: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7530: my %crsinfo =
7531: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7532: if (ref($crsinfo{$cid}) eq 'HASH') {
7533: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7534: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7535: }
7536: }
7537: }
7538:
7539: # -------------------------------------------------- Modify user authentication
7540: # Overrides without validation
7541:
7542: sub modifyuserauth {
7543: my ($udom,$uname,$umode,$upass)=@_;
7544: my $uhome=&homeserver($uname,$udom);
7545: unless (&allowed('mau',$udom)) { return 'refused'; }
7546: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
7547: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7548: ' in domain '.$env{'request.role.domain'});
7549: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7550: &escape($upass),$uhome);
7551: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
7552: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7553: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7554: &log($udom,,$uname,$uhome,
7555: 'Authentication changed by '.$env{'user.domain'}.', '.
7556: $env{'user.name'}.', '.$umode.
7557: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7558: unless ($reply eq 'ok') {
7559: &logthis('Authentication mode error: '.$reply);
7560: return 'error: '.$reply;
7561: }
7562: return 'ok';
7563: }
7564:
7565: # --------------------------------------------------------------- Modify a user
7566:
7567: sub modifyuser {
7568: my ($udom, $uname, $uid,
7569: $umode, $upass, $first,
7570: $middle, $last, $gene,
7571: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
7572: $udom= &LONCAPA::clean_domain($udom);
7573: $uname=&LONCAPA::clean_username($uname);
7574: my $showcandelete = 'none';
7575: if (ref($candelete) eq 'ARRAY') {
7576: if (@{$candelete} > 0) {
7577: $showcandelete = join(', ',@{$candelete});
7578: }
7579: }
7580: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
7581: $umode.', '.$first.', '.$middle.', '.
7582: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
7583: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7584: ' desiredhome not specified').
7585: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7586: ' in domain '.$env{'request.role.domain'});
7587: my $uhome=&homeserver($uname,$udom,'true');
7588: my $newuser;
7589: if ($uhome eq 'no_host') {
7590: $newuser = 1;
7591: }
7592: # ----------------------------------------------------------------- Create User
7593: if (($uhome eq 'no_host') &&
7594: (($umode && $upass) || ($umode eq 'localauth'))) {
7595: my $unhome='';
7596: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
7597: $unhome = $desiredhome;
7598: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7599: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
7600: } else { # load balancing routine for determining $unhome
7601: my $loadm=10000000;
7602: my %servers = &get_servers($udom,'library');
7603: foreach my $tryserver (keys(%servers)) {
7604: my $answer=reply('load',$tryserver);
7605: if (($answer=~/\d+/) && ($answer<$loadm)) {
7606: $loadm=$answer;
7607: $unhome=$tryserver;
7608: }
7609: }
7610: }
7611: if (($unhome eq '') || ($unhome eq 'no_host')) {
7612: return 'error: unable to find a home server for '.$uname.
7613: ' in domain '.$udom;
7614: }
7615: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7616: &escape($upass),$unhome);
7617: unless ($reply eq 'ok') {
7618: return 'error: '.$reply;
7619: }
7620: $uhome=&homeserver($uname,$udom,'true');
7621: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
7622: return 'error: unable verify users home machine.';
7623: }
7624: } # End of creation of new user
7625: # ---------------------------------------------------------------------- Add ID
7626: if ($uid) {
7627: $uid=~tr/A-Z/a-z/;
7628: my %uidhash=&idrget($udom,$uname);
7629: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7630: && (!$forceid)) {
7631: unless ($uid eq $uidhash{$uname}) {
7632: return 'error: user id "'.$uid.'" does not match '.
7633: 'current user id "'.$uidhash{$uname}.'".';
7634: }
7635: } else {
7636: &idput($udom,($uname => $uid));
7637: }
7638: }
7639: # -------------------------------------------------------------- Add names, etc
7640: my @tmp=&get('environment',
7641: ['firstname','middlename','lastname','generation','id',
7642: 'permanentemail','inststatus'],
7643: $udom,$uname);
7644: my (%names,%oldnames);
7645: if ($tmp[0] =~ m/^error:.*/) {
7646: %names=();
7647: } else {
7648: %names = @tmp;
7649: %oldnames = %names;
7650: }
7651: #
7652: # If name, email and/or uid are blank (e.g., because an uploaded file
7653: # of users did not contain them), do not overwrite existing values
7654: # unless field is in $candelete array ref.
7655: #
7656:
7657: my @fields = ('firstname','middlename','lastname','generation',
7658: 'permanentemail','id');
7659: my %newvalues;
7660: if (ref($candelete) eq 'ARRAY') {
7661: foreach my $field (@fields) {
7662: if (grep(/^\Q$field\E$/,@{$candelete})) {
7663: if ($field eq 'firstname') {
7664: $names{$field} = $first;
7665: } elsif ($field eq 'middlename') {
7666: $names{$field} = $middle;
7667: } elsif ($field eq 'lastname') {
7668: $names{$field} = $last;
7669: } elsif ($field eq 'generation') {
7670: $names{$field} = $gene;
7671: } elsif ($field eq 'permanentemail') {
7672: $names{$field} = $email;
7673: } elsif ($field eq 'id') {
7674: $names{$field} = $uid;
7675: }
7676: }
7677: }
7678: }
7679: if ($first) { $names{'firstname'} = $first; }
7680: if (defined($middle)) { $names{'middlename'} = $middle; }
7681: if ($last) { $names{'lastname'} = $last; }
7682: if (defined($gene)) { $names{'generation'} = $gene; }
7683: if ($email) {
7684: $email=~s/[^\w\@\.\-\,]//gs;
7685: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7686: }
7687: if ($uid) { $names{'id'} = $uid; }
7688: if (defined($inststatus)) {
7689: $names{'inststatus'} = '';
7690: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7691: if (ref($usertypes) eq 'HASH') {
7692: my @okstatuses;
7693: foreach my $item (split(/:/,$inststatus)) {
7694: if (defined($usertypes->{$item})) {
7695: push(@okstatuses,$item);
7696: }
7697: }
7698: if (@okstatuses) {
7699: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7700: }
7701: }
7702: }
7703: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7704: $umode.', '.$first.', '.$middle.', '.
7705: $last.', '.$gene.', '.$email.', '.$inststatus;
7706: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7707: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7708: } else {
7709: $logmsg .= ' during self creation';
7710: }
7711: my $changed;
7712: if ($newuser) {
7713: $changed = 1;
7714: } else {
7715: foreach my $field (@fields) {
7716: if ($names{$field} ne $oldnames{$field}) {
7717: $changed = 1;
7718: last;
7719: }
7720: }
7721: }
7722: unless ($changed) {
7723: $logmsg = 'No changes in user information needed for: '.$logmsg;
7724: &logthis($logmsg);
7725: return 'ok';
7726: }
7727: my $reply = &put('environment', \%names, $udom,$uname);
7728: if ($reply ne 'ok') {
7729: return 'error: '.$reply;
7730: }
7731: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7732: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7733: }
7734: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7735: &devalidate_cache_new('namescache',$uname.':'.$udom);
7736: $logmsg = 'Success modifying user '.$logmsg;
7737: &logthis($logmsg);
7738: return 'ok';
7739: }
7740:
7741: # -------------------------------------------------------------- Modify student
7742:
7743: sub modifystudent {
7744: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7745: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7746: $selfenroll,$context,$inststatus)=@_;
7747: if (!$cid) {
7748: unless ($cid=$env{'request.course.id'}) {
7749: return 'not_in_class';
7750: }
7751: }
7752: # --------------------------------------------------------------- Make the user
7753: my $reply=&modifyuser
7754: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7755: $desiredhome,$email,$inststatus);
7756: unless ($reply eq 'ok') { return $reply; }
7757: # This will cause &modify_student_enrollment to get the uid from the
7758: # students environment
7759: $uid = undef if (!$forceid);
7760: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7761: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7762: return $reply;
7763: }
7764:
7765: sub modify_student_enrollment {
7766: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7767: my ($cdom,$cnum,$chome);
7768: if (!$cid) {
7769: unless ($cid=$env{'request.course.id'}) {
7770: return 'not_in_class';
7771: }
7772: $cdom=$env{'course.'.$cid.'.domain'};
7773: $cnum=$env{'course.'.$cid.'.num'};
7774: } else {
7775: ($cdom,$cnum)=split(/_/,$cid);
7776: }
7777: $chome=$env{'course.'.$cid.'.home'};
7778: if (!$chome) {
7779: $chome=&homeserver($cnum,$cdom);
7780: }
7781: if (!$chome) { return 'unknown_course'; }
7782: # Make sure the user exists
7783: my $uhome=&homeserver($uname,$udom);
7784: if (($uhome eq '') || ($uhome eq 'no_host')) {
7785: return 'error: no such user';
7786: }
7787: # Get student data if we were not given enough information
7788: if (!defined($first) || $first eq '' ||
7789: !defined($last) || $last eq '' ||
7790: !defined($uid) || $uid eq '' ||
7791: !defined($middle) || $middle eq '' ||
7792: !defined($gene) || $gene eq '') {
7793: # They did not supply us with enough data to enroll the student, so
7794: # we need to pick up more information.
7795: my %tmp = &get('environment',
7796: ['firstname','middlename','lastname', 'generation','id']
7797: ,$udom,$uname);
7798:
7799: #foreach my $key (keys(%tmp)) {
7800: # &logthis("key $key = ".$tmp{$key});
7801: #}
7802: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7803: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7804: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7805: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7806: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7807: }
7808: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7809: my $user = "$uname:$udom";
7810: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
7811: my $reply=cput('classlist',
7812: {$user =>
7813: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7814: $cdom,$cnum);
7815: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7816: &devalidate_getsection_cache($udom,$uname,$cid);
7817: } else {
7818: return 'error: '.$reply;
7819: }
7820: # Add student role to user
7821: my $uurl='/'.$cid;
7822: $uurl=~s/\_/\//g;
7823: if ($usec) {
7824: $uurl.='/'.$usec;
7825: }
7826: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7827: $selfenroll,$context);
7828: if ($result ne 'ok') {
7829: if ($old_entry{$user} ne '') {
7830: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7831: } else {
7832: $reply = &del('classlist',[$user],$cdom,$cnum);
7833: }
7834: }
7835: return $result;
7836: }
7837:
7838: sub format_name {
7839: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7840: my $name;
7841: if ($first ne 'lastname') {
7842: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7843: } else {
7844: if ($lastname=~/\S/) {
7845: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7846: $name=~s/\s+,/,/;
7847: } else {
7848: $name.= $firstname.' '.$middlename.' '.$generation;
7849: }
7850: }
7851: $name=~s/^\s+//;
7852: $name=~s/\s+$//;
7853: $name=~s/\s+/ /g;
7854: return $name;
7855: }
7856:
7857: # ------------------------------------------------- Write to course preferences
7858:
7859: sub writecoursepref {
7860: my ($courseid,%prefs)=@_;
7861: $courseid=~s/^\///;
7862: $courseid=~s/\_/\//g;
7863: my ($cdomain,$cnum)=split(/\//,$courseid);
7864: my $chome=homeserver($cnum,$cdomain);
7865: if (($chome eq '') || ($chome eq 'no_host')) {
7866: return 'error: no such course';
7867: }
7868: my $cstring='';
7869: foreach my $pref (keys(%prefs)) {
7870: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7871: }
7872: $cstring=~s/\&$//;
7873: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7874: }
7875:
7876: # ---------------------------------------------------------- Make/modify course
7877:
7878: sub createcourse {
7879: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7880: $course_owner,$crstype,$cnum,$context,$category)=@_;
7881: $url=&declutter($url);
7882: my $cid='';
7883: if ($context eq 'requestcourses') {
7884: my $can_create = 0;
7885: my ($ownername,$ownerdom) = split(':',$course_owner);
7886: if ($udom eq $ownerdom) {
7887: if (&usertools_access($ownername,$ownerdom,$category,undef,
7888: $context)) {
7889: $can_create = 1;
7890: }
7891: } else {
7892: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7893: $category);
7894: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7895: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7896: if (@curr > 0) {
7897: my @options = qw(approval validate autolimit);
7898: my $optregex = join('|',@options);
7899: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7900: $can_create = 1;
7901: }
7902: }
7903: }
7904: }
7905: if ($can_create) {
7906: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7907: unless (&allowed('ccc',$udom)) {
7908: return 'refused';
7909: }
7910: }
7911: } else {
7912: return 'refused';
7913: }
7914: } elsif (!&allowed('ccc',$udom)) {
7915: return 'refused';
7916: }
7917: # --------------------------------------------------------------- Get Unique ID
7918: my $uname;
7919: if ($cnum =~ /^$match_courseid$/) {
7920: my $chome=&homeserver($cnum,$udom,'true');
7921: if (($chome eq '') || ($chome eq 'no_host')) {
7922: $uname = $cnum;
7923: } else {
7924: $uname = &generate_coursenum($udom,$crstype);
7925: }
7926: } else {
7927: $uname = &generate_coursenum($udom,$crstype);
7928: }
7929: return $uname if ($uname =~ /^error/);
7930: # -------------------------------------------------- Check supplied server name
7931: if (!defined($course_server)) {
7932: if (defined(&domain($udom,'primary'))) {
7933: $course_server = &domain($udom,'primary');
7934: } else {
7935: $course_server = $env{'user.home'};
7936: }
7937: }
7938: my %host_servers =
7939: &Apache::lonnet::get_servers($udom,'library');
7940: unless ($host_servers{$course_server}) {
7941: return 'error: invalid home server for course: '.$course_server;
7942: }
7943: # ------------------------------------------------------------- Make the course
7944: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
7945: $course_server);
7946: unless ($reply eq 'ok') { return 'error: '.$reply; }
7947: my $uhome=&homeserver($uname,$udom,'true');
7948: if (($uhome eq '') || ($uhome eq 'no_host')) {
7949: return 'error: no such course';
7950: }
7951: # ----------------------------------------------------------------- Course made
7952: # log existence
7953: my $now = time;
7954: my $newcourse = {
7955: $udom.'_'.$uname => {
7956: description => $description,
7957: inst_code => $inst_code,
7958: owner => $course_owner,
7959: type => $crstype,
7960: creator => $env{'user.name'}.':'.
7961: $env{'user.domain'},
7962: created => $now,
7963: context => $context,
7964: },
7965: };
7966: &courseidput($udom,$newcourse,$uhome,'notime');
7967: # set toplevel url
7968: my $topurl=$url;
7969: unless ($nonstandard) {
7970: # ------------------------------------------ For standard courses, make top url
7971: my $mapurl=&clutter($url);
7972: if ($mapurl eq '/res/') { $mapurl=''; }
7973: $env{'form.initmap'}=(<<ENDINITMAP);
7974: <map>
7975: <resource id="1" type="start"></resource>
7976: <resource id="2" src="$mapurl"></resource>
7977: <resource id="3" type="finish"></resource>
7978: <link index="1" from="1" to="2"></link>
7979: <link index="2" from="2" to="3"></link>
7980: </map>
7981: ENDINITMAP
7982: $topurl=&declutter(
7983: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
7984: );
7985: }
7986: # ----------------------------------------------------------- Write preferences
7987: &writecoursepref($udom.'_'.$uname,
7988: ('description' => $description,
7989: 'url' => $topurl,
7990: 'internal.creator' => $env{'user.name'}.':'.
7991: $env{'user.domain'},
7992: 'internal.created' => $now,
7993: 'internal.creationcontext' => $context)
7994: );
7995: return '/'.$udom.'/'.$uname;
7996: }
7997:
7998: # ------------------------------------------------------------------- Create ID
7999: sub generate_coursenum {
8000: my ($udom,$crstype) = @_;
8001: my $domdesc = &domain($udom);
8002: return 'error: invalid domain' if ($domdesc eq '');
8003: my $first;
8004: if ($crstype eq 'Community') {
8005: $first = '0';
8006: } else {
8007: $first = int(1+rand(9));
8008: }
8009: my $uname=$first.
8010: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8011: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8012: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8013: # ----------------------------------------------- Make sure that does not exist
8014: my $uhome=&homeserver($uname,$udom,'true');
8015: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8016: if ($crstype eq 'Community') {
8017: $first = '0';
8018: } else {
8019: $first = int(1+rand(9));
8020: }
8021: $uname=$first.
8022: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8023: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8024: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8025: $uhome=&homeserver($uname,$udom,'true');
8026: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8027: return 'error: unable to generate unique course-ID';
8028: }
8029: }
8030: return $uname;
8031: }
8032:
8033: sub is_course {
8034: my ($cdom,$cnum) = @_;
8035: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
8036: undef,'.');
8037: if (exists($courses{$cdom.'_'.$cnum})) {
8038: return 1;
8039: }
8040: return 0;
8041: }
8042:
8043: sub store_userdata {
8044: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8045: my $result;
8046: if ($datakey ne '') {
8047: if (ref($storehash) eq 'HASH') {
8048: if ($udom eq '' || $uname eq '') {
8049: $udom = $env{'user.domain'};
8050: $uname = $env{'user.name'};
8051: }
8052: my $uhome=&homeserver($uname,$udom);
8053: if (($uhome eq '') || ($uhome eq 'no_host')) {
8054: $result = 'error: no_host';
8055: } else {
8056: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8057: $storehash->{'host'} = $perlvar{'lonHostID'};
8058:
8059: my $namevalue='';
8060: foreach my $key (keys(%{$storehash})) {
8061: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8062: }
8063: $namevalue=~s/\&$//;
8064: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8065: $namevalue,$uhome);
8066: }
8067: } else {
8068: $result = 'error: data to store was not a hash reference';
8069: }
8070: } else {
8071: $result= 'error: invalid requestkey';
8072: }
8073: return $result;
8074: }
8075:
8076: # ---------------------------------------------------------- Assign Custom Role
8077:
8078: sub assigncustomrole {
8079: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
8080: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
8081: $end,$start,$deleteflag,$selfenroll,$context);
8082: }
8083:
8084: # ----------------------------------------------------------------- Revoke Role
8085:
8086: sub revokerole {
8087: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
8088: my $now=time;
8089: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
8090: }
8091:
8092: # ---------------------------------------------------------- Revoke Custom Role
8093:
8094: sub revokecustomrole {
8095: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
8096: my $now=time;
8097: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
8098: $deleteflag,$selfenroll,$context);
8099: }
8100:
8101: # ------------------------------------------------------------ Disk usage
8102: sub diskusage {
8103: my ($udom,$uname,$directorypath,$getpropath)=@_;
8104: $directorypath =~ s/\/$//;
8105: my $listing=&reply('du2:'.&escape($directorypath).':'
8106: .&escape($getpropath).':'.&escape($uname).':'
8107: .&escape($udom),homeserver($uname,$udom));
8108: if ($listing eq 'unknown_cmd') {
8109: if ($getpropath) {
8110: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8111: }
8112: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8113: }
8114: return $listing;
8115: }
8116:
8117: sub is_locked {
8118: my ($file_name, $domain, $user, $which) = @_;
8119: my @check;
8120: my $is_locked;
8121: push (@check,$file_name);
8122: my %locked = &get('file_permissions',\@check,
8123: $env{'user.domain'},$env{'user.name'});
8124: my ($tmp)=keys(%locked);
8125: if ($tmp=~/^error:/) { undef(%locked); }
8126:
8127: if (ref($locked{$file_name}) eq 'ARRAY') {
8128: $is_locked = 'false';
8129: foreach my $entry (@{$locked{$file_name}}) {
8130: if (ref($entry) eq 'ARRAY') {
8131: $is_locked = 'true';
8132: if (ref($which) eq 'ARRAY') {
8133: push(@{$which},$entry);
8134: } else {
8135: last;
8136: }
8137: }
8138: }
8139: } else {
8140: $is_locked = 'false';
8141: }
8142: return $is_locked;
8143: }
8144:
8145: sub declutter_portfile {
8146: my ($file) = @_;
8147: $file =~ s{^(/portfolio/|portfolio/)}{/};
8148: return $file;
8149: }
8150:
8151: # ------------------------------------------------------------- Mark as Read Only
8152:
8153: sub mark_as_readonly {
8154: my ($domain,$user,$files,$what) = @_;
8155: my %current_permissions = &dump('file_permissions',$domain,$user);
8156: my ($tmp)=keys(%current_permissions);
8157: if ($tmp=~/^error:/) { undef(%current_permissions); }
8158: foreach my $file (@{$files}) {
8159: $file = &declutter_portfile($file);
8160: push(@{$current_permissions{$file}},$what);
8161: }
8162: &put('file_permissions',\%current_permissions,$domain,$user);
8163: return;
8164: }
8165:
8166: # ------------------------------------------------------------Save Selected Files
8167:
8168: sub save_selected_files {
8169: my ($user, $path, @files) = @_;
8170: my $filename = $user."savedfiles";
8171: my @other_files = &files_not_in_path($user, $path);
8172: open (OUT, '>'.$tmpdir.$filename);
8173: foreach my $file (@files) {
8174: print (OUT $env{'form.currentpath'}.$file."\n");
8175: }
8176: foreach my $file (@other_files) {
8177: print (OUT $file."\n");
8178: }
8179: close (OUT);
8180: return 'ok';
8181: }
8182:
8183: sub clear_selected_files {
8184: my ($user) = @_;
8185: my $filename = $user."savedfiles";
8186: open (OUT, '>'.LONCAPA::tempdir().$filename);
8187: print (OUT undef);
8188: close (OUT);
8189: return ("ok");
8190: }
8191:
8192: sub files_in_path {
8193: my ($user, $path) = @_;
8194: my $filename = $user."savedfiles";
8195: my %return_files;
8196: open (IN, '<'.LONCAPA::tempdir().$filename);
8197: while (my $line_in = <IN>) {
8198: chomp ($line_in);
8199: my @paths_and_file = split (m!/!, $line_in);
8200: my $file_part = pop (@paths_and_file);
8201: my $path_part = join ('/', @paths_and_file);
8202: $path_part.='/';
8203: my $path_and_file = $path_part.$file_part;
8204: if ($path_part eq $path) {
8205: $return_files{$file_part}= 'selected';
8206: }
8207: }
8208: close (IN);
8209: return (\%return_files);
8210: }
8211:
8212: # called in portfolio select mode, to show files selected NOT in current directory
8213: sub files_not_in_path {
8214: my ($user, $path) = @_;
8215: my $filename = $user."savedfiles";
8216: my @return_files;
8217: my $path_part;
8218: open(IN, '<'.LONCAPA::.$filename);
8219: while (my $line = <IN>) {
8220: #ok, I know it's clunky, but I want it to work
8221: my @paths_and_file = split(m|/|, $line);
8222: my $file_part = pop(@paths_and_file);
8223: chomp($file_part);
8224: my $path_part = join('/', @paths_and_file);
8225: $path_part .= '/';
8226: my $path_and_file = $path_part.$file_part;
8227: if ($path_part ne $path) {
8228: push(@return_files, ($path_and_file));
8229: }
8230: }
8231: close(OUT);
8232: return (@return_files);
8233: }
8234:
8235: #----------------------------------------------Get portfolio file permissions
8236:
8237: sub get_portfile_permissions {
8238: my ($domain,$user) = @_;
8239: my %current_permissions = &dump('file_permissions',$domain,$user);
8240: my ($tmp)=keys(%current_permissions);
8241: if ($tmp=~/^error:/) { undef(%current_permissions); }
8242: return \%current_permissions;
8243: }
8244:
8245: #---------------------------------------------Get portfolio file access controls
8246:
8247: sub get_access_controls {
8248: my ($current_permissions,$group,$file) = @_;
8249: my %access;
8250: my $real_file = $file;
8251: $file =~ s/\.meta$//;
8252: if (defined($file)) {
8253: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8254: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
8255: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
8256: }
8257: }
8258: } else {
8259: foreach my $key (keys(%{$current_permissions})) {
8260: if ($key =~ /\0accesscontrol$/) {
8261: if (defined($group)) {
8262: if ($key !~ m-^\Q$group\E/-) {
8263: next;
8264: }
8265: }
8266: my ($fullpath) = split(/\0/,$key);
8267: if (ref($$current_permissions{$key}) eq 'HASH') {
8268: foreach my $control (keys(%{$$current_permissions{$key}})) {
8269: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8270: }
8271: }
8272: }
8273: }
8274: }
8275: return %access;
8276: }
8277:
8278: sub modify_access_controls {
8279: my ($file_name,$changes,$domain,$user)=@_;
8280: my ($outcome,$deloutcome);
8281: my %store_permissions;
8282: my %new_values;
8283: my %new_control;
8284: my %translation;
8285: my @deletions = ();
8286: my $now = time;
8287: if (exists($$changes{'activate'})) {
8288: if (ref($$changes{'activate'}) eq 'HASH') {
8289: my @newitems = sort(keys(%{$$changes{'activate'}}));
8290: my $numnew = scalar(@newitems);
8291: for (my $i=0; $i<$numnew; $i++) {
8292: my $newkey = $newitems[$i];
8293: my $newid = &Apache::loncommon::get_cgi_id();
8294: if ($newkey =~ /^\d+:/) {
8295: $newkey =~ s/^(\d+)/$newid/;
8296: $translation{$1} = $newid;
8297: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8298: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8299: $translation{$1} = $newid;
8300: }
8301: $new_values{$file_name."\0".$newkey} =
8302: $$changes{'activate'}{$newitems[$i]};
8303: $new_control{$newkey} = $now;
8304: }
8305: }
8306: }
8307: my %todelete;
8308: my %changed_items;
8309: foreach my $action ('delete','update') {
8310: if (exists($$changes{$action})) {
8311: if (ref($$changes{$action}) eq 'HASH') {
8312: foreach my $key (keys(%{$$changes{$action}})) {
8313: my ($itemnum) = ($key =~ /^([^:]+):/);
8314: if ($action eq 'delete') {
8315: $todelete{$itemnum} = 1;
8316: } else {
8317: $changed_items{$itemnum} = $key;
8318: }
8319: }
8320: }
8321: }
8322: }
8323: # get lock on access controls for file.
8324: my $lockhash = {
8325: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8326: ':'.$env{'user.domain'},
8327: };
8328: my $tries = 0;
8329: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8330:
8331: while (($gotlock ne 'ok') && $tries <3) {
8332: $tries ++;
8333: sleep 1;
8334: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8335: }
8336: if ($gotlock eq 'ok') {
8337: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8338: my ($tmp)=keys(%curr_permissions);
8339: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8340: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8341: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8342: if (ref($curr_controls) eq 'HASH') {
8343: foreach my $control_item (keys(%{$curr_controls})) {
8344: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8345: if (defined($todelete{$itemnum})) {
8346: push(@deletions,$file_name."\0".$control_item);
8347: } else {
8348: if (defined($changed_items{$itemnum})) {
8349: $new_control{$changed_items{$itemnum}} = $now;
8350: push(@deletions,$file_name."\0".$control_item);
8351: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8352: } else {
8353: $new_control{$control_item} = $$curr_controls{$control_item};
8354: }
8355: }
8356: }
8357: }
8358: }
8359: my ($group);
8360: if (&is_course($domain,$user)) {
8361: ($group,my $file) = split(/\//,$file_name,2);
8362: }
8363: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8364: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8365: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8366: # remove lock
8367: my @del_lock = ($file_name."\0".'locked_access_records');
8368: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
8369: my $sqlresult =
8370: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
8371: $group);
8372: } else {
8373: $outcome = "error: could not obtain lockfile\n";
8374: }
8375: return ($outcome,$deloutcome,\%new_values,\%translation);
8376: }
8377:
8378: sub make_public_indefinitely {
8379: my ($requrl) = @_;
8380: my $now = time;
8381: my $action = 'activate';
8382: my $aclnum = 0;
8383: if (&is_portfolio_url($requrl)) {
8384: my (undef,$udom,$unum,$file_name,$group) =
8385: &parse_portfolio_url($requrl);
8386: my $current_perms = &get_portfile_permissions($udom,$unum);
8387: my %access_controls = &get_access_controls($current_perms,
8388: $group,$file_name);
8389: foreach my $key (keys(%{$access_controls{$file_name}})) {
8390: my ($num,$scope,$end,$start) =
8391: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8392: if ($scope eq 'public') {
8393: if ($start <= $now && $end == 0) {
8394: $action = 'none';
8395: } else {
8396: $action = 'update';
8397: $aclnum = $num;
8398: }
8399: last;
8400: }
8401: }
8402: if ($action eq 'none') {
8403: return 'ok';
8404: } else {
8405: my %changes;
8406: my $newend = 0;
8407: my $newstart = $now;
8408: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8409: $changes{$action}{$newkey} = {
8410: type => 'public',
8411: time => {
8412: start => $newstart,
8413: end => $newend,
8414: },
8415: };
8416: my ($outcome,$deloutcome,$new_values,$translation) =
8417: &modify_access_controls($file_name,\%changes,$udom,$unum);
8418: return $outcome;
8419: }
8420: } else {
8421: return 'invalid';
8422: }
8423: }
8424:
8425: #------------------------------------------------------Get Marked as Read Only
8426:
8427: sub get_marked_as_readonly {
8428: my ($domain,$user,$what,$group) = @_;
8429: my $current_permissions = &get_portfile_permissions($domain,$user);
8430: my @readonly_files;
8431: my $cmp1=$what;
8432: if (ref($what)) { $cmp1=join('',@{$what}) };
8433: while (my ($file_name,$value) = each(%{$current_permissions})) {
8434: if (defined($group)) {
8435: if ($file_name !~ m-^\Q$group\E/-) {
8436: next;
8437: }
8438: }
8439: if (ref($value) eq "ARRAY"){
8440: foreach my $stored_what (@{$value}) {
8441: my $cmp2=$stored_what;
8442: if (ref($stored_what) eq 'ARRAY') {
8443: $cmp2=join('',@{$stored_what});
8444: }
8445: if ($cmp1 eq $cmp2) {
8446: push(@readonly_files, $file_name);
8447: last;
8448: } elsif (!defined($what)) {
8449: push(@readonly_files, $file_name);
8450: last;
8451: }
8452: }
8453: }
8454: }
8455: return @readonly_files;
8456: }
8457: #-----------------------------------------------------------Get Marked as Read Only Hash
8458:
8459: sub get_marked_as_readonly_hash {
8460: my ($current_permissions,$group,$what) = @_;
8461: my %readonly_files;
8462: while (my ($file_name,$value) = each(%{$current_permissions})) {
8463: if (defined($group)) {
8464: if ($file_name !~ m-^\Q$group\E/-) {
8465: next;
8466: }
8467: }
8468: if (ref($value) eq "ARRAY"){
8469: foreach my $stored_what (@{$value}) {
8470: if (ref($stored_what) eq 'ARRAY') {
8471: foreach my $lock_descriptor(@{$stored_what}) {
8472: if ($lock_descriptor eq 'graded') {
8473: $readonly_files{$file_name} = 'graded';
8474: } elsif ($lock_descriptor eq 'handback') {
8475: $readonly_files{$file_name} = 'handback';
8476: } else {
8477: if (!exists($readonly_files{$file_name})) {
8478: $readonly_files{$file_name} = 'locked';
8479: }
8480: }
8481: }
8482: }
8483: }
8484: }
8485: }
8486: return %readonly_files;
8487: }
8488: # ------------------------------------------------------------ Unmark as Read Only
8489:
8490: sub unmark_as_readonly {
8491: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8492: # for portfolio submissions, $what contains [$symb,$crsid]
8493: my ($domain,$user,$what,$file_name,$group) = @_;
8494: $file_name = &declutter_portfile($file_name);
8495: my $symb_crs = $what;
8496: if (ref($what)) { $symb_crs=join('',@$what); }
8497: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
8498: my ($tmp)=keys(%current_permissions);
8499: if ($tmp=~/^error:/) { undef(%current_permissions); }
8500: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
8501: foreach my $file (@readonly_files) {
8502: my $clean_file = &declutter_portfile($file);
8503: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
8504: my $current_locks = $current_permissions{$file};
8505: my @new_locks;
8506: my @del_keys;
8507: if (ref($current_locks) eq "ARRAY"){
8508: foreach my $locker (@{$current_locks}) {
8509: my $compare=$locker;
8510: if (ref($locker) eq 'ARRAY') {
8511: $compare=join('',@{$locker});
8512: if ($compare ne $symb_crs) {
8513: push(@new_locks, $locker);
8514: }
8515: }
8516: }
8517: if (scalar(@new_locks) > 0) {
8518: $current_permissions{$file} = \@new_locks;
8519: } else {
8520: push(@del_keys, $file);
8521: &del('file_permissions',\@del_keys, $domain, $user);
8522: delete($current_permissions{$file});
8523: }
8524: }
8525: }
8526: &put('file_permissions',\%current_permissions,$domain,$user);
8527: return;
8528: }
8529:
8530: # ------------------------------------------------------------ Directory lister
8531:
8532: sub dirlist {
8533: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
8534: $uri=~s/^\///;
8535: $uri=~s/\/$//;
8536: my ($udom, $uname);
8537: if ($getuserdir) {
8538: $udom = $userdomain;
8539: $uname = $username;
8540: } else {
8541: (undef,$udom,$uname)=split(/\//,$uri);
8542: if(defined($userdomain)) {
8543: $udom = $userdomain;
8544: }
8545: if(defined($username)) {
8546: $uname = $username;
8547: }
8548: }
8549: my ($dirRoot,$listing,@listing_results);
8550:
8551: $dirRoot = $perlvar{'lonDocRoot'};
8552: if (defined($getpropath)) {
8553: $dirRoot = &propath($udom,$uname);
8554: $dirRoot =~ s/\/$//;
8555: } elsif (defined($getuserdir)) {
8556: my $subdir=$uname.'__';
8557: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8558: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8559: ."/$udom/$subdir/$uname";
8560: } elsif (defined($alternateRoot)) {
8561: $dirRoot = $alternateRoot;
8562: }
8563:
8564: if($udom) {
8565: if($uname) {
8566: my $uhome = &homeserver($uname,$udom);
8567: if ($uhome eq 'no_host') {
8568: return ([],'no_host');
8569: }
8570: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
8571: .$getuserdir.':'.&escape($dirRoot)
8572: .':'.&escape($uname).':'.&escape($udom),$uhome);
8573: if ($listing eq 'unknown_cmd') {
8574: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
8575: } else {
8576: @listing_results = map { &unescape($_); } split(/:/,$listing);
8577: }
8578: if ($listing eq 'unknown_cmd') {
8579: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
8580: @listing_results = split(/:/,$listing);
8581: } else {
8582: @listing_results = map { &unescape($_); } split(/:/,$listing);
8583: }
8584: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8585: ($listing eq 'rejected') || ($listing eq 'refused') ||
8586: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8587: return ([],$listing);
8588: } else {
8589: return (\@listing_results);
8590: }
8591: } elsif(!$alternateRoot) {
8592: my (%allusers,%listerror);
8593: my %servers = &get_servers($udom,'library');
8594: foreach my $tryserver (keys(%servers)) {
8595: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8596: &escape($udom),$tryserver);
8597: if ($listing eq 'unknown_cmd') {
8598: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8599: $udom, $tryserver);
8600: } else {
8601: @listing_results = map { &unescape($_); } split(/:/,$listing);
8602: }
8603: if ($listing eq 'unknown_cmd') {
8604: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8605: $udom, $tryserver);
8606: @listing_results = split(/:/,$listing);
8607: } else {
8608: @listing_results =
8609: map { &unescape($_); } split(/:/,$listing);
8610: }
8611: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8612: ($listing eq 'rejected') || ($listing eq 'refused') ||
8613: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8614: $listerror{$tryserver} = $listing;
8615: } else {
8616: foreach my $line (@listing_results) {
8617: my ($entry) = split(/&/,$line,2);
8618: $allusers{$entry} = 1;
8619: }
8620: }
8621: }
8622: my @alluserslist=();
8623: foreach my $user (sort(keys(%allusers))) {
8624: push(@alluserslist,$user.'&user');
8625: }
8626: return (\@alluserslist);
8627: } else {
8628: return ([],'missing username');
8629: }
8630: } elsif(!defined($getpropath)) {
8631: my $path = $perlvar{'lonDocRoot'}.'/res/';
8632: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8633: return (\@all_domains);
8634: } else {
8635: return ([],'missing domain');
8636: }
8637: }
8638:
8639: # --------------------------------------------- GetFileTimestamp
8640: # This function utilizes dirlist and returns the date stamp for
8641: # when it was last modified. It will also return an error of -1
8642: # if an error occurs
8643:
8644: sub GetFileTimestamp {
8645: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
8646: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8647: $studentName = &LONCAPA::clean_username($studentName);
8648: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8649: undef,$getuserdir);
8650: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8651: return -1;
8652: }
8653: if (ref($fileref) eq 'ARRAY') {
8654: my @stats = split('&',$fileref->[0]);
8655: # @stats contains first the filename, then the stat output
8656: return $stats[10]; # so this is 10 instead of 9.
8657: } else {
8658: return -1;
8659: }
8660: }
8661:
8662: sub stat_file {
8663: my ($uri) = @_;
8664: $uri = &clutter_with_no_wrapper($uri);
8665:
8666: my ($udom,$uname,$file);
8667: if ($uri =~ m-^/(uploaded|editupload)/-) {
8668: ($udom,$uname,$file) =
8669: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8670: $file = 'userfiles/'.$file;
8671: }
8672: if ($uri =~ m-^/res/-) {
8673: ($udom,$uname) =
8674: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8675: $file = $uri;
8676: }
8677:
8678: if (!$udom || !$uname || !$file) {
8679: # unable to handle the uri
8680: return ();
8681: }
8682: my $getpropath;
8683: if ($file =~ /^userfiles\//) {
8684: $getpropath = 1;
8685: }
8686: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8687: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8688: return ();
8689: } else {
8690: if (ref($listref) eq 'ARRAY') {
8691: my @stats = split('&',$listref->[0]);
8692: shift(@stats); #filename is first
8693: return @stats;
8694: }
8695: }
8696: return ();
8697: }
8698:
8699: # -------------------------------------------------------- Value of a Condition
8700:
8701: # gets the value of a specific preevaluated condition
8702: # stored in the string $env{user.state.<cid>}
8703: # or looks up a condition reference in the bighash and if if hasn't
8704: # already been evaluated recurses into docondval to get the value of
8705: # the condition, then memoizing it to
8706: # $env{user.state.<cid>.<condition>}
8707: sub directcondval {
8708: my $number=shift;
8709: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8710: &Apache::lonuserstate::evalstate();
8711: }
8712: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8713: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8714: } elsif ($number =~ /^_/) {
8715: my $sub_condition;
8716: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8717: &GDBM_READER(),0640)) {
8718: $sub_condition=$bighash{'conditions'.$number};
8719: untie(%bighash);
8720: }
8721: my $value = &docondval($sub_condition);
8722: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8723: return $value;
8724: }
8725: if ($env{'user.state.'.$env{'request.course.id'}}) {
8726: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8727: } else {
8728: return 2;
8729: }
8730: }
8731:
8732: # get the collection of conditions for this resource
8733: sub condval {
8734: my $condidx=shift;
8735: my $allpathcond='';
8736: foreach my $cond (split(/\|/,$condidx)) {
8737: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8738: $allpathcond.=
8739: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8740: }
8741: }
8742: $allpathcond=~s/\|$//;
8743: return &docondval($allpathcond);
8744: }
8745:
8746: #evaluates an expression of conditions
8747: sub docondval {
8748: my ($allpathcond) = @_;
8749: my $result=0;
8750: if ($env{'request.course.id'}
8751: && defined($allpathcond)) {
8752: my $operand='|';
8753: my @stack;
8754: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8755: if ($chunk eq '(') {
8756: push @stack,($operand,$result);
8757: } elsif ($chunk eq ')') {
8758: my $before=pop @stack;
8759: if (pop @stack eq '&') {
8760: $result=$result>$before?$before:$result;
8761: } else {
8762: $result=$result>$before?$result:$before;
8763: }
8764: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8765: $operand=$chunk;
8766: } else {
8767: my $new=directcondval($chunk);
8768: if ($operand eq '&') {
8769: $result=$result>$new?$new:$result;
8770: } else {
8771: $result=$result>$new?$result:$new;
8772: }
8773: }
8774: }
8775: }
8776: return $result;
8777: }
8778:
8779: # ---------------------------------------------------- Devalidate courseresdata
8780:
8781: sub devalidatecourseresdata {
8782: my ($coursenum,$coursedomain)=@_;
8783: my $hashid=$coursenum.':'.$coursedomain;
8784: &devalidate_cache_new('courseres',$hashid);
8785: }
8786:
8787:
8788: # --------------------------------------------------- Course Resourcedata Query
8789: #
8790: # Parameters:
8791: # $coursenum - Number of the course.
8792: # $coursedomain - Domain at which the course was created.
8793: # Returns:
8794: # A hash of the course parameters along (I think) with timestamps
8795: # and version info.
8796:
8797: sub get_courseresdata {
8798: my ($coursenum,$coursedomain)=@_;
8799: my $coursehom=&homeserver($coursenum,$coursedomain);
8800: my $hashid=$coursenum.':'.$coursedomain;
8801: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8802: my %dumpreply;
8803: unless (defined($cached)) {
8804: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8805: $result=\%dumpreply;
8806: my ($tmp) = keys(%dumpreply);
8807: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8808: &do_cache_new('courseres',$hashid,$result,600);
8809: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8810: return $tmp;
8811: } elsif ($tmp =~ /^(error)/) {
8812: $result=undef;
8813: &do_cache_new('courseres',$hashid,$result,600);
8814: }
8815: }
8816: return $result;
8817: }
8818:
8819: sub devalidateuserresdata {
8820: my ($uname,$udom)=@_;
8821: my $hashid="$udom:$uname";
8822: &devalidate_cache_new('userres',$hashid);
8823: }
8824:
8825: sub get_userresdata {
8826: my ($uname,$udom)=@_;
8827: #most student don\'t have any data set, check if there is some data
8828: if (&EXT_cache_status($udom,$uname)) { return undef; }
8829:
8830: my $hashid="$udom:$uname";
8831: my ($result,$cached)=&is_cached_new('userres',$hashid);
8832: if (!defined($cached)) {
8833: my %resourcedata=&dump('resourcedata',$udom,$uname);
8834: $result=\%resourcedata;
8835: &do_cache_new('userres',$hashid,$result,600);
8836: }
8837: my ($tmp)=keys(%$result);
8838: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8839: return $result;
8840: }
8841: #error 2 occurs when the .db doesn't exist
8842: if ($tmp!~/error: 2 /) {
8843: &logthis("<font color=\"blue\">WARNING:".
8844: " Trying to get resource data for ".
8845: $uname." at ".$udom.": ".
8846: $tmp."</font>");
8847: } elsif ($tmp=~/error: 2 /) {
8848: #&EXT_cache_set($udom,$uname);
8849: &do_cache_new('userres',$hashid,undef,600);
8850: undef($tmp); # not really an error so don't send it back
8851: }
8852: return $tmp;
8853: }
8854: #----------------------------------------------- resdata - return resource data
8855: # Purpose:
8856: # Return resource data for either users or for a course.
8857: # Parameters:
8858: # $name - Course/user name.
8859: # $domain - Name of the domain the user/course is registered on.
8860: # $type - Type of thing $name is (must be 'course' or 'user'
8861: # @which - Array of names of resources desired.
8862: # Returns:
8863: # The value of the first reasource in @which that is found in the
8864: # resource hash.
8865: # Exceptional Conditions:
8866: # If the $type passed in is not valid (not the string 'course' or
8867: # 'user', an undefined reference is returned.
8868: # If none of the resources are found, an undef is returned
8869: sub resdata {
8870: my ($name,$domain,$type,@which)=@_;
8871: my $result;
8872: if ($type eq 'course') {
8873: $result=&get_courseresdata($name,$domain);
8874: } elsif ($type eq 'user') {
8875: $result=&get_userresdata($name,$domain);
8876: }
8877: if (!ref($result)) { return $result; }
8878: foreach my $item (@which) {
8879: if (defined($result->{$item->[0]})) {
8880: return [$result->{$item->[0]},$item->[1]];
8881: }
8882: }
8883: return undef;
8884: }
8885:
8886: #
8887: # EXT resource caching routines
8888: #
8889:
8890: sub clear_EXT_cache_status {
8891: &delenv('cache.EXT.');
8892: }
8893:
8894: sub EXT_cache_status {
8895: my ($target_domain,$target_user) = @_;
8896: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8897: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8898: # We know already the user has no data
8899: return 1;
8900: } else {
8901: return 0;
8902: }
8903: }
8904:
8905: sub EXT_cache_set {
8906: my ($target_domain,$target_user) = @_;
8907: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8908: #&appenv({$cachename => time});
8909: }
8910:
8911: # --------------------------------------------------------- Value of a Variable
8912: sub EXT {
8913:
8914: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8915: unless ($varname) { return ''; }
8916: #get real user name/domain, courseid and symb
8917: my $courseid;
8918: my $publicuser;
8919: if ($symbparm) {
8920: $symbparm=&get_symb_from_alias($symbparm);
8921: }
8922: if (!($uname && $udom)) {
8923: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8924: if (!$symbparm) { $symbparm=$cursymb; }
8925: } else {
8926: $courseid=$env{'request.course.id'};
8927: }
8928: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8929: my $rest;
8930: if (defined($therest[0])) {
8931: $rest=join('.',@therest);
8932: } else {
8933: $rest='';
8934: }
8935:
8936: my $qualifierrest=$qualifier;
8937: if ($rest) { $qualifierrest.='.'.$rest; }
8938: my $spacequalifierrest=$space;
8939: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
8940: if ($realm eq 'user') {
8941: # --------------------------------------------------------------- user.resource
8942: if ($space eq 'resource') {
8943: if ( (defined($Apache::lonhomework::parsing_a_problem)
8944: || defined($Apache::lonhomework::parsing_a_task))
8945: &&
8946: ($symbparm eq &symbread()) ) {
8947: # if we are in the middle of processing the resource the
8948: # get the value we are planning on committing
8949: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8950: return $Apache::lonhomework::results{$qualifierrest};
8951: } else {
8952: return $Apache::lonhomework::history{$qualifierrest};
8953: }
8954: } else {
8955: my %restored;
8956: if ($publicuser || $env{'request.state'} eq 'construct') {
8957: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8958: } else {
8959: %restored=&restore($symbparm,$courseid,$udom,$uname);
8960: }
8961: return $restored{$qualifierrest};
8962: }
8963: # ----------------------------------------------------------------- user.access
8964: } elsif ($space eq 'access') {
8965: # FIXME - not supporting calls for a specific user
8966: return &allowed($qualifier,$rest);
8967: # ------------------------------------------ user.preferences, user.environment
8968: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
8969: if (($uname eq $env{'user.name'}) &&
8970: ($udom eq $env{'user.domain'})) {
8971: return $env{join('.',('environment',$qualifierrest))};
8972: } else {
8973: my %returnhash;
8974: if (!$publicuser) {
8975: %returnhash=&userenvironment($udom,$uname,
8976: $qualifierrest);
8977: }
8978: return $returnhash{$qualifierrest};
8979: }
8980: # ----------------------------------------------------------------- user.course
8981: } elsif ($space eq 'course') {
8982: # FIXME - not supporting calls for a specific user
8983: return $env{join('.',('request.course',$qualifier))};
8984: # ------------------------------------------------------------------- user.role
8985: } elsif ($space eq 'role') {
8986: # FIXME - not supporting calls for a specific user
8987: my ($role,$where)=split(/\./,$env{'request.role'});
8988: if ($qualifier eq 'value') {
8989: return $role;
8990: } elsif ($qualifier eq 'extent') {
8991: return $where;
8992: }
8993: # ----------------------------------------------------------------- user.domain
8994: } elsif ($space eq 'domain') {
8995: return $udom;
8996: # ------------------------------------------------------------------- user.name
8997: } elsif ($space eq 'name') {
8998: return $uname;
8999: # ---------------------------------------------------- Any other user namespace
9000: } else {
9001: my %reply;
9002: if (!$publicuser) {
9003: %reply=&get($space,[$qualifierrest],$udom,$uname);
9004: }
9005: return $reply{$qualifierrest};
9006: }
9007: } elsif ($realm eq 'query') {
9008: # ---------------------------------------------- pull stuff out of query string
9009: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9010: [$spacequalifierrest]);
9011: return $env{'form.'.$spacequalifierrest};
9012: } elsif ($realm eq 'request') {
9013: # ------------------------------------------------------------- request.browser
9014: if ($space eq 'browser') {
9015: return $env{'browser.'.$qualifier};
9016: # ------------------------------------------------------------ request.filename
9017: } else {
9018: return $env{'request.'.$spacequalifierrest};
9019: }
9020: } elsif ($realm eq 'course') {
9021: # ---------------------------------------------------------- course.description
9022: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
9023: } elsif ($realm eq 'resource') {
9024:
9025: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
9026: if (!$symbparm) { $symbparm=&symbread(); }
9027: }
9028:
9029: if ($space eq 'title') {
9030: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9031: return &gettitle($symbparm);
9032: }
9033:
9034: if ($space eq 'map') {
9035: my ($map) = &decode_symb($symbparm);
9036: return &symbread($map);
9037: }
9038: if ($space eq 'filename') {
9039: if ($symbparm) {
9040: return &clutter((&decode_symb($symbparm))[2]);
9041: }
9042: return &hreflocation('',$env{'request.filename'});
9043: }
9044:
9045: my ($section, $group, @groups);
9046: my ($courselevelm,$courselevel);
9047: if ($symbparm && defined($courseid) &&
9048: $courseid eq $env{'request.course.id'}) {
9049:
9050: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
9051:
9052: # ----------------------------------------------------- Cascading lookup scheme
9053: my $symbp=$symbparm;
9054: my $mapp=&deversion((&decode_symb($symbp))[0]);
9055:
9056: my $symbparm=$symbp.'.'.$spacequalifierrest;
9057: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9058:
9059: if (($env{'user.name'} eq $uname) &&
9060: ($env{'user.domain'} eq $udom)) {
9061: $section=$env{'request.course.sec'};
9062: @groups = split(/:/,$env{'request.course.groups'});
9063: @groups=&sort_course_groups($courseid,@groups);
9064: } else {
9065: if (! defined($usection)) {
9066: $section=&getsection($udom,$uname,$courseid);
9067: } else {
9068: $section = $usection;
9069: }
9070: @groups = &get_users_groups($udom,$uname,$courseid);
9071: }
9072:
9073: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9074: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9075: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9076:
9077: $courselevel=$courseid.'.'.$spacequalifierrest;
9078: my $courselevelr=$courseid.'.'.$symbparm;
9079: $courselevelm=$courseid.'.'.$mapparm;
9080:
9081: # ----------------------------------------------------------- first, check user
9082:
9083: my $userreply=&resdata($uname,$udom,'user',
9084: ([$courselevelr,'resource'],
9085: [$courselevelm,'map' ],
9086: [$courselevel, 'course' ]));
9087: if (defined($userreply)) { return &get_reply($userreply); }
9088:
9089: # ------------------------------------------------ second, check some of course
9090: my $coursereply;
9091: if (@groups > 0) {
9092: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9093: $mapparm,$spacequalifierrest);
9094: if (defined($coursereply)) { return &get_reply($coursereply); }
9095: }
9096:
9097: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9098: $env{'course.'.$courseid.'.domain'},
9099: 'course',
9100: ([$seclevelr, 'resource'],
9101: [$seclevelm, 'map' ],
9102: [$seclevel, 'course' ],
9103: [$courselevelr,'resource']));
9104: if (defined($coursereply)) { return &get_reply($coursereply); }
9105:
9106: # ------------------------------------------------------ third, check map parms
9107: my %parmhash=();
9108: my $thisparm='';
9109: if (tie(%parmhash,'GDBM_File',
9110: $env{'request.course.fn'}.'_parms.db',
9111: &GDBM_READER(),0640)) {
9112: $thisparm=$parmhash{$symbparm};
9113: untie(%parmhash);
9114: }
9115: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
9116: }
9117: # ------------------------------------------ fourth, look in resource metadata
9118:
9119: $spacequalifierrest=~s/\./\_/;
9120: my $filename;
9121: if (!$symbparm) { $symbparm=&symbread(); }
9122: if ($symbparm) {
9123: $filename=(&decode_symb($symbparm))[2];
9124: } else {
9125: $filename=$env{'request.filename'};
9126: }
9127: my $metadata=&metadata($filename,$spacequalifierrest);
9128: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9129: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
9130: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9131:
9132: # ---------------------------------------------- fourth, look in rest of course
9133: if ($symbparm && defined($courseid) &&
9134: $courseid eq $env{'request.course.id'}) {
9135: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9136: $env{'course.'.$courseid.'.domain'},
9137: 'course',
9138: ([$courselevelm,'map' ],
9139: [$courselevel, 'course']));
9140: if (defined($coursereply)) { return &get_reply($coursereply); }
9141: }
9142: # ------------------------------------------------------------------ Cascade up
9143: unless ($space eq '0') {
9144: my @parts=split(/_/,$space);
9145: my $id=pop(@parts);
9146: my $part=join('_',@parts);
9147: if ($part eq '') { $part='0'; }
9148: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
9149: $symbparm,$udom,$uname,$section,1);
9150: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
9151: }
9152: if ($recurse) { return undef; }
9153: my $pack_def=&packages_tab_default($filename,$varname);
9154: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
9155: # ---------------------------------------------------- Any other user namespace
9156: } elsif ($realm eq 'environment') {
9157: # ----------------------------------------------------------------- environment
9158: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9159: return $env{'environment.'.$spacequalifierrest};
9160: } else {
9161: if ($uname eq 'anonymous' && $udom eq '') {
9162: return '';
9163: }
9164: my %returnhash=&userenvironment($udom,$uname,
9165: $spacequalifierrest);
9166: return $returnhash{$spacequalifierrest};
9167: }
9168: } elsif ($realm eq 'system') {
9169: # ----------------------------------------------------------------- system.time
9170: if ($space eq 'time') {
9171: return time;
9172: }
9173: } elsif ($realm eq 'server') {
9174: # ----------------------------------------------------------------- system.time
9175: if ($space eq 'name') {
9176: return $ENV{'SERVER_NAME'};
9177: }
9178: }
9179: return '';
9180: }
9181:
9182: sub get_reply {
9183: my ($reply_value) = @_;
9184: if (ref($reply_value) eq 'ARRAY') {
9185: if (wantarray) {
9186: return @$reply_value;
9187: }
9188: return $reply_value->[0];
9189: } else {
9190: return $reply_value;
9191: }
9192: }
9193:
9194: sub check_group_parms {
9195: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9196: my @groupitems = ();
9197: my $resultitem;
9198: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
9199: foreach my $group (@{$groups}) {
9200: foreach my $level (@levels) {
9201: my $item = $courseid.'.['.$group.'].'.$level->[0];
9202: push(@groupitems,[$item,$level->[1]]);
9203: }
9204: }
9205: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9206: $env{'course.'.$courseid.'.domain'},
9207: 'course',@groupitems);
9208: return $coursereply;
9209: }
9210:
9211: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
9212: my ($courseid,@groups) = @_;
9213: @groups = sort(@groups);
9214: return @groups;
9215: }
9216:
9217: sub packages_tab_default {
9218: my ($uri,$varname)=@_;
9219: my (undef,$part,$name)=split(/\./,$varname);
9220:
9221: my (@extension,@specifics,$do_default);
9222: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
9223: my ($pack_type,$pack_part)=split(/_/,$package,2);
9224: if ($pack_type eq 'default') {
9225: $do_default=1;
9226: } elsif ($pack_type eq 'extension') {
9227: push(@extension,[$package,$pack_type,$pack_part]);
9228: } elsif ($pack_part eq $part || $pack_type eq 'part') {
9229: # only look at packages defaults for packages that this id is
9230: push(@specifics,[$package,$pack_type,$pack_part]);
9231: }
9232: }
9233: # first look for a package that matches the requested part id
9234: foreach my $package (@specifics) {
9235: my (undef,$pack_type,$pack_part)=@{$package};
9236: next if ($pack_part ne $part);
9237: if (defined($packagetab{"$pack_type&$name&default"})) {
9238: return $packagetab{"$pack_type&$name&default"};
9239: }
9240: }
9241: # look for any possible matching non extension_ package
9242: foreach my $package (@specifics) {
9243: my (undef,$pack_type,$pack_part)=@{$package};
9244: if (defined($packagetab{"$pack_type&$name&default"})) {
9245: return $packagetab{"$pack_type&$name&default"};
9246: }
9247: if ($pack_type eq 'part') { $pack_part='0'; }
9248: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9249: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
9250: }
9251: }
9252: # look for any posible extension_ match
9253: foreach my $package (@extension) {
9254: my ($package,$pack_type)=@{$package};
9255: if (defined($packagetab{"$pack_type&$name&default"})) {
9256: return $packagetab{"$pack_type&$name&default"};
9257: }
9258: if (defined($packagetab{$package."&$name&default"})) {
9259: return $packagetab{$package."&$name&default"};
9260: }
9261: }
9262: # look for a global default setting
9263: if ($do_default && defined($packagetab{"default&$name&default"})) {
9264: return $packagetab{"default&$name&default"};
9265: }
9266: return undef;
9267: }
9268:
9269: sub add_prefix_and_part {
9270: my ($prefix,$part)=@_;
9271: my $keyroot;
9272: if (defined($prefix) && $prefix !~ /^__/) {
9273: # prefix that has a part already
9274: $keyroot=$prefix;
9275: } elsif (defined($prefix)) {
9276: # prefix that is missing a part
9277: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9278: } else {
9279: # no prefix at all
9280: if (defined($part)) { $keyroot='_'.$part; }
9281: }
9282: return $keyroot;
9283: }
9284:
9285: # ---------------------------------------------------------------- Get metadata
9286:
9287: my %metaentry;
9288: my %importedpartids;
9289: sub metadata {
9290: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
9291: $uri=&declutter($uri);
9292: # if it is a non metadata possible uri return quickly
9293: if (($uri eq '') ||
9294: (($uri =~ m|^/*adm/|) &&
9295: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
9296: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
9297: return undef;
9298: }
9299: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
9300: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
9301: return undef;
9302: }
9303: my $filename=$uri;
9304: $uri=~s/\.meta$//;
9305: #
9306: # Is the metadata already cached?
9307: # Look at timestamp of caching
9308: # Everything is cached by the main uri, libraries are never directly cached
9309: #
9310: if (!defined($liburi)) {
9311: my ($result,$cached)=&is_cached_new('meta',$uri);
9312: if (defined($cached)) { return $result->{':'.$what}; }
9313: }
9314: {
9315: # Imported parts would go here
9316: my %importedids=();
9317: my @origfileimportpartids=();
9318: my $importedparts=0;
9319: #
9320: # Is this a recursive call for a library?
9321: #
9322: # if (! exists($metacache{$uri})) {
9323: # $metacache{$uri}={};
9324: # }
9325: my $cachetime = 60*60;
9326: if ($liburi) {
9327: $liburi=&declutter($liburi);
9328: $filename=$liburi;
9329: } else {
9330: &devalidate_cache_new('meta',$uri);
9331: undef(%metaentry);
9332: }
9333: my %metathesekeys=();
9334: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9335: my $metastring;
9336: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
9337: my $which = &hreflocation('','/'.($liburi || $uri));
9338: $metastring =
9339: &Apache::lonnet::ssi_body($which,
9340: ('grade_target' => 'meta'));
9341: $cachetime = 1; # only want this cached in the child not long term
9342: } elsif (($uri !~ m -^(editupload)/-) &&
9343: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9344: my $file=&filelocation('',&clutter($filename));
9345: #push(@{$metaentry{$uri.'.file'}},$file);
9346: $metastring=&getfile($file);
9347: }
9348: my $parser=HTML::LCParser->new(\$metastring);
9349: my $token;
9350: undef %metathesekeys;
9351: while ($token=$parser->get_token) {
9352: if ($token->[0] eq 'S') {
9353: if (defined($token->[2]->{'package'})) {
9354: #
9355: # This is a package - get package info
9356: #
9357: my $package=$token->[2]->{'package'};
9358: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9359: if (defined($token->[2]->{'id'})) {
9360: $keyroot.='_'.$token->[2]->{'id'};
9361: }
9362: if ($metaentry{':packages'}) {
9363: $metaentry{':packages'}.=','.$package.$keyroot;
9364: } else {
9365: $metaentry{':packages'}=$package.$keyroot;
9366: }
9367: foreach my $pack_entry (keys(%packagetab)) {
9368: my $part=$keyroot;
9369: $part=~s/^\_//;
9370: if ($pack_entry=~/^\Q$package\E\&/ ||
9371: $pack_entry=~/^\Q$package\E_0\&/) {
9372: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
9373: # ignore package.tab specified default values
9374: # here &package_tab_default() will fetch those
9375: if ($subp eq 'default') { next; }
9376: my $value=$packagetab{$pack_entry};
9377: my $unikey;
9378: if ($pack =~ /_0$/) {
9379: $unikey='parameter_0_'.$name;
9380: $part=0;
9381: } else {
9382: $unikey='parameter'.$keyroot.'_'.$name;
9383: }
9384: if ($subp eq 'display') {
9385: $value.=' [Part: '.$part.']';
9386: }
9387: $metaentry{':'.$unikey.'.part'}=$part;
9388: $metathesekeys{$unikey}=1;
9389: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9390: $metaentry{':'.$unikey.'.'.$subp}=$value;
9391: }
9392: if (defined($metaentry{':'.$unikey.'.default'})) {
9393: $metaentry{':'.$unikey}=
9394: $metaentry{':'.$unikey.'.default'};
9395: }
9396: }
9397: }
9398: } else {
9399: #
9400: # This is not a package - some other kind of start tag
9401: #
9402: my $entry=$token->[1];
9403: my $unikey='';
9404:
9405: if ($entry eq 'import') {
9406: #
9407: # Importing a library here
9408: #
9409: my $location=$parser->get_text('/import');
9410: my $dir=$filename;
9411: $dir=~s|[^/]*$||;
9412: $location=&filelocation($dir,$location);
9413:
9414: my $importmode=$token->[2]->{'importmode'};
9415: if ($importmode eq 'problem') {
9416: # Import as problem/response
9417: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9418: } elsif ($importmode eq 'part') {
9419: # Import as part(s)
9420: $importedparts=1;
9421: # We need to get the original file and the imported file to get the part order correct
9422: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9423: # Load and inspect original file
9424: if ($#origfileimportpartids<0) {
9425: undef(%importedpartids);
9426: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9427: my $origfile=&getfile($origfilelocation);
9428: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9429: }
9430:
9431: # Load and inspect imported file
9432: my $impfile=&getfile($location);
9433: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9434: if ($#impfilepartids>=0) {
9435: # This problem had parts
9436: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
9437: } else {
9438: # Importing by turning a single problem into a problem part
9439: # It gets the import-tags ID as part-ID
9440: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
9441: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
9442: }
9443: } else {
9444: # Normal import
9445: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9446: if (defined($token->[2]->{'id'})) {
9447: $unikey.='_'.$token->[2]->{'id'};
9448: }
9449: }
9450:
9451: if ($depthcount<20) {
9452: my $metadata =
9453: &metadata($uri,'keys', $location,$unikey,
9454: $depthcount+1);
9455: foreach my $meta (split(',',$metadata)) {
9456: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9457: $metathesekeys{$meta}=1;
9458: }
9459:
9460: }
9461: } else {
9462: #
9463: # Not importing, some other kind of non-package, non-library start tag
9464: #
9465: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9466: if (defined($token->[2]->{'id'})) {
9467: $unikey.='_'.$token->[2]->{'id'};
9468: }
9469: if (defined($token->[2]->{'name'})) {
9470: $unikey.='_'.$token->[2]->{'name'};
9471: }
9472: $metathesekeys{$unikey}=1;
9473: foreach my $param (@{$token->[3]}) {
9474: $metaentry{':'.$unikey.'.'.$param} =
9475: $token->[2]->{$param};
9476: }
9477: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
9478: my $default=$metaentry{':'.$unikey.'.default'};
9479: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9480: # only ws inside the tag, and not in default, so use default
9481: # as value
9482: $metaentry{':'.$unikey}=$default;
9483: } elsif ( $internaltext =~ /\S/ ) {
9484: # something interesting inside the tag
9485: $metaentry{':'.$unikey}=$internaltext;
9486: } else {
9487: # no interesting values, don't set a default
9488: }
9489: # end of not-a-package not-a-library import
9490: }
9491: # end of not-a-package start tag
9492: }
9493: # the next is the end of "start tag"
9494: }
9495: }
9496: my ($extension) = ($uri =~ /\.(\w+)$/);
9497: $extension = lc($extension);
9498: if ($extension eq 'htm') { $extension='html'; }
9499:
9500: foreach my $key (keys(%packagetab)) {
9501: #no specific packages #how's our extension
9502: if ($key!~/^extension_\Q$extension\E&/) { next; }
9503: &metadata_create_package_def($uri,$key,'extension_'.$extension,
9504: \%metathesekeys);
9505: }
9506:
9507: if (!exists($metaentry{':packages'})
9508: || $packagetab{"import_defaults&extension_$extension"}) {
9509: foreach my $key (keys(%packagetab)) {
9510: #no specific packages well let's get default then
9511: if ($key!~/^default&/) { next; }
9512: &metadata_create_package_def($uri,$key,'default',
9513: \%metathesekeys);
9514: }
9515: }
9516: # are there custom rights to evaluate
9517: if ($metaentry{':copyright'} eq 'custom') {
9518:
9519: #
9520: # Importing a rights file here
9521: #
9522: unless ($depthcount) {
9523: my $location=$metaentry{':customdistributionfile'};
9524: my $dir=$filename;
9525: $dir=~s|[^/]*$||;
9526: $location=&filelocation($dir,$location);
9527: my $rights_metadata =
9528: &metadata($uri,'keys',$location,'_rights',
9529: $depthcount+1);
9530: foreach my $rights (split(',',$rights_metadata)) {
9531: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9532: $metathesekeys{$rights}=1;
9533: }
9534: }
9535: }
9536: # uniqifiy package listing
9537: my %seen;
9538: my @uniq_packages =
9539: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9540: $metaentry{':packages'} = join(',',@uniq_packages);
9541:
9542: if ($importedparts) {
9543: # We had imported parts and need to rebuild partorder
9544: $metaentry{':partorder'}='';
9545: $metathesekeys{'partorder'}=1;
9546: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9547: if ($origfileimportpartids[$index] eq 'part') {
9548: # original part, part of the problem
9549: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9550: } else {
9551: # we have imported parts at this position
9552: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9553: }
9554: }
9555: $metaentry{':partorder'}=~s/^\,//;
9556: }
9557:
9558: $metaentry{':keys'} = join(',',keys(%metathesekeys));
9559: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9560: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
9561: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
9562: # this is the end of "was not already recently cached
9563: }
9564: return $metaentry{':'.$what};
9565: }
9566:
9567: sub metadata_create_package_def {
9568: my ($uri,$key,$package,$metathesekeys)=@_;
9569: my ($pack,$name,$subp)=split(/\&/,$key);
9570: if ($subp eq 'default') { next; }
9571:
9572: if (defined($metaentry{':packages'})) {
9573: $metaentry{':packages'}.=','.$package;
9574: } else {
9575: $metaentry{':packages'}=$package;
9576: }
9577: my $value=$packagetab{$key};
9578: my $unikey;
9579: $unikey='parameter_0_'.$name;
9580: $metaentry{':'.$unikey.'.part'}=0;
9581: $$metathesekeys{$unikey}=1;
9582: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9583: $metaentry{':'.$unikey.'.'.$subp}=$value;
9584: }
9585: if (defined($metaentry{':'.$unikey.'.default'})) {
9586: $metaentry{':'.$unikey}=
9587: $metaentry{':'.$unikey.'.default'};
9588: }
9589: }
9590:
9591: sub metadata_generate_part0 {
9592: my ($metadata,$metacache,$uri) = @_;
9593: my %allnames;
9594: foreach my $metakey (keys(%$metadata)) {
9595: if ($metakey=~/^parameter\_(.*)/) {
9596: my $part=$$metacache{':'.$metakey.'.part'};
9597: my $name=$$metacache{':'.$metakey.'.name'};
9598: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
9599: $allnames{$name}=$part;
9600: }
9601: }
9602: }
9603: foreach my $name (keys(%allnames)) {
9604: $$metadata{"parameter_0_$name"}=1;
9605: my $key=":parameter_0_$name";
9606: $$metacache{"$key.part"}='0';
9607: $$metacache{"$key.name"}=$name;
9608: $$metacache{"$key.type"}=$$metacache{':parameter_'.
9609: $allnames{$name}.'_'.$name.
9610: '.type'};
9611: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
9612: '.display'};
9613: my $expr='[Part: '.$allnames{$name}.']';
9614: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
9615: $$metacache{"$key.display"}=$olddis;
9616: }
9617: }
9618:
9619: # ------------------------------------------------------ Devalidate title cache
9620:
9621: sub devalidate_title_cache {
9622: my ($url)=@_;
9623: if (!$env{'request.course.id'}) { return; }
9624: my $symb=&symbread($url);
9625: if (!$symb) { return; }
9626: my $key=$env{'request.course.id'}."\0".$symb;
9627: &devalidate_cache_new('title',$key);
9628: }
9629:
9630: # ------------------------------------------------- Get the title of a course
9631:
9632: sub current_course_title {
9633: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9634: }
9635: # ------------------------------------------------- Get the title of a resource
9636:
9637: sub gettitle {
9638: my $urlsymb=shift;
9639: my $symb=&symbread($urlsymb);
9640: if ($symb) {
9641: my $key=$env{'request.course.id'}."\0".$symb;
9642: my ($result,$cached)=&is_cached_new('title',$key);
9643: if (defined($cached)) {
9644: return $result;
9645: }
9646: my ($map,$resid,$url)=&decode_symb($symb);
9647: my $title='';
9648: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9649: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9650: } else {
9651: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9652: &GDBM_READER(),0640)) {
9653: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9654: $title=$bighash{'title_'.$mapid.'.'.$resid};
9655: untie(%bighash);
9656: }
9657: }
9658: $title=~s/\&colon\;/\:/gs;
9659: if ($title) {
9660: # Remember both $symb and $title for dynamic metadata
9661: $accesshash{$symb.'___crstitle'}=$title;
9662: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
9663: # Cache this title and then return it
9664: return &do_cache_new('title',$key,$title,600);
9665: }
9666: $urlsymb=$url;
9667: }
9668: my $title=&metadata($urlsymb,'title');
9669: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9670: return $title;
9671: }
9672:
9673: sub get_slot {
9674: my ($which,$cnum,$cdom)=@_;
9675: if (!$cnum || !$cdom) {
9676: (undef,my $courseid)=&whichuser();
9677: $cdom=$env{'course.'.$courseid.'.domain'};
9678: $cnum=$env{'course.'.$courseid.'.num'};
9679: }
9680: my $key=join("\0",'slots',$cdom,$cnum,$which);
9681: my %slotinfo;
9682: if (exists($remembered{$key})) {
9683: $slotinfo{$which} = $remembered{$key};
9684: } else {
9685: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9686: &Apache::lonhomework::showhash(%slotinfo);
9687: my ($tmp)=keys(%slotinfo);
9688: if ($tmp=~/^error:/) { return (); }
9689: $remembered{$key} = $slotinfo{$which};
9690: }
9691: if (ref($slotinfo{$which}) eq 'HASH') {
9692: return %{$slotinfo{$which}};
9693: }
9694: return $slotinfo{$which};
9695: }
9696:
9697: sub get_reservable_slots {
9698: my ($cnum,$cdom,$uname,$udom) = @_;
9699: my $now = time;
9700: my $reservable_info;
9701: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9702: if (exists($remembered{$key})) {
9703: $reservable_info = $remembered{$key};
9704: } else {
9705: my %resv;
9706: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9707: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9708: $reservable_info = \%resv;
9709: $remembered{$key} = $reservable_info;
9710: }
9711: return $reservable_info;
9712: }
9713:
9714: sub get_course_slots {
9715: my ($cnum,$cdom) = @_;
9716: my $hashid=$cnum.':'.$cdom;
9717: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9718: if (defined($cached)) {
9719: if (ref($result) eq 'HASH') {
9720: return %{$result};
9721: }
9722: } else {
9723: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9724: my ($tmp) = keys(%slots);
9725: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9726: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9727: return %slots;
9728: }
9729: }
9730: return;
9731: }
9732:
9733: sub devalidate_slots_cache {
9734: my ($cnum,$cdom)=@_;
9735: my $hashid=$cnum.':'.$cdom;
9736: &devalidate_cache_new('allslots',$hashid);
9737: }
9738:
9739: # ------------------------------------------------- Update symbolic store links
9740:
9741: sub symblist {
9742: my ($mapname,%newhash)=@_;
9743: $mapname=&deversion(&declutter($mapname));
9744: my %hash;
9745: if (($env{'request.course.fn'}) && (%newhash)) {
9746: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9747: &GDBM_WRCREAT(),0640)) {
9748: foreach my $url (keys(%newhash)) {
9749: next if ($url eq 'last_known'
9750: && $env{'form.no_update_last_known'});
9751: $hash{declutter($url)}=&encode_symb($mapname,
9752: $newhash{$url}->[1],
9753: $newhash{$url}->[0]);
9754: }
9755: if (untie(%hash)) {
9756: return 'ok';
9757: }
9758: }
9759: }
9760: return 'error';
9761: }
9762:
9763: # --------------------------------------------------------------- Verify a symb
9764:
9765: sub symbverify {
9766: my ($symb,$thisurl)=@_;
9767: my $thisfn=$thisurl;
9768: $thisfn=&declutter($thisfn);
9769: # direct jump to resource in page or to a sequence - will construct own symbs
9770: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9771: # check URL part
9772: my ($map,$resid,$url)=&decode_symb($symb);
9773:
9774: unless ($url eq $thisfn) { return 0; }
9775:
9776: $symb=&symbclean($symb);
9777: $thisurl=&deversion($thisurl);
9778: $thisfn=&deversion($thisfn);
9779:
9780: my %bighash;
9781: my $okay=0;
9782:
9783: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9784: &GDBM_READER(),0640)) {
9785: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9786: $thisurl =~ s/\?.+$//;
9787: }
9788: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9789: unless ($ids) {
9790: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9791: $ids=$bighash{$idkey};
9792: }
9793: if ($ids) {
9794: # ------------------------------------------------------------------- Has ID(s)
9795: foreach my $id (split(/\,/,$ids)) {
9796: my ($mapid,$resid)=split(/\./,$id);
9797: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9798: $symb =~ s/\?.+$//;
9799: }
9800: if (
9801: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9802: eq $symb) {
9803: if (($env{'request.role.adv'}) ||
9804: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9805: ($thisurl eq '/adm/navmaps')) {
9806: $okay=1;
9807: }
9808: }
9809: }
9810: }
9811: untie(%bighash);
9812: }
9813: return $okay;
9814: }
9815:
9816: # --------------------------------------------------------------- Clean-up symb
9817:
9818: sub symbclean {
9819: my $symb=shift;
9820: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9821: # remove version from map
9822: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9823:
9824: # remove version from URL
9825: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9826:
9827: # remove wrapper
9828:
9829: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9830: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9831: return $symb;
9832: }
9833:
9834: # ---------------------------------------------- Split symb to find map and url
9835:
9836: sub encode_symb {
9837: my ($map,$resid,$url)=@_;
9838: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9839: }
9840:
9841: sub decode_symb {
9842: my $symb=shift;
9843: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9844: my ($map,$resid,$url)=split(/___/,$symb);
9845: return (&fixversion($map),$resid,&fixversion($url));
9846: }
9847:
9848: sub fixversion {
9849: my $fn=shift;
9850: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9851: my %bighash;
9852: my $uri=&clutter($fn);
9853: my $key=$env{'request.course.id'}.'_'.$uri;
9854: # is this cached?
9855: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9856: if (defined($cached)) { return $result; }
9857: # unfortunately not cached, or expired
9858: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9859: &GDBM_READER(),0640)) {
9860: if ($bighash{'version_'.$uri}) {
9861: my $version=$bighash{'version_'.$uri};
9862: unless (($version eq 'mostrecent') ||
9863: ($version==&getversion($uri))) {
9864: $uri=~s/\.(\w+)$/\.$version\.$1/;
9865: }
9866: }
9867: untie %bighash;
9868: }
9869: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9870: }
9871:
9872: sub deversion {
9873: my $url=shift;
9874: $url=~s/\.\d+\.(\w+)$/\.$1/;
9875: return $url;
9876: }
9877:
9878: # ------------------------------------------------------ Return symb list entry
9879:
9880: sub symbread {
9881: my ($thisfn,$donotrecurse)=@_;
9882: my $cache_str='request.symbread.cached.'.$thisfn;
9883: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9884: # no filename provided? try from environment
9885: unless ($thisfn) {
9886: if ($env{'request.symb'}) {
9887: return $env{$cache_str}=&symbclean($env{'request.symb'});
9888: }
9889: $thisfn=$env{'request.filename'};
9890: }
9891: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9892: # is that filename actually a symb? Verify, clean, and return
9893: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9894: if (&symbverify($thisfn,$1)) {
9895: return $env{$cache_str}=&symbclean($thisfn);
9896: }
9897: }
9898: $thisfn=declutter($thisfn);
9899: my %hash;
9900: my %bighash;
9901: my $syval='';
9902: if (($env{'request.course.fn'}) && ($thisfn)) {
9903: my $targetfn = $thisfn;
9904: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9905: $targetfn = 'adm/wrapper/'.$thisfn;
9906: }
9907: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9908: $targetfn=$1;
9909: }
9910: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9911: &GDBM_READER(),0640)) {
9912: $syval=$hash{$targetfn};
9913: untie(%hash);
9914: }
9915: # ---------------------------------------------------------- There was an entry
9916: if ($syval) {
9917: #unless ($syval=~/\_\d+$/) {
9918: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9919: #&appenv({'request.ambiguous' => $thisfn});
9920: #return $env{$cache_str}='';
9921: #}
9922: #$syval.=$1;
9923: #}
9924: } else {
9925: # ------------------------------------------------------- Was not in symb table
9926: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9927: &GDBM_READER(),0640)) {
9928: # ---------------------------------------------- Get ID(s) for current resource
9929: my $ids=$bighash{'ids_'.&clutter($thisfn)};
9930: unless ($ids) {
9931: $ids=$bighash{'ids_/'.$thisfn};
9932: }
9933: unless ($ids) {
9934: # alias?
9935: $ids=$bighash{'mapalias_'.$thisfn};
9936: }
9937: if ($ids) {
9938: # ------------------------------------------------------------------- Has ID(s)
9939: my @possibilities=split(/\,/,$ids);
9940: if ($#possibilities==0) {
9941: # ----------------------------------------------- There is only one possibility
9942: my ($mapid,$resid)=split(/\./,$ids);
9943: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9944: $resid,$thisfn);
9945: } elsif (!$donotrecurse) {
9946: # ------------------------------------------ There is more than one possibility
9947: my $realpossible=0;
9948: foreach my $id (@possibilities) {
9949: my $file=$bighash{'src_'.$id};
9950: if (&allowed('bre',$file)) {
9951: my ($mapid,$resid)=split(/\./,$id);
9952: if ($bighash{'map_type_'.$mapid} ne 'page') {
9953: $realpossible++;
9954: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9955: $resid,$thisfn);
9956: }
9957: }
9958: }
9959: if ($realpossible!=1) { $syval=''; }
9960: } else {
9961: $syval='';
9962: }
9963: }
9964: untie(%bighash)
9965: }
9966: }
9967: if ($syval) {
9968: return $env{$cache_str}=$syval;
9969: }
9970: }
9971: &appenv({'request.ambiguous' => $thisfn});
9972: return $env{$cache_str}='';
9973: }
9974:
9975: # ---------------------------------------------------------- Return random seed
9976:
9977: sub numval {
9978: my $txt=shift;
9979: $txt=~tr/A-J/0-9/;
9980: $txt=~tr/a-j/0-9/;
9981: $txt=~tr/K-T/0-9/;
9982: $txt=~tr/k-t/0-9/;
9983: $txt=~tr/U-Z/0-5/;
9984: $txt=~tr/u-z/0-5/;
9985: $txt=~s/\D//g;
9986: if ($_64bit) { if ($txt > 2**32) { return -1; } }
9987: return int($txt);
9988: }
9989:
9990: sub numval2 {
9991: my $txt=shift;
9992: $txt=~tr/A-J/0-9/;
9993: $txt=~tr/a-j/0-9/;
9994: $txt=~tr/K-T/0-9/;
9995: $txt=~tr/k-t/0-9/;
9996: $txt=~tr/U-Z/0-5/;
9997: $txt=~tr/u-z/0-5/;
9998: $txt=~s/\D//g;
9999: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10000: my $total;
10001: foreach my $val (@txts) { $total+=$val; }
10002: if ($_64bit) { if ($total > 2**32) { return -1; } }
10003: return int($total);
10004: }
10005:
10006: sub numval3 {
10007: use integer;
10008: my $txt=shift;
10009: $txt=~tr/A-J/0-9/;
10010: $txt=~tr/a-j/0-9/;
10011: $txt=~tr/K-T/0-9/;
10012: $txt=~tr/k-t/0-9/;
10013: $txt=~tr/U-Z/0-5/;
10014: $txt=~tr/u-z/0-5/;
10015: $txt=~s/\D//g;
10016: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10017: my $total;
10018: foreach my $val (@txts) { $total+=$val; }
10019: if ($_64bit) { $total=(($total<<32)>>32); }
10020: return $total;
10021: }
10022:
10023: sub digest {
10024: my ($data)=@_;
10025: my $digest=&Digest::MD5::md5($data);
10026: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10027: my ($e,$f);
10028: {
10029: use integer;
10030: $e=($a+$b);
10031: $f=($c+$d);
10032: if ($_64bit) {
10033: $e=(($e<<32)>>32);
10034: $f=(($f<<32)>>32);
10035: }
10036: }
10037: if (wantarray) {
10038: return ($e,$f);
10039: } else {
10040: my $g;
10041: {
10042: use integer;
10043: $g=($e+$f);
10044: if ($_64bit) {
10045: $g=(($g<<32)>>32);
10046: }
10047: }
10048: return $g;
10049: }
10050: }
10051:
10052: sub latest_rnd_algorithm_id {
10053: return '64bit5';
10054: }
10055:
10056: sub get_rand_alg {
10057: my ($courseid)=@_;
10058: if (!$courseid) { $courseid=(&whichuser())[1]; }
10059: if ($courseid) {
10060: return $env{"course.$courseid.rndseed"};
10061: }
10062: return &latest_rnd_algorithm_id();
10063: }
10064:
10065: sub validCODE {
10066: my ($CODE)=@_;
10067: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10068: return 0;
10069: }
10070:
10071: sub getCODE {
10072: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10073: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10074: defined($Apache::lonhomework::parsing_a_task) ) &&
10075: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10076: return $Apache::lonhomework::history{'resource.CODE'};
10077: }
10078: return undef;
10079: }
10080: #
10081: # Determines the random seed for a specific context:
10082: #
10083: # parameters:
10084: # symb - in course context the symb for the seed.
10085: # course_id - The course id of the form domain_coursenum.
10086: # domain - Domain for the user.
10087: # course - Course for the user.
10088: # cenv - environment of the course.
10089: #
10090: # NOTE:
10091: # All parameters are picked out of the environment if missing
10092: # or not defined.
10093: # If a symb cannot be determined the current time is used instead.
10094: #
10095: # For a given well defined symb, courside, domain, username,
10096: # and course environment, the seed is reproducible.
10097: #
10098: sub rndseed {
10099: my ($symb,$courseid,$domain,$username, $cenv)=@_;
10100: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10101: if (!defined($symb)) {
10102: unless ($symb=$wsymb) { return time; }
10103: }
10104: if (!defined $courseid) {
10105: $courseid=$wcourseid;
10106: }
10107: if (!defined $domain) { $domain=$wdomain; }
10108: if (!defined $username) { $username=$wusername }
10109:
10110: my $which;
10111: if (defined($cenv->{'rndseed'})) {
10112: $which = $cenv->{'rndseed'};
10113: } else {
10114: $which =&get_rand_alg($courseid);
10115: }
10116: if (defined(&getCODE())) {
10117:
10118: if ($which eq '64bit5') {
10119: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10120: } elsif ($which eq '64bit4') {
10121: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10122: } else {
10123: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10124: }
10125: } elsif ($which eq '64bit5') {
10126: return &rndseed_64bit5($symb,$courseid,$domain,$username);
10127: } elsif ($which eq '64bit4') {
10128: return &rndseed_64bit4($symb,$courseid,$domain,$username);
10129: } elsif ($which eq '64bit3') {
10130: return &rndseed_64bit3($symb,$courseid,$domain,$username);
10131: } elsif ($which eq '64bit2') {
10132: return &rndseed_64bit2($symb,$courseid,$domain,$username);
10133: } elsif ($which eq '64bit') {
10134: return &rndseed_64bit($symb,$courseid,$domain,$username);
10135: }
10136: return &rndseed_32bit($symb,$courseid,$domain,$username);
10137: }
10138:
10139: sub rndseed_32bit {
10140: my ($symb,$courseid,$domain,$username)=@_;
10141: {
10142: use integer;
10143: my $symbchck=unpack("%32C*",$symb) << 27;
10144: my $symbseed=numval($symb) << 22;
10145: my $namechck=unpack("%32C*",$username) << 17;
10146: my $nameseed=numval($username) << 12;
10147: my $domainseed=unpack("%32C*",$domain) << 7;
10148: my $courseseed=unpack("%32C*",$courseid);
10149: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10150: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10151: #&logthis("rndseed :$num:$symb");
10152: if ($_64bit) { $num=(($num<<32)>>32); }
10153: return $num;
10154: }
10155: }
10156:
10157: sub rndseed_64bit {
10158: my ($symb,$courseid,$domain,$username)=@_;
10159: {
10160: use integer;
10161: my $symbchck=unpack("%32S*",$symb) << 21;
10162: my $symbseed=numval($symb) << 10;
10163: my $namechck=unpack("%32S*",$username);
10164:
10165: my $nameseed=numval($username) << 21;
10166: my $domainseed=unpack("%32S*",$domain) << 10;
10167: my $courseseed=unpack("%32S*",$courseid);
10168:
10169: my $num1=$symbchck+$symbseed+$namechck;
10170: my $num2=$nameseed+$domainseed+$courseseed;
10171: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10172: #&logthis("rndseed :$num:$symb");
10173: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10174: return "$num1,$num2";
10175: }
10176: }
10177:
10178: sub rndseed_64bit2 {
10179: my ($symb,$courseid,$domain,$username)=@_;
10180: {
10181: use integer;
10182: # strings need to be an even # of cahracters long, it it is odd the
10183: # last characters gets thrown away
10184: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10185: my $symbseed=numval($symb) << 10;
10186: my $namechck=unpack("%32S*",$username.' ');
10187:
10188: my $nameseed=numval($username) << 21;
10189: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10190: my $courseseed=unpack("%32S*",$courseid.' ');
10191:
10192: my $num1=$symbchck+$symbseed+$namechck;
10193: my $num2=$nameseed+$domainseed+$courseseed;
10194: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10195: #&logthis("rndseed :$num:$symb");
10196: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10197: return "$num1,$num2";
10198: }
10199: }
10200:
10201: sub rndseed_64bit3 {
10202: my ($symb,$courseid,$domain,$username)=@_;
10203: {
10204: use integer;
10205: # strings need to be an even # of cahracters long, it it is odd the
10206: # last characters gets thrown away
10207: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10208: my $symbseed=numval2($symb) << 10;
10209: my $namechck=unpack("%32S*",$username.' ');
10210:
10211: my $nameseed=numval2($username) << 21;
10212: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10213: my $courseseed=unpack("%32S*",$courseid.' ');
10214:
10215: my $num1=$symbchck+$symbseed+$namechck;
10216: my $num2=$nameseed+$domainseed+$courseseed;
10217: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10218: #&logthis("rndseed :$num1:$num2:$_64bit");
10219: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10220:
10221: return "$num1:$num2";
10222: }
10223: }
10224:
10225: sub rndseed_64bit4 {
10226: my ($symb,$courseid,$domain,$username)=@_;
10227: {
10228: use integer;
10229: # strings need to be an even # of cahracters long, it it is odd the
10230: # last characters gets thrown away
10231: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10232: my $symbseed=numval3($symb) << 10;
10233: my $namechck=unpack("%32S*",$username.' ');
10234:
10235: my $nameseed=numval3($username) << 21;
10236: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10237: my $courseseed=unpack("%32S*",$courseid.' ');
10238:
10239: my $num1=$symbchck+$symbseed+$namechck;
10240: my $num2=$nameseed+$domainseed+$courseseed;
10241: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10242: #&logthis("rndseed :$num1:$num2:$_64bit");
10243: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10244:
10245: return "$num1:$num2";
10246: }
10247: }
10248:
10249: sub rndseed_64bit5 {
10250: my ($symb,$courseid,$domain,$username)=@_;
10251: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10252: return "$num1:$num2";
10253: }
10254:
10255: sub rndseed_CODE_64bit {
10256: my ($symb,$courseid,$domain,$username)=@_;
10257: {
10258: use integer;
10259: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10260: my $symbseed=numval2($symb);
10261: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10262: my $CODEseed=numval(&getCODE());
10263: my $courseseed=unpack("%32S*",$courseid.' ');
10264: my $num1=$symbseed+$CODEchck;
10265: my $num2=$CODEseed+$courseseed+$symbchck;
10266: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10267: #&logthis("rndseed :$num1:$num2:$symb");
10268: if ($_64bit) { $num1=(($num1<<32)>>32); }
10269: if ($_64bit) { $num2=(($num2<<32)>>32); }
10270: return "$num1:$num2";
10271: }
10272: }
10273:
10274: sub rndseed_CODE_64bit4 {
10275: my ($symb,$courseid,$domain,$username)=@_;
10276: {
10277: use integer;
10278: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10279: my $symbseed=numval3($symb);
10280: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10281: my $CODEseed=numval3(&getCODE());
10282: my $courseseed=unpack("%32S*",$courseid.' ');
10283: my $num1=$symbseed+$CODEchck;
10284: my $num2=$CODEseed+$courseseed+$symbchck;
10285: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10286: #&logthis("rndseed :$num1:$num2:$symb");
10287: if ($_64bit) { $num1=(($num1<<32)>>32); }
10288: if ($_64bit) { $num2=(($num2<<32)>>32); }
10289: return "$num1:$num2";
10290: }
10291: }
10292:
10293: sub rndseed_CODE_64bit5 {
10294: my ($symb,$courseid,$domain,$username)=@_;
10295: my $code = &getCODE();
10296: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10297: return "$num1:$num2";
10298: }
10299:
10300: sub setup_random_from_rndseed {
10301: my ($rndseed)=@_;
10302: if ($rndseed =~/([,:])/) {
10303: my ($num1,$num2)=split(/[,:]/,$rndseed);
10304: &Math::Random::random_set_seed(abs($num1),abs($num2));
10305: } else {
10306: &Math::Random::random_set_seed_from_phrase($rndseed);
10307: }
10308: }
10309:
10310: sub latest_receipt_algorithm_id {
10311: return 'receipt3';
10312: }
10313:
10314: sub recunique {
10315: my $fucourseid=shift;
10316: my $unique;
10317: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10318: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10319: $unique=$env{"course.$fucourseid.internal.encseed"};
10320: } else {
10321: $unique=$perlvar{'lonReceipt'};
10322: }
10323: return unpack("%32C*",$unique);
10324: }
10325:
10326: sub recprefix {
10327: my $fucourseid=shift;
10328: my $prefix;
10329: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10330: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10331: $prefix=$env{"course.$fucourseid.internal.encpref"};
10332: } else {
10333: $prefix=$perlvar{'lonHostID'};
10334: }
10335: return unpack("%32C*",$prefix);
10336: }
10337:
10338: sub ireceipt {
10339: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10340:
10341: my $return =&recprefix($fucourseid).'-';
10342:
10343: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10344: $env{'request.state'} eq 'construct') {
10345: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10346: return $return;
10347: }
10348:
10349: my $cuname=unpack("%32C*",$funame);
10350: my $cudom=unpack("%32C*",$fudom);
10351: my $cucourseid=unpack("%32C*",$fucourseid);
10352: my $cusymb=unpack("%32C*",$fusymb);
10353: my $cunique=&recunique($fucourseid);
10354: my $cpart=unpack("%32S*",$part);
10355: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10356:
10357: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
10358:
10359: $return.= ($cunique%$cuname+
10360: $cunique%$cudom+
10361: $cusymb%$cuname+
10362: $cusymb%$cudom+
10363: $cucourseid%$cuname+
10364: $cucourseid%$cudom+
10365: $cpart%$cuname+
10366: $cpart%$cudom);
10367: } else {
10368: $return.= ($cunique%$cuname+
10369: $cunique%$cudom+
10370: $cusymb%$cuname+
10371: $cusymb%$cudom+
10372: $cucourseid%$cuname+
10373: $cucourseid%$cudom);
10374: }
10375: return $return;
10376: }
10377:
10378: sub receipt {
10379: my ($part)=@_;
10380: my ($symb,$courseid,$domain,$name) = &whichuser();
10381: return &ireceipt($name,$domain,$courseid,$symb,$part);
10382: }
10383:
10384: sub whichuser {
10385: my ($passedsymb)=@_;
10386: my ($symb,$courseid,$domain,$name,$publicuser);
10387: if (defined($env{'form.grade_symb'})) {
10388: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10389: my $allowed=&allowed('vgr',$tmp_courseid);
10390: if (!$allowed &&
10391: exists($env{'request.course.sec'}) &&
10392: $env{'request.course.sec'} !~ /^\s*$/) {
10393: $allowed=&allowed('vgr',$tmp_courseid.
10394: '/'.$env{'request.course.sec'});
10395: }
10396: if ($allowed) {
10397: ($symb)=&get_env_multiple('form.grade_symb');
10398: $courseid=$tmp_courseid;
10399: ($domain)=&get_env_multiple('form.grade_domain');
10400: ($name)=&get_env_multiple('form.grade_username');
10401: return ($symb,$courseid,$domain,$name,$publicuser);
10402: }
10403: }
10404: if (!$passedsymb) {
10405: $symb=&symbread();
10406: } else {
10407: $symb=$passedsymb;
10408: }
10409: $courseid=$env{'request.course.id'};
10410: $domain=$env{'user.domain'};
10411: $name=$env{'user.name'};
10412: if ($name eq 'public' && $domain eq 'public') {
10413: if (!defined($env{'form.username'})) {
10414: $env{'form.username'}.=time.rand(10000000);
10415: }
10416: $name.=$env{'form.username'};
10417: }
10418: return ($symb,$courseid,$domain,$name,$publicuser);
10419:
10420: }
10421:
10422: # ------------------------------------------------------------ Serves up a file
10423: # returns either the contents of the file or
10424: # -1 if the file doesn't exist
10425: #
10426: # if the target is a file that was uploaded via DOCS,
10427: # a check will be made to see if a current copy exists on the local server,
10428: # if it does this will be served, otherwise a copy will be retrieved from
10429: # the home server for the course and stored in /home/httpd/html/userfiles on
10430: # the local server.
10431:
10432: sub getfile {
10433: my ($file) = @_;
10434: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10435: &repcopy($file);
10436: return &readfile($file);
10437: }
10438:
10439: sub repcopy_userfile {
10440: my ($file)=@_;
10441: my $londocroot = $perlvar{'lonDocRoot'};
10442: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10443: if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10444: my ($cdom,$cnum,$filename) =
10445: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10446: my $uri="/uploaded/$cdom/$cnum/$filename";
10447: if (-e "$file") {
10448: # we already have a local copy, check it out
10449: my @fileinfo = stat($file);
10450: my $rtncode;
10451: my $info;
10452: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10453: if ($lwpresp ne 'ok') {
10454: # there is no such file anymore, even though we had a local copy
10455: if ($rtncode eq '404') {
10456: unlink($file);
10457: }
10458: return -1;
10459: }
10460: if ($info < $fileinfo[9]) {
10461: # nice, the file we have is up-to-date, just say okay
10462: return 'ok';
10463: } else {
10464: # the file is outdated, get rid of it
10465: unlink($file);
10466: }
10467: }
10468: # one way or the other, at this point, we don't have the file
10469: # construct the correct path for the file
10470: my @parts = ($cdom,$cnum);
10471: if ($filename =~ m|^(.+)/[^/]+$|) {
10472: push @parts, split(/\//,$1);
10473: }
10474: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10475: foreach my $part (@parts) {
10476: $path .= '/'.$part;
10477: if (!-e $path) {
10478: mkdir($path,0770);
10479: }
10480: }
10481: # now the path exists for sure
10482: # get a user agent
10483: my $ua=new LWP::UserAgent;
10484: my $transferfile=$file.'.in.transfer';
10485: # FIXME: this should flock
10486: if (-e $transferfile) { return 'ok'; }
10487: my $request;
10488: $uri=~s/^\///;
10489: my $homeserver = &homeserver($cnum,$cdom);
10490: my $protocol = $protocol{$homeserver};
10491: $protocol = 'http' if ($protocol ne 'https');
10492: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10493: my $response=$ua->request($request,$transferfile);
10494: # did it work?
10495: if ($response->is_error()) {
10496: unlink($transferfile);
10497: &logthis("Userfile repcopy failed for $uri");
10498: return -1;
10499: }
10500: # worked, rename the transfer file
10501: rename($transferfile,$file);
10502: return 'ok';
10503: }
10504:
10505: sub tokenwrapper {
10506: my $uri=shift;
10507: $uri=~s|^https?\://([^/]+)||;
10508: $uri=~s|^/||;
10509: $env{'user.environment'}=~/\/([^\/]+)\.id/;
10510: my $token=$1;
10511: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10512: if ($udom && $uname && $file) {
10513: $file=~s|(\?\.*)*$||;
10514: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10515: my $homeserver = &homeserver($uname,$udom);
10516: my $protocol = $protocol{$homeserver};
10517: $protocol = 'http' if ($protocol ne 'https');
10518: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10519: (($uri=~/\?/)?'&':'?').'token='.$token.
10520: '&tokenissued='.$perlvar{'lonHostID'};
10521: } else {
10522: return '/adm/notfound.html';
10523: }
10524: }
10525:
10526: # call with reqtype HEAD: get last modification time
10527: # call with reqtype GET: get the file contents
10528: # Do not call this with reqtype GET for large files! It loads everything into memory
10529: #
10530: sub getuploaded {
10531: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10532: $uri=~s/^\///;
10533: my $homeserver = &homeserver($cnum,$cdom);
10534: my $protocol = $protocol{$homeserver};
10535: $protocol = 'http' if ($protocol ne 'https');
10536: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10537: my $ua=new LWP::UserAgent;
10538: my $request=new HTTP::Request($reqtype,$uri);
10539: my $response=$ua->request($request);
10540: $$rtncode = $response->code;
10541: if (! $response->is_success()) {
10542: return 'failed';
10543: }
10544: if ($reqtype eq 'HEAD') {
10545: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10546: } elsif ($reqtype eq 'GET') {
10547: $$info = $response->content;
10548: }
10549: return 'ok';
10550: }
10551:
10552: sub readfile {
10553: my $file = shift;
10554: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10555: my $fh;
10556: open($fh,"<$file");
10557: my $a='';
10558: while (my $line = <$fh>) { $a .= $line; }
10559: return $a;
10560: }
10561:
10562: sub filelocation {
10563: my ($dir,$file) = @_;
10564: my $location;
10565: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10566:
10567: if ($file =~ m-^/adm/-) {
10568: $file=~s-^/adm/wrapper/-/-;
10569: $file=~s-^/adm/coursedocs/showdoc/-/-;
10570: }
10571:
10572: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10573: $location = $file;
10574: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10575: my ($udom,$uname,$filename)=
10576: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10577: my $home=&homeserver($uname,$udom);
10578: my $is_me=0;
10579: my @ids=¤t_machine_ids();
10580: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10581: if ($is_me) {
10582: $location=propath($udom,$uname).'/userfiles/'.$filename;
10583: } else {
10584: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10585: $udom.'/'.$uname.'/'.$filename;
10586: }
10587: } elsif ($file =~ m-^/adm/-) {
10588: $location = $perlvar{'lonDocRoot'}.'/'.$file;
10589: } else {
10590: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10591: $file=~s:^/(res|priv)/:/:;
10592: my $space=$1;
10593: if ( !( $file =~ m:^/:) ) {
10594: $location = $dir. '/'.$file;
10595: } else {
10596: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10597: }
10598: }
10599: $location=~s://+:/:g; # remove duplicate /
10600: while ($location=~m{/\.\./}) {
10601: if ($location =~ m{/[^/]+/\.\./}) {
10602: $location=~ s{/[^/]+/\.\./}{/}g;
10603: } else {
10604: $location=~ s{/\.\./}{/}g;
10605: }
10606: } #remove dir/..
10607: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10608: return $location;
10609: }
10610:
10611: sub hreflocation {
10612: my ($dir,$file)=@_;
10613: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10614: $file=filelocation($dir,$file);
10615: } elsif ($file=~m-^/adm/-) {
10616: $file=~s-^/adm/wrapper/-/-;
10617: $file=~s-^/adm/coursedocs/showdoc/-/-;
10618: }
10619: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10620: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10621: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10622: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10623: {/uploaded/$1/$2/}x;
10624: }
10625: if ($file=~ m{^/userfiles/}) {
10626: $file =~ s{^/userfiles/}{/uploaded/};
10627: }
10628: return $file;
10629: }
10630:
10631:
10632:
10633:
10634:
10635: sub current_machine_domains {
10636: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10637: }
10638:
10639: sub machine_domains {
10640: my ($hostname) = @_;
10641: my @domains;
10642: my %hostname = &all_hostnames();
10643: while( my($id, $name) = each(%hostname)) {
10644: # &logthis("-$id-$name-$hostname-");
10645: if ($hostname eq $name) {
10646: push(@domains,&host_domain($id));
10647: }
10648: }
10649: return @domains;
10650: }
10651:
10652: sub current_machine_ids {
10653: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10654: }
10655:
10656: sub machine_ids {
10657: my ($hostname) = @_;
10658: $hostname ||= &hostname($perlvar{'lonHostID'});
10659: my @ids;
10660: my %name_to_host = &all_names();
10661: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10662: return @{ $name_to_host{$hostname} };
10663: }
10664: return;
10665: }
10666:
10667: sub additional_machine_domains {
10668: my @domains;
10669: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10670: while( my $line = <$fh>) {
10671: $line =~ s/\s//g;
10672: push(@domains,$line);
10673: }
10674: return @domains;
10675: }
10676:
10677: sub default_login_domain {
10678: my $domain = $perlvar{'lonDefDomain'};
10679: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10680: foreach my $posdom (¤t_machine_domains(),
10681: &additional_machine_domains()) {
10682: if (lc($posdom) eq lc($testdomain)) {
10683: $domain=$posdom;
10684: last;
10685: }
10686: }
10687: return $domain;
10688: }
10689:
10690: # ------------------------------------------------------------- Declutters URLs
10691:
10692: sub declutter {
10693: my $thisfn=shift;
10694: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10695: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10696: $thisfn=~s/^\///;
10697: $thisfn=~s|^adm/wrapper/||;
10698: $thisfn=~s|^adm/coursedocs/showdoc/||;
10699: $thisfn=~s/^res\///;
10700: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10701: $thisfn=~s/\?.+$//;
10702: }
10703: return $thisfn;
10704: }
10705:
10706: # ------------------------------------------------------------- Clutter up URLs
10707:
10708: sub clutter {
10709: my $thisfn='/'.&declutter(shift);
10710: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10711: || $thisfn =~ m{^/adm/(includes|pages)} ) {
10712: $thisfn='/res'.$thisfn;
10713: }
10714: if ($thisfn !~m|^/adm|) {
10715: if ($thisfn =~ m|^/ext/|) {
10716: $thisfn='/adm/wrapper'.$thisfn;
10717: } else {
10718: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10719: my $embstyle=&Apache::loncommon::fileembstyle($ext);
10720: if ($embstyle eq 'ssi'
10721: || ($embstyle eq 'hdn')
10722: || ($embstyle eq 'rat')
10723: || ($embstyle eq 'prv')
10724: || ($embstyle eq 'ign')) {
10725: #do nothing with these
10726: } elsif (($embstyle eq 'img')
10727: || ($embstyle eq 'emb')
10728: || ($embstyle eq 'wrp')) {
10729: $thisfn='/adm/wrapper'.$thisfn;
10730: } elsif ($embstyle eq 'unk'
10731: && $thisfn!~/\.(sequence|page)$/) {
10732: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
10733: } else {
10734: # &logthis("Got a blank emb style");
10735: }
10736: }
10737: }
10738: return $thisfn;
10739: }
10740:
10741: sub clutter_with_no_wrapper {
10742: my $uri = &clutter(shift);
10743: if ($uri =~ m-^/adm/-) {
10744: $uri =~ s-^/adm/wrapper/-/-;
10745: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10746: }
10747: return $uri;
10748: }
10749:
10750: sub freeze_escape {
10751: my ($value)=@_;
10752: if (ref($value)) {
10753: $value=&nfreeze($value);
10754: return '__FROZEN__'.&escape($value);
10755: }
10756: return &escape($value);
10757: }
10758:
10759:
10760: sub thaw_unescape {
10761: my ($value)=@_;
10762: if ($value =~ /^__FROZEN__/) {
10763: substr($value,0,10,undef);
10764: $value=&unescape($value);
10765: return &thaw($value);
10766: }
10767: return &unescape($value);
10768: }
10769:
10770: sub correct_line_ends {
10771: my ($result)=@_;
10772: $$result =~s/\r\n/\n/mg;
10773: $$result =~s/\r/\n/mg;
10774: }
10775: # ================================================================ Main Program
10776:
10777: sub goodbye {
10778: &logthis("Starting Shut down");
10779: #not converted to using infrastruture and probably shouldn't be
10780: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10781: #converted
10782: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10783: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10784: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10785: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10786: #1.1 only
10787: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10788: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10789: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10790: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10791: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10792: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10793: &logthis(sprintf("%-20s is %s",'hits',$hits));
10794: &flushcourselogs();
10795: &logthis("Shutting down");
10796: }
10797:
10798: sub get_dns {
10799: my ($url,$func,$ignore_cache) = @_;
10800: if (!$ignore_cache) {
10801: my ($content,$cached)=
10802: &Apache::lonnet::is_cached_new('dns',$url);
10803: if ($cached) {
10804: &$func($content);
10805: return;
10806: }
10807: }
10808:
10809: my %alldns;
10810: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10811: foreach my $dns (<$config>) {
10812: next if ($dns !~ /^\^(\S*)/x);
10813: my $line = $1;
10814: my ($host,$protocol) = split(/:/,$line);
10815: if ($protocol ne 'https') {
10816: $protocol = 'http';
10817: }
10818: $alldns{$host} = $protocol;
10819: }
10820: while (%alldns) {
10821: my ($dns) = keys(%alldns);
10822: my $ua=new LWP::UserAgent;
10823: $ua->timeout(30);
10824: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10825: my $response=$ua->request($request);
10826: delete($alldns{$dns});
10827: next if ($response->is_error());
10828: my @content = split("\n",$response->content);
10829: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10830: &$func(\@content);
10831: return;
10832: }
10833: close($config);
10834: my $which = (split('/',$url))[3];
10835: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10836: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10837: my @content = <$config>;
10838: &$func(\@content);
10839: return;
10840: }
10841: # ------------------------------------------------------------ Read domain file
10842: {
10843: my $loaded;
10844: my %domain;
10845:
10846: sub parse_domain_tab {
10847: my ($lines) = @_;
10848: foreach my $line (@$lines) {
10849: next if ($line =~ /^(\#|\s*$ )/x);
10850:
10851: chomp($line);
10852: my ($name,@elements) = split(/:/,$line,9);
10853: my %this_domain;
10854: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10855: 'lang_def', 'city', 'longi', 'lati',
10856: 'primary') {
10857: $this_domain{$field} = shift(@elements);
10858: }
10859: $domain{$name} = \%this_domain;
10860: }
10861: }
10862:
10863: sub reset_domain_info {
10864: undef($loaded);
10865: undef(%domain);
10866: }
10867:
10868: sub load_domain_tab {
10869: my ($ignore_cache) = @_;
10870: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10871: my $fh;
10872: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10873: my @lines = <$fh>;
10874: &parse_domain_tab(\@lines);
10875: }
10876: close($fh);
10877: $loaded = 1;
10878: }
10879:
10880: sub domain {
10881: &load_domain_tab() if (!$loaded);
10882:
10883: my ($name,$what) = @_;
10884: return if ( !exists($domain{$name}) );
10885:
10886: if (!$what) {
10887: return $domain{$name}{'description'};
10888: }
10889: return $domain{$name}{$what};
10890: }
10891:
10892: sub domain_info {
10893: &load_domain_tab() if (!$loaded);
10894: return %domain;
10895: }
10896:
10897: }
10898:
10899:
10900: # ------------------------------------------------------------- Read hosts file
10901: {
10902: my %hostname;
10903: my %hostdom;
10904: my %libserv;
10905: my $loaded;
10906: my %name_to_host;
10907: my %internetdom;
10908: my %LC_dns_serv;
10909:
10910: sub parse_hosts_tab {
10911: my ($file) = @_;
10912: foreach my $configline (@$file) {
10913: next if ($configline =~ /^(\#|\s*$ )/x);
10914: chomp($configline);
10915: if ($configline =~ /^\^/) {
10916: if ($configline =~ /^\^([\w.\-]+)/) {
10917: $LC_dns_serv{$1} = 1;
10918: }
10919: next;
10920: }
10921: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10922: $name=~s/\s//g;
10923: if ($id && $domain && $role && $name) {
10924: $hostname{$id}=$name;
10925: push(@{$name_to_host{$name}}, $id);
10926: $hostdom{$id}=$domain;
10927: if ($role eq 'library') { $libserv{$id}=$name; }
10928: if (defined($protocol)) {
10929: if ($protocol eq 'https') {
10930: $protocol{$id} = $protocol;
10931: } else {
10932: $protocol{$id} = 'http';
10933: }
10934: } else {
10935: $protocol{$id} = 'http';
10936: }
10937: if (defined($intdom)) {
10938: $internetdom{$id} = $intdom;
10939: }
10940: }
10941: }
10942: }
10943:
10944: sub reset_hosts_info {
10945: &purge_remembered();
10946: &reset_domain_info();
10947: &reset_hosts_ip_info();
10948: undef(%name_to_host);
10949: undef(%hostname);
10950: undef(%hostdom);
10951: undef(%libserv);
10952: undef($loaded);
10953: }
10954:
10955: sub load_hosts_tab {
10956: my ($ignore_cache) = @_;
10957: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10958: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10959: my @config = <$config>;
10960: &parse_hosts_tab(\@config);
10961: close($config);
10962: $loaded=1;
10963: }
10964:
10965: sub hostname {
10966: &load_hosts_tab() if (!$loaded);
10967:
10968: my ($lonid) = @_;
10969: return $hostname{$lonid};
10970: }
10971:
10972: sub all_hostnames {
10973: &load_hosts_tab() if (!$loaded);
10974:
10975: return %hostname;
10976: }
10977:
10978: sub all_names {
10979: &load_hosts_tab() if (!$loaded);
10980:
10981: return %name_to_host;
10982: }
10983:
10984: sub all_host_domain {
10985: &load_hosts_tab() if (!$loaded);
10986: return %hostdom;
10987: }
10988:
10989: sub is_library {
10990: &load_hosts_tab() if (!$loaded);
10991:
10992: return exists($libserv{$_[0]});
10993: }
10994:
10995: sub all_library {
10996: &load_hosts_tab() if (!$loaded);
10997:
10998: return %libserv;
10999: }
11000:
11001: sub unique_library {
11002: #2x reverse removes all hostnames that appear more than once
11003: my %unique = reverse &all_library();
11004: return reverse %unique;
11005: }
11006:
11007: sub get_servers {
11008: &load_hosts_tab() if (!$loaded);
11009:
11010: my ($domain,$type) = @_;
11011: my %possible_hosts = ($type eq 'library') ? %libserv
11012: : %hostname;
11013: my %result;
11014: if (ref($domain) eq 'ARRAY') {
11015: while ( my ($host,$hostname) = each(%possible_hosts)) {
11016: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11017: $result{$host} = $hostname;
11018: }
11019: }
11020: } else {
11021: while ( my ($host,$hostname) = each(%possible_hosts)) {
11022: if ($hostdom{$host} eq $domain) {
11023: $result{$host} = $hostname;
11024: }
11025: }
11026: }
11027: return %result;
11028: }
11029:
11030: sub get_unique_servers {
11031: my %unique = reverse &get_servers(@_);
11032: return reverse %unique;
11033: }
11034:
11035: sub host_domain {
11036: &load_hosts_tab() if (!$loaded);
11037:
11038: my ($lonid) = @_;
11039: return $hostdom{$lonid};
11040: }
11041:
11042: sub all_domains {
11043: &load_hosts_tab() if (!$loaded);
11044:
11045: my %seen;
11046: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11047: return @uniq;
11048: }
11049:
11050: sub internet_dom {
11051: &load_hosts_tab() if (!$loaded);
11052:
11053: my ($lonid) = @_;
11054: return $internetdom{$lonid};
11055: }
11056:
11057: sub is_LC_dns {
11058: &load_hosts_tab() if (!$loaded);
11059:
11060: my ($hostname) = @_;
11061: return exists($LC_dns_serv{$hostname});
11062: }
11063:
11064: }
11065:
11066: {
11067: my %iphost;
11068: my %name_to_ip;
11069: my %lonid_to_ip;
11070:
11071: sub get_hosts_from_ip {
11072: my ($ip) = @_;
11073: my %iphosts = &get_iphost();
11074: if (ref($iphosts{$ip})) {
11075: return @{$iphosts{$ip}};
11076: }
11077: return;
11078: }
11079:
11080: sub reset_hosts_ip_info {
11081: undef(%iphost);
11082: undef(%name_to_ip);
11083: undef(%lonid_to_ip);
11084: }
11085:
11086: sub get_host_ip {
11087: my ($lonid) = @_;
11088: if (exists($lonid_to_ip{$lonid})) {
11089: return $lonid_to_ip{$lonid};
11090: }
11091: my $name=&hostname($lonid);
11092: my $ip = gethostbyname($name);
11093: return if (!$ip || length($ip) ne 4);
11094: $ip=inet_ntoa($ip);
11095: $name_to_ip{$name} = $ip;
11096: $lonid_to_ip{$lonid} = $ip;
11097: return $ip;
11098: }
11099:
11100: sub get_iphost {
11101: my ($ignore_cache) = @_;
11102:
11103: if (!$ignore_cache) {
11104: if (%iphost) {
11105: return %iphost;
11106: }
11107: my ($ip_info,$cached)=
11108: &Apache::lonnet::is_cached_new('iphost','iphost');
11109: if ($cached) {
11110: %iphost = %{$ip_info->[0]};
11111: %name_to_ip = %{$ip_info->[1]};
11112: %lonid_to_ip = %{$ip_info->[2]};
11113: return %iphost;
11114: }
11115: }
11116:
11117: # get yesterday's info for fallback
11118: my %old_name_to_ip;
11119: my ($ip_info,$cached)=
11120: &Apache::lonnet::is_cached_new('iphost','iphost');
11121: if ($cached) {
11122: %old_name_to_ip = %{$ip_info->[1]};
11123: }
11124:
11125: my %name_to_host = &all_names();
11126: foreach my $name (keys(%name_to_host)) {
11127: my $ip;
11128: if (!exists($name_to_ip{$name})) {
11129: $ip = gethostbyname($name);
11130: if (!$ip || length($ip) ne 4) {
11131: if (defined($old_name_to_ip{$name})) {
11132: $ip = $old_name_to_ip{$name};
11133: &logthis("Can't find $name defaulting to old $ip");
11134: } else {
11135: &logthis("Name $name no IP found");
11136: next;
11137: }
11138: } else {
11139: $ip=inet_ntoa($ip);
11140: }
11141: $name_to_ip{$name} = $ip;
11142: } else {
11143: $ip = $name_to_ip{$name};
11144: }
11145: foreach my $id (@{ $name_to_host{$name} }) {
11146: $lonid_to_ip{$id} = $ip;
11147: }
11148: push(@{$iphost{$ip}},@{$name_to_host{$name}});
11149: }
11150: &Apache::lonnet::do_cache_new('iphost','iphost',
11151: [\%iphost,\%name_to_ip,\%lonid_to_ip],
11152: 48*60*60);
11153:
11154: return %iphost;
11155: }
11156:
11157: #
11158: # Given a DNS returns the loncapa host name for that DNS
11159: #
11160: sub host_from_dns {
11161: my ($dns) = @_;
11162: my @hosts;
11163: my $ip;
11164:
11165: if (exists($name_to_ip{$dns})) {
11166: $ip = $name_to_ip{$dns};
11167: }
11168: if (!$ip) {
11169: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11170: if (length($ip) == 4) {
11171: $ip = &IO::Socket::inet_ntoa($ip);
11172: }
11173: }
11174: if ($ip) {
11175: @hosts = get_hosts_from_ip($ip);
11176: return $hosts[0];
11177: }
11178: return undef;
11179: }
11180:
11181: sub get_internet_names {
11182: my ($lonid) = @_;
11183: return if ($lonid eq '');
11184: my ($idnref,$cached)=
11185: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11186: if ($cached) {
11187: return $idnref;
11188: }
11189: my $ip = &get_host_ip($lonid);
11190: my @hosts = &get_hosts_from_ip($ip);
11191: my %iphost = &get_iphost();
11192: my (@idns,%seen);
11193: foreach my $id (@hosts) {
11194: my $dom = &host_domain($id);
11195: my $prim_id = &domain($dom,'primary');
11196: my $prim_ip = &get_host_ip($prim_id);
11197: next if ($seen{$prim_ip});
11198: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11199: foreach my $id (@{$iphost{$prim_ip}}) {
11200: my $intdom = &internet_dom($id);
11201: unless (grep(/^\Q$intdom\E$/,@idns)) {
11202: push(@idns,$intdom);
11203: }
11204: }
11205: }
11206: $seen{$prim_ip} = 1;
11207: }
11208: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11209: }
11210:
11211: }
11212:
11213: sub all_loncaparevs {
11214: 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);
11215: }
11216:
11217: BEGIN {
11218:
11219: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11220: unless ($readit) {
11221: {
11222: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11223: %perlvar = (%perlvar,%{$configvars});
11224: }
11225:
11226:
11227: # ------------------------------------------------------ Read spare server file
11228: {
11229: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11230:
11231: while (my $configline=<$config>) {
11232: chomp($configline);
11233: if ($configline) {
11234: my ($host,$type) = split(':',$configline,2);
11235: if (!defined($type) || $type eq '') { $type = 'default' };
11236: push(@{ $spareid{$type} }, $host);
11237: }
11238: }
11239: close($config);
11240: }
11241: # ------------------------------------------------------------ Read permissions
11242: {
11243: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11244:
11245: while (my $configline=<$config>) {
11246: chomp($configline);
11247: if ($configline) {
11248: my ($role,$perm)=split(/ /,$configline);
11249: if ($perm ne '') { $pr{$role}=$perm; }
11250: }
11251: }
11252: close($config);
11253: }
11254:
11255: # -------------------------------------------- Read plain texts for permissions
11256: {
11257: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11258:
11259: while (my $configline=<$config>) {
11260: chomp($configline);
11261: if ($configline) {
11262: my ($short,@plain)=split(/:/,$configline);
11263: %{$prp{$short}} = ();
11264: if (@plain > 0) {
11265: $prp{$short}{'std'} = $plain[0];
11266: for (my $i=1; $i<@plain; $i++) {
11267: $prp{$short}{'alt'.$i} = $plain[$i];
11268: }
11269: }
11270: }
11271: }
11272: close($config);
11273: }
11274:
11275: # ---------------------------------------------------------- Read package table
11276: {
11277: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11278:
11279: while (my $configline=<$config>) {
11280: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11281: chomp($configline);
11282: my ($short,$plain)=split(/:/,$configline);
11283: my ($pack,$name)=split(/\&/,$short);
11284: if ($plain ne '') {
11285: $packagetab{$pack.'&'.$name.'&name'}=$name;
11286: $packagetab{$short}=$plain;
11287: }
11288: }
11289: close($config);
11290: }
11291:
11292: # ---------------------------------------------------------- Read loncaparev table
11293: {
11294: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11295: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11296: while (my $configline=<$config>) {
11297: chomp($configline);
11298: my ($hostid,$loncaparev)=split(/:/,$configline);
11299: $loncaparevs{$hostid}=$loncaparev;
11300: }
11301: close($config);
11302: }
11303: }
11304: }
11305:
11306: # ---------------------------------------------------------- Read serverhostID table
11307: {
11308: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11309: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11310: while (my $configline=<$config>) {
11311: chomp($configline);
11312: my ($name,$id)=split(/:/,$configline);
11313: $serverhomeIDs{$name}=$id;
11314: }
11315: close($config);
11316: }
11317: }
11318: }
11319:
11320: {
11321: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11322: if (-e $file) {
11323: my $parser = HTML::LCParser->new($file);
11324: while (my $token = $parser->get_token()) {
11325: if ($token->[0] eq 'S') {
11326: my $item = $token->[1];
11327: my $name = $token->[2]{'name'};
11328: my $value = $token->[2]{'value'};
11329: if ($item ne '' && $name ne '' && $value ne '') {
11330: my $release = $parser->get_text();
11331: $release =~ s/(^\s*|\s*$ )//gx;
11332: $needsrelease{$item.':'.$name.':'.$value} = $release;
11333: }
11334: }
11335: }
11336: }
11337: }
11338:
11339: # ---------------------------------------------------------- Read managers table
11340: {
11341: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11342: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11343: while (my $configline=<$config>) {
11344: chomp($configline);
11345: next if ($configline =~ /^\#/);
11346: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11347: $managerstab{$configline} = 1;
11348: }
11349: }
11350: close($config);
11351: }
11352: }
11353: }
11354:
11355: # ------------- set up temporary directory
11356: {
11357: $tmpdir = LONCAPA::tempdir();
11358:
11359: }
11360:
11361: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11362: 'compress_threshold'=> 20_000,
11363: });
11364:
11365: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11366: $dumpcount=0;
11367: $locknum=0;
11368:
11369: &logtouch();
11370: &logthis('<font color="yellow">INFO: Read configuration</font>');
11371: $readit=1;
11372: {
11373: use integer;
11374: my $test=(2**32)+1;
11375: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11376: &logthis(" Detected 64bit platform ($_64bit)");
11377: }
11378: }
11379: }
11380:
11381: 1;
11382: __END__
11383:
11384: =pod
11385:
11386: =head1 NAME
11387:
11388: Apache::lonnet - Subroutines to ask questions about things in the network.
11389:
11390: =head1 SYNOPSIS
11391:
11392: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11393:
11394: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11395:
11396: Common parameters:
11397:
11398: =over 4
11399:
11400: =item *
11401:
11402: $uname : an internal username (if $cname expecting a course Id specifically)
11403:
11404: =item *
11405:
11406: $udom : a domain (if $cdom expecting a course's domain specifically)
11407:
11408: =item *
11409:
11410: $symb : a resource instance identifier
11411:
11412: =item *
11413:
11414: $namespace : the name of a .db file that contains the data needed or
11415: being set.
11416:
11417: =back
11418:
11419: =head1 OVERVIEW
11420:
11421: lonnet provides subroutines which interact with the
11422: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11423: about classes, users, and resources.
11424:
11425: For many of these objects you can also use this to store data about
11426: them or modify them in various ways.
11427:
11428: =head2 Symbs
11429:
11430: To identify a specific instance of a resource, LON-CAPA uses symbols
11431: or "symbs"X<symb>. These identifiers are built from the URL of the
11432: map, the resource number of the resource in the map, and the URL of
11433: the resource itself. The latter is somewhat redundant, but might help
11434: if maps change.
11435:
11436: An example is
11437:
11438: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11439:
11440: The respective map entry is
11441:
11442: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11443: title="Problem 2">
11444: </resource>
11445:
11446: Symbs are used by the random number generator, as well as to store and
11447: restore data specific to a certain instance of for example a problem.
11448:
11449: =head2 Storing And Retrieving Data
11450:
11451: X<store()>X<cstore()>X<restore()>Three of the most important functions
11452: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11453: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11454: is is the non-critical message twin of cstore. These functions are for
11455: handlers to store a perl hash to a user's permanent data space in an
11456: easy manner, and to retrieve it again on another call. It is expected
11457: that a handler would use this once at the beginning to retrieve data,
11458: and then again once at the end to send only the new data back.
11459:
11460: The data is stored in the user's data directory on the user's
11461: homeserver under the ID of the course.
11462:
11463: The hash that is returned by restore will have all of the previous
11464: value for all of the elements of the hash.
11465:
11466: Example:
11467:
11468: #creating a hash
11469: my %hash;
11470: $hash{'foo'}='bar';
11471:
11472: #storing it
11473: &Apache::lonnet::cstore(\%hash);
11474:
11475: #changing a value
11476: $hash{'foo'}='notbar';
11477:
11478: #adding a new value
11479: $hash{'bar'}='foo';
11480: &Apache::lonnet::cstore(\%hash);
11481:
11482: #retrieving the hash
11483: my %history=&Apache::lonnet::restore();
11484:
11485: #print the hash
11486: foreach my $key (sort(keys(%history))) {
11487: print("\%history{$key} = $history{$key}");
11488: }
11489:
11490: Will print out:
11491:
11492: %history{1:foo} = bar
11493: %history{1:keys} = foo:timestamp
11494: %history{1:timestamp} = 990455579
11495: %history{2:bar} = foo
11496: %history{2:foo} = notbar
11497: %history{2:keys} = foo:bar:timestamp
11498: %history{2:timestamp} = 990455580
11499: %history{bar} = foo
11500: %history{foo} = notbar
11501: %history{timestamp} = 990455580
11502: %history{version} = 2
11503:
11504: Note that the special hash entries C<keys>, C<version> and
11505: C<timestamp> were added to the hash. C<version> will be equal to the
11506: total number of versions of the data that have been stored. The
11507: C<timestamp> attribute will be the UNIX time the hash was
11508: stored. C<keys> is available in every historical section to list which
11509: keys were added or changed at a specific historical revision of a
11510: hash.
11511:
11512: B<Warning>: do not store the hash that restore returns directly. This
11513: will cause a mess since it will restore the historical keys as if the
11514: were new keys. I.E. 1:foo will become 1:1:foo etc.
11515:
11516: Calling convention:
11517:
11518: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11519: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11520:
11521: For more detailed information, see lonnet specific documentation.
11522:
11523: =head1 RETURN MESSAGES
11524:
11525: =over 4
11526:
11527: =item * B<con_lost>: unable to contact remote host
11528:
11529: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11530: when the connection is brought back up
11531:
11532: =item * B<con_failed>: unable to contact remote host and unable to save message
11533: for later delivery
11534:
11535: =item * B<error:>: an error a occurred, a description of the error follows the :
11536:
11537: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11538: that was requested
11539:
11540: =back
11541:
11542: =head1 PUBLIC SUBROUTINES
11543:
11544: =head2 Session Environment Functions
11545:
11546: =over 4
11547:
11548: =item *
11549: X<appenv()>
11550: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11551: the user envirnoment file, and will be restored for each access this
11552: user makes during this session, also modifies the %env for the current
11553: process. Optional rolesarrayref - if defined contains a reference to an array
11554: of roles which are exempt from the restriction on modifying user.role entries
11555: in the user's environment.db and in %env.
11556:
11557: =item *
11558: X<delenv()>
11559: B<delenv($delthis,$regexp)>: removes all items from the session
11560: environment file that begin with $delthis. If the
11561: optional second arg - $regexp - is true, $delthis is treated as a
11562: regular expression, otherwise \Q$delthis\E is used.
11563: The values are also deleted from the current processes %env.
11564:
11565: =item * get_env_multiple($name)
11566:
11567: gets $name from the %env hash, it seemlessly handles the cases where multiple
11568: values may be defined and end up as an array ref.
11569:
11570: returns an array of values
11571:
11572: =back
11573:
11574: =head2 User Information
11575:
11576: =over 4
11577:
11578: =item *
11579: X<queryauthenticate()>
11580: B<queryauthenticate($uname,$udom)>: try to determine user's current
11581: authentication scheme
11582:
11583: =item *
11584: X<authenticate()>
11585: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11586: authenticate user from domain's lib servers (first use the current
11587: one). C<$upass> should be the users password.
11588: $checkdefauth is optional (value is 1 if a check should be made to
11589: authenticate user using default authentication method, and allow
11590: account creation if username does not have account in the domain).
11591: $clientcancheckhost is optional (value is 1 if checking whether the
11592: server can host will occur on the client side in lonauth.pm).
11593:
11594: =item *
11595: X<homeserver()>
11596: B<homeserver($uname,$udom)>: find the server which has
11597: the user's directory and files (there must be only one), this caches
11598: the answer, and also caches if there is a borken connection.
11599:
11600: =item *
11601: X<idget()>
11602: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11603: (IDs are a unique resource in a domain, there must be only 1 ID per
11604: username, and only 1 username per ID in a specific domain) (returns
11605: hash: id=>name,id=>name)
11606:
11607: =item *
11608: X<idrget()>
11609: B<idrget($udom,@unames)>: find the IDs behind a list of
11610: usernames (returns hash: name=>id,name=>id)
11611:
11612: =item *
11613: X<idput()>
11614: B<idput($udom,%ids)>: store away a list of names and associated IDs
11615:
11616: =item *
11617: X<rolesinit()>
11618: B<rolesinit($udom,$username,$authhost)>: get user privileges
11619:
11620: =item *
11621: X<getsection()>
11622: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11623: course $cname, return section name/number or '' for "not in course"
11624: and '-1' for "no section"
11625:
11626: =item *
11627: X<userenvironment()>
11628: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11629: passed in @what from the requested user's environment, returns a hash
11630:
11631: =item *
11632: X<userlog_query()>
11633: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11634: activity.log file. %filters defines filters applied when parsing the
11635: log file. These can be start or end timestamps, or the type of action
11636: - log to look for Login or Logout events, check for Checkin or
11637: Checkout, role for role selection. The response is in the form
11638: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11639: escaped strings of the action recorded in the activity.log file.
11640:
11641: =back
11642:
11643: =head2 User Roles
11644:
11645: =over 4
11646:
11647: =item *
11648:
11649: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11650: F: full access
11651: U,I,K: authentication modes (cxx only)
11652: '': forbidden
11653: 1: user needs to choose course
11654: 2: browse allowed
11655: A: passphrase authentication needed
11656:
11657: =item *
11658:
11659: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11660: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11661: and course level
11662:
11663: =item *
11664:
11665: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11666: (rolesplain.tab); plain text explanation of a user role term.
11667: $type is Course (default) or Community.
11668: If $forcedefault evaluates to true, text returned will be default
11669: text for $type. Otherwise, if this is a course, the text returned
11670: will be a custom name for the role (if defined in the course's
11671: environment). If no custom name is defined the default is returned.
11672:
11673: =item *
11674:
11675: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11676: All arguments are optional. Returns a hash of a roles, either for
11677: co-author/assistant author roles for a user's Construction Space
11678: (default), or if $context is 'userroles', roles for the user himself,
11679: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11680: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11681: For each key, value is set to colon-separated start and end times for
11682: the role. If no username and domain are specified, will default to
11683: current user/domain. Types, roles, and roledoms are references to arrays
11684: of role statuses (active, future or previous), roles
11685: (e.g., cc,in, st etc.) and domains of the roles which can be used
11686: to restrict the list of roles reported. If no array ref is
11687: provided for types, will default to return only active roles.
11688:
11689: =back
11690:
11691: =head2 User Modification
11692:
11693: =over 4
11694:
11695: =item *
11696:
11697: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11698: user for the level given by URL. Optional start and end dates (leave empty
11699: string or zero for "no date")
11700:
11701: =item *
11702:
11703: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11704: change a users, password, possible return values are: ok,
11705: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11706: refused
11707:
11708: =item *
11709:
11710: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11711:
11712: =item *
11713:
11714: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11715: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11716:
11717: will update user information (firstname,middlename,lastname,generation,
11718: permanentemail), and if forceid is true, student/employee ID also.
11719: A user's institutional affiliation(s) can also be updated.
11720: User information fields will not be overwritten with empty entries
11721: unless the field is included in the $candelete array reference.
11722: This array is included when a single user is modified via "Manage Users",
11723: or when Autoupdate.pl is run by cron in a domain.
11724:
11725: =item *
11726:
11727: modifystudent
11728:
11729: modify a student's enrollment and identification information.
11730: The course id is resolved based on the current users environment.
11731: This means the envoking user must be a course coordinator or otherwise
11732: associated with a course.
11733:
11734: This call is essentially a wrapper for lonnet::modifyuser and
11735: lonnet::modify_student_enrollment
11736:
11737: Inputs:
11738:
11739: =over 4
11740:
11741: =item B<$udom> Student's loncapa domain
11742:
11743: =item B<$uname> Student's loncapa login name
11744:
11745: =item B<$uid> Student/Employee ID
11746:
11747: =item B<$umode> Student's authentication mode
11748:
11749: =item B<$upass> Student's password
11750:
11751: =item B<$first> Student's first name
11752:
11753: =item B<$middle> Student's middle name
11754:
11755: =item B<$last> Student's last name
11756:
11757: =item B<$gene> Student's generation
11758:
11759: =item B<$usec> Student's section in course
11760:
11761: =item B<$end> Unix time of the roles expiration
11762:
11763: =item B<$start> Unix time of the roles start date
11764:
11765: =item B<$forceid> If defined, allow $uid to be changed
11766:
11767: =item B<$desiredhome> server to use as home server for student
11768:
11769: =item B<$email> Student's permanent e-mail address
11770:
11771: =item B<$type> Type of enrollment (auto or manual)
11772:
11773: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11774:
11775: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11776:
11777: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11778:
11779: =item B<$context> role change context (shown in User Management Logs display in a course)
11780:
11781: =item B<$inststatus> institutional status of user - : separated string of escaped status types
11782:
11783: =back
11784:
11785: =item *
11786:
11787: modify_student_enrollment
11788:
11789: Change a students enrollment status in a class. The environment variable
11790: 'role.request.course' must be defined for this function to proceed.
11791:
11792: Inputs:
11793:
11794: =over 4
11795:
11796: =item $udom, students domain
11797:
11798: =item $uname, students name
11799:
11800: =item $uid, students user id
11801:
11802: =item $first, students first name
11803:
11804: =item $middle
11805:
11806: =item $last
11807:
11808: =item $gene
11809:
11810: =item $usec
11811:
11812: =item $end
11813:
11814: =item $start
11815:
11816: =item $type
11817:
11818: =item $locktype
11819:
11820: =item $cid
11821:
11822: =item $selfenroll
11823:
11824: =item $context
11825:
11826: =back
11827:
11828:
11829: =item *
11830:
11831: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11832: custom role; give a custom role to a user for the level given by URL. Specify
11833: name and domain of role author, and role name
11834:
11835: =item *
11836:
11837: revokerole($udom,$uname,$url,$role) : revoke a role for url
11838:
11839: =item *
11840:
11841: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11842:
11843: =back
11844:
11845: =head2 Course Infomation
11846:
11847: =over 4
11848:
11849: =item *
11850:
11851: coursedescription($courseid,$options) : returns a hash of information about the
11852: specified course id, including all environment settings for the
11853: course, the description of the course will be in the hash under the
11854: key 'description'
11855:
11856: $options is an optional parameter that if supplied is a hash reference that controls
11857: what how this function works. It has the following key/values:
11858:
11859: =over 4
11860:
11861: =item freshen_cache
11862:
11863: If defined, and the environment cache for the course is valid, it is
11864: returned in the returned hash.
11865:
11866: =item one_time
11867:
11868: If defined, the last cache time is set to _now_
11869:
11870: =item user
11871:
11872: If defined, the supplied username is used instead of the current user.
11873:
11874:
11875: =back
11876:
11877: =item *
11878:
11879: resdata($name,$domain,$type,@which) : request for current parameter
11880: setting for a specific $type, where $type is either 'course' or 'user',
11881: @what should be a list of parameters to ask about. This routine caches
11882: answers for 5 minutes.
11883:
11884: =item *
11885:
11886: get_courseresdata($courseid, $domain) : dump the entire course resource
11887: data base, returning a hash that is keyed by the resource name and has
11888: values that are the resource value. I believe that the timestamps and
11889: versions are also returned.
11890:
11891:
11892: =back
11893:
11894: =head2 Course Modification
11895:
11896: =over 4
11897:
11898: =item *
11899:
11900: writecoursepref($courseid,%prefs) : write preferences (environment
11901: database) for a course
11902:
11903: =item *
11904:
11905: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11906:
11907: =item *
11908:
11909: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11910:
11911: =back
11912:
11913: =head2 Resource Subroutines
11914:
11915: =over 4
11916:
11917: =item *
11918:
11919: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11920:
11921: =item *
11922:
11923: repcopy($filename) : subscribes to the requested file, and attempts to
11924: replicate from the owning library server, Might return
11925: 'unavailable', 'not_found', 'forbidden', 'ok', or
11926: 'bad_request', also attempts to grab the metadata for the
11927: resource. Expects the local filesystem pathname
11928: (/home/httpd/html/res/....)
11929:
11930: =back
11931:
11932: =head2 Resource Information
11933:
11934: =over 4
11935:
11936: =item *
11937:
11938: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11939: a vairety of different possible values, $varname should be a request
11940: string, and the other parameters can be used to specify who and what
11941: one is asking about.
11942:
11943: Possible values for $varname are environment.lastname (or other item
11944: from the envirnment hash), user.name (or someother aspect about the
11945: user), resource.0.maxtries (or some other part and parameter of a
11946: resource)
11947:
11948: =item *
11949:
11950: directcondval($number) : get current value of a condition; reads from a state
11951: string
11952:
11953: =item *
11954:
11955: condval($condidx) : value of condition index based on state
11956:
11957: =item *
11958:
11959: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11960: resource's metadata, $what should be either a specific key, or either
11961: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11962: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11963:
11964: this function automatically caches all requests
11965:
11966: =item *
11967:
11968: metadata_query($query,$custom,$customshow) : make a metadata query against the
11969: network of library servers; returns file handle of where SQL and regex results
11970: will be stored for query
11971:
11972: =item *
11973:
11974: symbread($filename) : return symbolic list entry (filename argument optional);
11975: returns the data handle
11976:
11977: =item *
11978:
11979: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11980: a possible symb for the URL in $thisfn, and if is an encryypted
11981: resource that the user accessed using /enc/ returns a 1 on success, 0
11982: on failure, user must be in a course, as it assumes the existance of
11983: the course initial hash, and uses $env('request.course.id'}
11984:
11985:
11986: =item *
11987:
11988: symbclean($symb) : removes versions numbers from a symb, returns the
11989: cleaned symb
11990:
11991: =item *
11992:
11993: is_on_map($uri) : checks if the $uri is somewhere on the current
11994: course map, user must be in a course for it to work.
11995:
11996: =item *
11997:
11998: numval($salt) : return random seed value (addend for rndseed)
11999:
12000: =item *
12001:
12002: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12003: a random seed, all arguments are optional, if they aren't sent it uses the
12004: environment to derive them. Note: if symb isn't sent and it can't get one
12005: from &symbread it will use the current time as its return value
12006:
12007: =item *
12008:
12009: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12010: unfakeable, receipt
12011:
12012: =item *
12013:
12014: receipt() : API to ireceipt working off of env values; given out to users
12015:
12016: =item *
12017:
12018: countacc($url) : count the number of accesses to a given URL
12019:
12020: =item *
12021:
12022: 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
12023:
12024: =item *
12025:
12026: 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)
12027:
12028: =item *
12029:
12030: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12031:
12032: =item *
12033:
12034: devalidate($symb) : devalidate temporary spreadsheet calculations,
12035: forcing spreadsheet to reevaluate the resource scores next time.
12036:
12037: =back
12038:
12039: =head2 Storing/Retreiving Data
12040:
12041: =over 4
12042:
12043: =item *
12044:
12045: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12046: for this url; hashref needs to be given and should be a \%hashname; the
12047: remaining args aren't required and if they aren't passed or are '' they will
12048: be derived from the env
12049:
12050: =item *
12051:
12052: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12053: uses critical subroutine
12054:
12055: =item *
12056:
12057: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12058: all args are optional
12059:
12060: =item *
12061:
12062: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12063: dumps the complete (or key matching regexp) namespace into a hash
12064: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12065: normally &store()ed into
12066:
12067: $range should be either an integer '100' (give me the first 100
12068: matching records)
12069: or be two integers sperated by a - with no spaces
12070: '30-50' (give me the 30th through the 50th matching
12071: records)
12072:
12073:
12074: =item *
12075:
12076: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12077: replaces a &store() version of data with a replacement set of data
12078: for a particular resource in a namespace passed in the $storehash hash
12079: reference
12080:
12081: =item *
12082:
12083: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12084: works very similar to store/cstore, but all data is stored in a
12085: temporary location and can be reset using tmpreset, $storehash should
12086: be a hash reference, returns nothing on success
12087:
12088: =item *
12089:
12090: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12091: similar to restore, but all data is stored in a temporary location and
12092: can be reset using tmpreset. Returns a hash of values on success,
12093: error string otherwise.
12094:
12095: =item *
12096:
12097: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12098: deltes all keys for $symb form the temporary storage hash.
12099:
12100: =item *
12101:
12102: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12103: reference filled in from namesp ($udom and $uname are optional)
12104:
12105: =item *
12106:
12107: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12108: namesp ($udom and $uname are optional)
12109:
12110: =item *
12111:
12112: dump($namespace,$udom,$uname,$regexp,$range) :
12113: dumps the complete (or key matching regexp) namespace into a hash
12114: ($udom, $uname, $regexp, $range are optional)
12115:
12116: $range should be either an integer '100' (give me the first 100
12117: matching records)
12118: or be two integers sperated by a - with no spaces
12119: '30-50' (give me the 30th through the 50th matching
12120: records)
12121: =item *
12122:
12123: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12124: $store can be a scalar, an array reference, or if the amount to be
12125: incremented is > 1, a hash reference.
12126:
12127: ($udom and $uname are optional)
12128:
12129: =item *
12130:
12131: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12132: ($udom and $uname are optional)
12133:
12134: =item *
12135:
12136: cput($namespace,$storehash,$udom,$uname) : critical put
12137: ($udom and $uname are optional)
12138:
12139: =item *
12140:
12141: newput($namespace,$storehash,$udom,$uname) :
12142:
12143: Attempts to store the items in the $storehash, but only if they don't
12144: currently exist, if this succeeds you can be certain that you have
12145: successfully created a new key value pair in the $namespace db.
12146:
12147:
12148: Args:
12149: $namespace: name of database to store values to
12150: $storehash: hashref to store to the db
12151: $udom: (optional) domain of user containing the db
12152: $uname: (optional) name of user caontaining the db
12153:
12154: Returns:
12155: 'ok' -> succeeded in storing all keys of $storehash
12156: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12157: least <key> already existed in the db (other
12158: requested keys may also already exist)
12159: 'error: <msg>' -> unable to tie the DB or other error occurred
12160: 'con_lost' -> unable to contact request server
12161: 'refused' -> action was not allowed by remote machine
12162:
12163:
12164: =item *
12165:
12166: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12167: reference filled in from namesp (encrypts the return communication)
12168: ($udom and $uname are optional)
12169:
12170: =item *
12171:
12172: log($udom,$name,$home,$message) : write to permanent log for user; use
12173: critical subroutine
12174:
12175: =item *
12176:
12177: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12178: array reference filled in from namespace found in domain level on either
12179: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12180:
12181: =item *
12182:
12183: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12184: domain level either on specified domain server ($uhome) or primary domain
12185: server ($udom and $uhome are optional)
12186:
12187: =item *
12188:
12189: get_domain_defaults($target_domain) : returns hash with defaults for
12190: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12191: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12192: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12193: Values are retrieved from cache (if current), or from domain's configuration.db
12194: (if available), or lastly from values in lonTabs/dns_domain,tab,
12195: or lonTabs/domain.tab.
12196:
12197: %domdefaults = &get_auth_defaults($target_domain);
12198:
12199: =back
12200:
12201: =head2 Network Status Functions
12202:
12203: =over 4
12204:
12205: =item *
12206:
12207: dirlist() : return directory list based on URI (first arg).
12208:
12209: Inputs: 1 required, 5 optional.
12210:
12211: =over
12212:
12213: =item
12214: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12215:
12216: =item
12217: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12218:
12219: =item
12220: $username - username of user/course to be listed. Extracted from $uri if absent.
12221:
12222: =item
12223: $getpropath - boolean: 1 if prepend path using &propath().
12224:
12225: =item
12226: $getuserdir - boolean: 1 if prepend path for "userfiles".
12227:
12228: =item
12229: $alternateRoot - path to prepend in place of path from $uri.
12230:
12231: =back
12232:
12233: Returns: Array of up to two items.
12234:
12235: =over
12236:
12237: a reference to an array of files/subdirectories
12238:
12239: =over
12240:
12241: Each element in the array of files/subdirectories is a & separated list of
12242: item name and the result of running stat on the item. If dirlist was requested
12243: for a file instead of a directory, the item name will be ''. For a directory
12244: listing, if the item is a metadata file, the element will end &N&M
12245: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12246: default copyright set (1).
12247:
12248: =back
12249:
12250: a scalar containing error condition (if encountered).
12251:
12252: =over
12253:
12254: =item
12255: no_host (no homeserver identified for $username:$domain).
12256:
12257: =item
12258: no_such_host (server contacted for listing not identified as valid host).
12259:
12260: =item
12261: con_lost (connection to remote server failed).
12262:
12263: =item
12264: refused (invalid $username:$domain received on lond side).
12265:
12266: =item
12267: no_such_dir (directory at specified path on lond side does not exist).
12268:
12269: =item
12270: empty (directory at specified path on lond side is empty).
12271:
12272: =over
12273:
12274: This is currently not encountered because the &ls3, &ls2,
12275: &ls (_handler) routines on the lond side do not filter out
12276: . and .. from a directory listing.
12277:
12278: =back
12279:
12280: =back
12281:
12282: =back
12283:
12284: =item *
12285:
12286: spareserver() : find server with least workload from spare.tab
12287:
12288:
12289: =item *
12290:
12291: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12292: if there is no corresponding loncapa host.
12293:
12294: =back
12295:
12296:
12297: =head2 Apache Request
12298:
12299: =over 4
12300:
12301: =item *
12302:
12303: ssi($url,%hash) : server side include, does a complete request cycle on url to
12304: localhost, posts hash
12305:
12306: =back
12307:
12308: =head2 Data to String to Data
12309:
12310: =over 4
12311:
12312: =item *
12313:
12314: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12315: and '&' separators, supports elements that are arrayrefs and hashrefs
12316:
12317: =item *
12318:
12319: hashref2str($hashref) : convert a hashref into a string complete with
12320: escaping and '=' and '&' separators, supports elements that are
12321: arrayrefs and hashrefs
12322:
12323: =item *
12324:
12325: arrayref2str($arrayref) : convert an arrayref into a string complete
12326: with escaping and '&' separators, supports elements that are arrayrefs
12327: and hashrefs
12328:
12329: =item *
12330:
12331: str2hash($string) : convert string to hash using unescaping and
12332: splitting on '=' and '&', supports elements that are arrayrefs and
12333: hashrefs
12334:
12335: =item *
12336:
12337: str2array($string) : convert string to hash using unescaping and
12338: splitting on '&', supports elements that are arrayrefs and hashrefs
12339:
12340: =back
12341:
12342: =head2 Logging Routines
12343:
12344:
12345: These routines allow one to make log messages in the lonnet.log and
12346: lonnet.perm logfiles.
12347:
12348: =over 4
12349:
12350: =item *
12351:
12352: logtouch() : make sure the logfile, lonnet.log, exists
12353:
12354: =item *
12355:
12356: logthis() : append message to the normal lonnet.log file, it gets
12357: preiodically rolled over and deleted.
12358:
12359: =item *
12360:
12361: logperm() : append a permanent message to lonnet.perm.log, this log
12362: file never gets deleted by any automated portion of the system, only
12363: messages of critical importance should go in here.
12364:
12365:
12366: =back
12367:
12368: =head2 General File Helper Routines
12369:
12370: =over 4
12371:
12372: =item *
12373:
12374: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12375: (a) files in /uploaded
12376: (i) If a local copy of the file exists -
12377: compares modification date of local copy with last-modified date for
12378: definitive version stored on home server for course. If local copy is
12379: stale, requests a new version from the home server and stores it.
12380: If the original has been removed from the home server, then local copy
12381: is unlinked.
12382: (ii) If local copy does not exist -
12383: requests the file from the home server and stores it.
12384:
12385: If $caller is 'uploadrep':
12386: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12387: for request for files originally uploaded via DOCS.
12388: - returns 'ok' if fresh local copy now available, -1 otherwise.
12389:
12390: Otherwise:
12391: This indicates a call from the content generation phase of the request.
12392: - returns the entire contents of the file or -1.
12393:
12394: (b) files in /res
12395: - returns the entire contents of a file or -1;
12396: it properly subscribes to and replicates the file if neccessary.
12397:
12398:
12399: =item *
12400:
12401: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12402: reference
12403:
12404: returns either a stat() list of data about the file or an empty list
12405: if the file doesn't exist or couldn't find out about it (connection
12406: problems or user unknown)
12407:
12408: =item *
12409:
12410: filelocation($dir,$file) : returns file system location of a file
12411: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12412: directory that relative $file lookups are to looked in ($dir of /a/dir
12413: and a file of ../bob will become /a/bob)
12414:
12415: =item *
12416:
12417: hreflocation($dir,$file) : returns file system location or a URL; same as
12418: filelocation except for hrefs
12419:
12420: =item *
12421:
12422: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12423:
12424: =back
12425:
12426: =head2 Usererfile file routines (/uploaded*)
12427:
12428: =over 4
12429:
12430: =item *
12431:
12432: userfileupload(): main rotine for putting a file in a user or course's
12433: filespace, arguments are,
12434:
12435: formname - required - this is the name of the element in $env where the
12436: filename, and the contents of the file to create/modifed exist
12437: the filename is in $env{'form.'.$formname.'.filename'} and the
12438: contents of the file is located in $env{'form.'.$formname}
12439: context - if coursedoc, store the file in the course of the active role
12440: of the current user;
12441: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12442: if 'canceloverwrite': delete file in tmp/overwrites directory
12443: subdir - required - subdirectory to put the file in under ../userfiles/
12444: if undefined, it will be placed in "unknown"
12445:
12446: (This routine calls clean_filename() to remove any dangerous
12447: characters from the filename, and then calls finuserfileupload() to
12448: complete the transaction)
12449:
12450: returns either the url of the uploaded file (/uploaded/....) if successful
12451: and /adm/notfound.html if unsuccessful
12452:
12453: =item *
12454:
12455: clean_filename(): routine for cleaing a filename up for storage in
12456: userfile space, argument is:
12457:
12458: filename - proposed filename
12459:
12460: returns: the new clean filename
12461:
12462: =item *
12463:
12464: finishuserfileupload(): routine that creates and sends the file to
12465: userspace, probably shouldn't be called directly
12466:
12467: docuname: username or courseid of destination for the file
12468: docudom: domain of user/course of destination for the file
12469: formname: same as for userfileupload()
12470: fname: filename (including subdirectories) for the file
12471: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12472: allfiles: reference to hash used to store objects found by parser
12473: codebase: reference to hash used for codebases of java objects found by parser
12474: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12475: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12476: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12477: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12478: context: if 'overwrite', will move the uploaded file from its temporary location to
12479: userfiles to facilitate overwriting a previously uploaded file with same name.
12480: mimetype: reference to scalar to accommodate mime type determined
12481: from File::MMagic if $parser = parse.
12482:
12483: returns either the url of the uploaded file (/uploaded/....) if successful
12484: and /adm/notfound.html if unsuccessful (or an error message if context
12485: was 'overwrite').
12486:
12487:
12488: =item *
12489:
12490: renameuserfile(): renames an existing userfile to a new name
12491:
12492: Args:
12493: docuname: username or courseid of destination for the file
12494: docudom: domain of user/course of destination for the file
12495: old: current file name (including any subdirs under userfiles)
12496: new: desired file name (including any subdirs under userfiles)
12497:
12498: =item *
12499:
12500: mkdiruserfile(): creates a directory is a userfiles dir
12501:
12502: Args:
12503: docuname: username or courseid of destination for the file
12504: docudom: domain of user/course of destination for the file
12505: dir: dir to create (including any subdirs under userfiles)
12506:
12507: =item *
12508:
12509: removeuserfile(): removes a file that exists in userfiles
12510:
12511: Args:
12512: docuname: username or courseid of destination for the file
12513: docudom: domain of user/course of destination for the file
12514: fname: filname to delete (including any subdirs under userfiles)
12515:
12516: =item *
12517:
12518: removeuploadedurl(): convience function for removeuserfile()
12519:
12520: Args:
12521: url: a full /uploaded/... url to delete
12522:
12523: =item *
12524:
12525: get_portfile_permissions():
12526: Args:
12527: domain: domain of user or course contain the portfolio files
12528: user: name of user or num of course contain the portfolio files
12529: Returns:
12530: hashref of a dump of the proper file_permissions.db
12531:
12532:
12533: =item *
12534:
12535: get_access_controls():
12536:
12537: Args:
12538: current_permissions: the hash ref returned from get_portfile_permissions()
12539: group: (optional) the group you want the files associated with
12540: file: (optional) the file you want access info on
12541:
12542: Returns:
12543: a hash (keys are file names) of hashes containing
12544: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12545: values are XML containing access control settings (see below)
12546:
12547: Internal notes:
12548:
12549: access controls are stored in file_permissions.db as key=value pairs.
12550: key -> path to file/file_name\0uniqueID:scope_end_start
12551: where scope -> public,guest,course,group,domains or users.
12552: end -> UNIX time for end of access (0 -> no end date)
12553: start -> UNIX time for start of access
12554:
12555: value -> XML description of access control
12556: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12557: <start></start>
12558: <end></end>
12559:
12560: <password></password> for scope type = guest
12561:
12562: <domain></domain> for scope type = course or group
12563: <number></number>
12564: <roles id="">
12565: <role></role>
12566: <access></access>
12567: <section></section>
12568: <group></group>
12569: </roles>
12570:
12571: <dom></dom> for scope type = domains
12572:
12573: <users> for scope type = users
12574: <user>
12575: <uname></uname>
12576: <udom></udom>
12577: </user>
12578: </users>
12579: </scope>
12580:
12581: Access data is also aggregated for each file in an additional key=value pair:
12582: key -> path to file/file_name\0accesscontrol
12583: value -> reference to hash
12584: hash contains key = value pairs
12585: where key = uniqueID:scope_end_start
12586: value = UNIX time record was last updated
12587:
12588: Used to improve speed of look-ups of access controls for each file.
12589:
12590: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12591:
12592: modify_access_controls():
12593:
12594: Modifies access controls for a portfolio file
12595: Args
12596: 1. file name
12597: 2. reference to hash of required changes,
12598: 3. domain
12599: 4. username
12600: where domain,username are the domain of the portfolio owner
12601: (either a user or a course)
12602:
12603: Returns:
12604: 1. result of additions or updates ('ok' or 'error', with error message).
12605: 2. result of deletions ('ok' or 'error', with error message).
12606: 3. reference to hash of any new or updated access controls.
12607: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12608: key = integer (inbound ID)
12609: value = uniqueID
12610:
12611: =back
12612:
12613: =head2 HTTP Helper Routines
12614:
12615: =over 4
12616:
12617: =item *
12618:
12619: escape() : unpack non-word characters into CGI-compatible hex codes
12620:
12621: =item *
12622:
12623: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12624:
12625: =back
12626:
12627: =head1 PRIVATE SUBROUTINES
12628:
12629: =head2 Underlying communication routines (Shouldn't call)
12630:
12631: =over 4
12632:
12633: =item *
12634:
12635: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12636:
12637: =item *
12638:
12639: reply() : uses subreply to send a message to remote machine, logs all failures
12640:
12641: =item *
12642:
12643: critical() : passes a critical message to another server; if cannot
12644: get through then place message in connection buffer directory and
12645: returns con_delayed, if incapable of saving message, returns
12646: con_failed
12647:
12648: =item *
12649:
12650: reconlonc() : tries to reconnect lonc client processes.
12651:
12652: =back
12653:
12654: =head2 Resource Access Logging
12655:
12656: =over 4
12657:
12658: =item *
12659:
12660: flushcourselogs() : flush (save) buffer logs and access logs
12661:
12662: =item *
12663:
12664: courselog($what) : save message for course in hash
12665:
12666: =item *
12667:
12668: courseacclog($what) : save message for course using &courselog(). Perform
12669: special processing for specific resource types (problems, exams, quizzes, etc).
12670:
12671: =item *
12672:
12673: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12674: as a PerlChildExitHandler
12675:
12676: =back
12677:
12678: =head2 Other
12679:
12680: =over 4
12681:
12682: =item *
12683:
12684: symblist($mapname,%newhash) : update symbolic storage links
12685:
12686: =back
12687:
12688: =cut
12689:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>