File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1150:
download - view:
text,
annotated -
select for diffs
Tue Dec 20 22:40:06 2011 UTC (12 years, 7 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Improve efficiency by caching information for all slots in course.
- New routines:
&get_reservable_slots() -- information for current user about student schedulable
slots opening in the future, which will be available to the user.
(%remembered stores data for duration of request).
&get_course_slots() - retrieve contents of 'slots' db from cache or lonnet::dump().
&devalidate_slots_cache() -- devalidates 'allslots' cache.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1150 2011/12/20 22:40:06 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:
100: use File::Copy;
101:
102: my $readit;
103: my $max_connection_retries = 10; # Or some such value.
104:
105: require Exporter;
106:
107: our @ISA = qw (Exporter);
108: our @EXPORT = qw(%env);
109:
110:
111: # --------------------------------------------------------------------- Logging
112: {
113: my $logid;
114: sub instructor_log {
115: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
116: if (($cnum eq '') || ($cdom eq '')) {
117: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
118: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
119: }
120: $logid++;
121: my $now = time();
122: my $id=$now.'00000'.$$.'00000'.$logid;
123: return &Apache::lonnet::put('nohist_'.$hash_name,
124: { $id => {
125: 'exe_uname' => $env{'user.name'},
126: 'exe_udom' => $env{'user.domain'},
127: 'exe_time' => $now,
128: 'exe_ip' => $ENV{'REMOTE_ADDR'},
129: 'delflag' => $delflag,
130: 'logentry' => $storehash,
131: 'uname' => $uname,
132: 'udom' => $udom,
133: }
134: },$cdom,$cnum);
135: }
136: }
137:
138: sub logtouch {
139: my $execdir=$perlvar{'lonDaemons'};
140: unless (-e "$execdir/logs/lonnet.log") {
141: open(my $fh,">>$execdir/logs/lonnet.log");
142: close $fh;
143: }
144: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
145: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
146: }
147:
148: sub logthis {
149: my $message=shift;
150: my $execdir=$perlvar{'lonDaemons'};
151: my $now=time;
152: my $local=localtime($now);
153: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
154: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
155: print $fh $logstring;
156: close($fh);
157: }
158: return 1;
159: }
160:
161: sub logperm {
162: my $message=shift;
163: my $execdir=$perlvar{'lonDaemons'};
164: my $now=time;
165: my $local=localtime($now);
166: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
167: print $fh "$now:$message:$local\n";
168: close($fh);
169: }
170: return 1;
171: }
172:
173: sub create_connection {
174: my ($hostname,$lonid) = @_;
175: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
176: Type => SOCK_STREAM,
177: Timeout => 10);
178: return 0 if (!$client);
179: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
180: my $result = <$client>;
181: chomp($result);
182: return 1 if ($result eq 'done');
183: return 0;
184: }
185:
186: sub get_server_timezone {
187: my ($cnum,$cdom) = @_;
188: my $home=&homeserver($cnum,$cdom);
189: if ($home ne 'no_host') {
190: my $cachetime = 24*3600;
191: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
192: if (defined($cached)) {
193: return $timezone;
194: } else {
195: my $timezone = &reply('servertimezone',$home);
196: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
197: }
198: }
199: }
200:
201: sub get_server_distarch {
202: my ($lonhost,$ignore_cache) = @_;
203: if (defined($lonhost)) {
204: if (!defined(&hostname($lonhost))) {
205: return;
206: }
207: my $cachetime = 12*3600;
208: if (!$ignore_cache) {
209: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
210: if (defined($cached)) {
211: return $distarch;
212: }
213: }
214: my $rep = &reply('serverdistarch',$lonhost);
215: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
216: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
217: $rep eq '') {
218: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
219: }
220: }
221: return;
222: }
223:
224: sub get_server_loncaparev {
225: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
226: if (defined($lonhost)) {
227: if (!defined(&hostname($lonhost))) {
228: undef($lonhost);
229: }
230: }
231: if (!defined($lonhost)) {
232: if (defined(&domain($dom,'primary'))) {
233: $lonhost=&domain($dom,'primary');
234: if ($lonhost eq 'no_host') {
235: undef($lonhost);
236: }
237: }
238: }
239: if (defined($lonhost)) {
240: my $cachetime = 12*3600;
241: if (!$ignore_cache) {
242: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
243: if (defined($cached)) {
244: return $loncaparev;
245: }
246: }
247: my ($answer,$loncaparev);
248: my @ids=¤t_machine_ids();
249: if (grep(/^\Q$lonhost\E$/,@ids)) {
250: $answer = $perlvar{'lonVersion'};
251: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
252: $loncaparev = $1;
253: }
254: } else {
255: $answer = &reply('serverloncaparev',$lonhost);
256: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
257: if ($caller eq 'loncron') {
258: my $ua=new LWP::UserAgent;
259: $ua->timeout(4);
260: my $protocol = $protocol{$lonhost};
261: $protocol = 'http' if ($protocol ne 'https');
262: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
263: my $request=new HTTP::Request('GET',$url);
264: my $response=$ua->request($request);
265: unless ($response->is_error()) {
266: my $content = $response->content;
267: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
268: $loncaparev = $1;
269: }
270: }
271: } else {
272: $loncaparev = $loncaparevs{$lonhost};
273: }
274: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
275: $loncaparev = $1;
276: }
277: }
278: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
279: }
280: }
281:
282: sub get_server_homeID {
283: my ($hostname,$ignore_cache,$caller) = @_;
284: unless ($ignore_cache) {
285: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
286: if (defined($cached)) {
287: return $serverhomeID;
288: }
289: }
290: my $cachetime = 12*3600;
291: my $serverhomeID;
292: if ($caller eq 'loncron') {
293: my @machine_ids = &machine_ids($hostname);
294: foreach my $id (@machine_ids) {
295: my $response = &reply('serverhomeID',$id);
296: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
297: $serverhomeID = $response;
298: last;
299: }
300: }
301: if ($serverhomeID eq '') {
302: $serverhomeID = $machine_ids[-1];
303: }
304: } else {
305: $serverhomeID = $serverhomeIDs{$hostname};
306: }
307: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
308: }
309:
310: sub get_remote_globals {
311: my ($lonhost,$whathash,$ignore_cache) = @_;
312: my ($result,%returnhash,%whatneeded);
313: if (ref($whathash) eq 'HASH') {
314: foreach my $what (sort(keys(%{$whathash}))) {
315: my $hashid = $lonhost.'-'.$what;
316: my ($response,$cached);
317: unless ($ignore_cache) {
318: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
319: }
320: if (defined($cached)) {
321: $returnhash{$what} = $response;
322: } else {
323: $whatneeded{$what} = 1;
324: }
325: }
326: if (keys(%whatneeded) == 0) {
327: $result = 'ok';
328: } else {
329: my $requested = &freeze_escape(\%whatneeded);
330: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
331: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
332: ($rep eq 'unknown_cmd')) {
333: $result = $rep;
334: } else {
335: $result = 'ok';
336: my @pairs=split(/\&/,$rep);
337: foreach my $item (@pairs) {
338: my ($key,$value)=split(/=/,$item,2);
339: my $what = &unescape($key);
340: my $hashid = $lonhost.'-'.$what;
341: $returnhash{$what}=&thaw_unescape($value);
342: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
343: }
344: }
345: }
346: }
347: return ($result,\%returnhash);
348: }
349:
350: sub remote_devalidate_cache {
351: my ($lonhost,$name,$id) = @_;
352: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
353: return $response;
354: }
355:
356: # -------------------------------------------------- Non-critical communication
357: sub subreply {
358: my ($cmd,$server)=@_;
359: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
360: #
361: # With loncnew process trimming, there's a timing hole between lonc server
362: # process exit and the master server picking up the listen on the AF_UNIX
363: # socket. In that time interval, a lock file will exist:
364:
365: my $lockfile=$peerfile.".lock";
366: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
367: sleep(1);
368: }
369: # At this point, either a loncnew parent is listening or an old lonc
370: # or loncnew child is listening so we can connect or everything's dead.
371: #
372: # We'll give the connection a few tries before abandoning it. If
373: # connection is not possible, we'll con_lost back to the client.
374: #
375: my $client;
376: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
377: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
378: Type => SOCK_STREAM,
379: Timeout => 10);
380: if ($client) {
381: last; # Connected!
382: } else {
383: &create_connection(&hostname($server),$server);
384: }
385: sleep(1); # Try again later if failed connection.
386: }
387: my $answer;
388: if ($client) {
389: print $client "sethost:$server:$cmd\n";
390: $answer=<$client>;
391: if (!$answer) { $answer="con_lost"; }
392: chomp($answer);
393: } else {
394: $answer = 'con_lost'; # Failed connection.
395: }
396: return $answer;
397: }
398:
399: sub reply {
400: my ($cmd,$server)=@_;
401: unless (defined(&hostname($server))) { return 'no_such_host'; }
402: my $answer=subreply($cmd,$server);
403: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
404: &logthis("<font color=\"blue\">WARNING:".
405: " $cmd to $server returned $answer</font>");
406: }
407: return $answer;
408: }
409:
410: # ----------------------------------------------------------- Send USR1 to lonc
411:
412: sub reconlonc {
413: my ($lonid) = @_;
414: my $hostname = &hostname($lonid);
415: if ($lonid) {
416: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
417: if ($hostname && -e $peerfile) {
418: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
419: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
420: Type => SOCK_STREAM,
421: Timeout => 10);
422: if ($client) {
423: print $client ("reset_retries\n");
424: my $answer=<$client>;
425: #reset just this one.
426: }
427: }
428: return;
429: }
430:
431: &logthis("Trying to reconnect lonc");
432: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
433: if (open(my $fh,"<$loncfile")) {
434: my $loncpid=<$fh>;
435: chomp($loncpid);
436: if (kill 0 => $loncpid) {
437: &logthis("lonc at pid $loncpid responding, sending USR1");
438: kill USR1 => $loncpid;
439: sleep 1;
440: } else {
441: &logthis(
442: "<font color=\"blue\">WARNING:".
443: " lonc at pid $loncpid not responding, giving up</font>");
444: }
445: } else {
446: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
447: }
448: }
449:
450: # ------------------------------------------------------ Critical communication
451:
452: sub critical {
453: my ($cmd,$server)=@_;
454: unless (&hostname($server)) {
455: &logthis("<font color=\"blue\">WARNING:".
456: " Critical message to unknown server ($server)</font>");
457: return 'no_such_host';
458: }
459: my $answer=reply($cmd,$server);
460: if ($answer eq 'con_lost') {
461: &reconlonc("$perlvar{'lonSockDir'}/$server");
462: my $answer=reply($cmd,$server);
463: if ($answer eq 'con_lost') {
464: my $now=time;
465: my $middlename=$cmd;
466: $middlename=substr($middlename,0,16);
467: $middlename=~s/\W//g;
468: my $dfilename=
469: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
470: $dumpcount++;
471: {
472: my $dfh;
473: if (open($dfh,">$dfilename")) {
474: print $dfh "$cmd\n";
475: close($dfh);
476: }
477: }
478: sleep 2;
479: my $wcmd='';
480: {
481: my $dfh;
482: if (open($dfh,"<$dfilename")) {
483: $wcmd=<$dfh>;
484: close($dfh);
485: }
486: }
487: chomp($wcmd);
488: if ($wcmd eq $cmd) {
489: &logthis("<font color=\"blue\">WARNING: ".
490: "Connection buffer $dfilename: $cmd</font>");
491: &logperm("D:$server:$cmd");
492: return 'con_delayed';
493: } else {
494: &logthis("<font color=\"red\">CRITICAL:"
495: ." Critical connection failed: $server $cmd</font>");
496: &logperm("F:$server:$cmd");
497: return 'con_failed';
498: }
499: }
500: }
501: return $answer;
502: }
503:
504: # ------------------------------------------- check if return value is an error
505:
506: sub error {
507: my ($result) = @_;
508: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
509: if ($2 == 2) { return undef; }
510: return $1;
511: }
512: return undef;
513: }
514:
515: sub convert_and_load_session_env {
516: my ($lonidsdir,$handle)=@_;
517: my @profile;
518: {
519: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
520: if (!$opened) {
521: return 0;
522: }
523: flock($idf,LOCK_SH);
524: @profile=<$idf>;
525: close($idf);
526: }
527: my %temp_env;
528: foreach my $line (@profile) {
529: if ($line !~ m/=/) {
530: return 0;
531: }
532: chomp($line);
533: my ($envname,$envvalue)=split(/=/,$line,2);
534: $temp_env{&unescape($envname)} = &unescape($envvalue);
535: }
536: unlink("$lonidsdir/$handle.id");
537: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
538: 0640)) {
539: %disk_env = %temp_env;
540: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
541: untie(%disk_env);
542: }
543: return 1;
544: }
545:
546: # ------------------------------------------- Transfer profile into environment
547: my $env_loaded;
548: sub transfer_profile_to_env {
549: my ($lonidsdir,$handle,$force_transfer) = @_;
550: if (!$force_transfer && $env_loaded) { return; }
551:
552: if (!defined($lonidsdir)) {
553: $lonidsdir = $perlvar{'lonIDsDir'};
554: }
555: if (!defined($handle)) {
556: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
557: }
558:
559: my $convert;
560: {
561: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
562: if (!$opened) {
563: return;
564: }
565: flock($idf,LOCK_SH);
566: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
567: &GDBM_READER(),0640)) {
568: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
569: untie(%disk_env);
570: } else {
571: $convert = 1;
572: }
573: }
574: if ($convert) {
575: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
576: &logthis("Failed to load session, or convert session.");
577: }
578: }
579:
580: my %remove;
581: while ( my $envname = each(%env) ) {
582: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
583: if ($time < time-300) {
584: $remove{$key}++;
585: }
586: }
587: }
588:
589: $env{'user.environment'} = "$lonidsdir/$handle.id";
590: $env_loaded=1;
591: foreach my $expired_key (keys(%remove)) {
592: &delenv($expired_key);
593: }
594: }
595:
596: # ---------------------------------------------------- Check for valid session
597: sub check_for_valid_session {
598: my ($r) = @_;
599: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
600: my $lonid=$cookies{'lonID'};
601: return undef if (!$lonid);
602:
603: my $handle=&LONCAPA::clean_handle($lonid->value);
604: my $lonidsdir=$r->dir_config('lonIDsDir');
605: return undef if (!-e "$lonidsdir/$handle.id");
606:
607: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
608: return undef if (!$opened);
609:
610: flock($idf,LOCK_SH);
611: my %disk_env;
612: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
613: &GDBM_READER(),0640)) {
614: return undef;
615: }
616:
617: if (!defined($disk_env{'user.name'})
618: || !defined($disk_env{'user.domain'})) {
619: return undef;
620: }
621: return $handle;
622: }
623:
624: sub timed_flock {
625: my ($file,$lock_type) = @_;
626: my $failed=0;
627: eval {
628: local $SIG{__DIE__}='DEFAULT';
629: local $SIG{ALRM}=sub {
630: $failed=1;
631: die("failed lock");
632: };
633: alarm(13);
634: flock($file,$lock_type);
635: alarm(0);
636: };
637: if ($failed) {
638: return undef;
639: } else {
640: return 1;
641: }
642: }
643:
644: # ---------------------------------------------------------- Append Environment
645:
646: sub appenv {
647: my ($newenv,$roles) = @_;
648: if (ref($newenv) eq 'HASH') {
649: foreach my $key (keys(%{$newenv})) {
650: my $refused = 0;
651: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
652: $refused = 1;
653: if (ref($roles) eq 'ARRAY') {
654: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
655: if (grep(/^\Q$role\E$/,@{$roles})) {
656: $refused = 0;
657: }
658: }
659: }
660: if ($refused) {
661: &logthis("<font color=\"blue\">WARNING: ".
662: "Attempt to modify environment ".$key." to ".$newenv->{$key}
663: .'</font>');
664: delete($newenv->{$key});
665: } else {
666: $env{$key}=$newenv->{$key};
667: }
668: }
669: my $opened = open(my $env_file,'+<',$env{'user.environment'});
670: if ($opened
671: && &timed_flock($env_file,LOCK_EX)
672: &&
673: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
674: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
675: while (my ($key,$value) = each(%{$newenv})) {
676: $disk_env{$key} = $value;
677: }
678: untie(%disk_env);
679: }
680: }
681: return 'ok';
682: }
683: # ----------------------------------------------------- Delete from Environment
684:
685: sub delenv {
686: my ($delthis,$regexp,$roles) = @_;
687: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
688: my $refused = 1;
689: if (ref($roles) eq 'ARRAY') {
690: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
691: if (grep(/^\Q$role\E$/,@{$roles})) {
692: $refused = 0;
693: }
694: }
695: if ($refused) {
696: &logthis("<font color=\"blue\">WARNING: ".
697: "Attempt to delete from environment ".$delthis);
698: return 'error';
699: }
700: }
701: my $opened = open(my $env_file,'+<',$env{'user.environment'});
702: if ($opened
703: && &timed_flock($env_file,LOCK_EX)
704: &&
705: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
706: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
707: foreach my $key (keys(%disk_env)) {
708: if ($regexp) {
709: if ($key=~/^$delthis/) {
710: delete($env{$key});
711: delete($disk_env{$key});
712: }
713: } else {
714: if ($key=~/^\Q$delthis\E/) {
715: delete($env{$key});
716: delete($disk_env{$key});
717: }
718: }
719: }
720: untie(%disk_env);
721: }
722: return 'ok';
723: }
724:
725: sub get_env_multiple {
726: my ($name) = @_;
727: my @values;
728: if (defined($env{$name})) {
729: # exists is it an array
730: if (ref($env{$name})) {
731: @values=@{ $env{$name} };
732: } else {
733: $values[0]=$env{$name};
734: }
735: }
736: return(@values);
737: }
738:
739: # ------------------------------------------------------------------- Locking
740:
741: sub set_lock {
742: my ($text)=@_;
743: $locknum++;
744: my $id=$$.'-'.$locknum;
745: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
746: 'session.lock.'.$id => $text});
747: return $id;
748: }
749:
750: sub get_locks {
751: my $num=0;
752: my %texts=();
753: foreach my $lock (split(/\,/,$env{'session.locks'})) {
754: if ($lock=~/\w/) {
755: $num++;
756: $texts{$lock}=$env{'session.lock.'.$lock};
757: }
758: }
759: return ($num,%texts);
760: }
761:
762: sub remove_lock {
763: my ($id)=@_;
764: my $newlocks='';
765: foreach my $lock (split(/\,/,$env{'session.locks'})) {
766: if (($lock=~/\w/) && ($lock ne $id)) {
767: $newlocks.=','.$lock;
768: }
769: }
770: &appenv({'session.locks' => $newlocks});
771: &delenv('session.lock.'.$id);
772: }
773:
774: sub remove_all_locks {
775: my $activelocks=$env{'session.locks'};
776: foreach my $lock (split(/\,/,$env{'session.locks'})) {
777: if ($lock=~/\w/) {
778: &remove_lock($lock);
779: }
780: }
781: }
782:
783:
784: # ------------------------------------------ Find out current server userload
785: sub userload {
786: my $numusers=0;
787: {
788: opendir(LONIDS,$perlvar{'lonIDsDir'});
789: my $filename;
790: my $curtime=time;
791: while ($filename=readdir(LONIDS)) {
792: next if ($filename eq '.' || $filename eq '..');
793: next if ($filename =~ /publicuser_\d+\.id/);
794: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
795: if ($curtime-$mtime < 1800) { $numusers++; }
796: }
797: closedir(LONIDS);
798: }
799: my $userloadpercent=0;
800: my $maxuserload=$perlvar{'lonUserLoadLim'};
801: if ($maxuserload) {
802: $userloadpercent=100*$numusers/$maxuserload;
803: }
804: $userloadpercent=sprintf("%.2f",$userloadpercent);
805: return $userloadpercent;
806: }
807:
808: # ------------------------------ Find server with least workload from spare.tab
809:
810: sub spareserver {
811: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
812: my $spare_server;
813: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
814: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
815: : $userloadpercent;
816: my ($uint_dom,$remotesessions);
817: if (($udom ne '') && (&domain($udom) ne '')) {
818: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
819: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
820: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
821: $remotesessions = $udomdefaults{'remotesessions'};
822: }
823: my $spareshash = &this_host_spares($udom);
824: if (ref($spareshash) eq 'HASH') {
825: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
826: foreach my $try_server (@{ $spareshash->{'primary'} }) {
827: if ($uint_dom) {
828: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
829: $try_server));
830: }
831: ($spare_server, $lowest_load) =
832: &compare_server_load($try_server, $spare_server, $lowest_load);
833: }
834: }
835:
836: my $found_server = ($spare_server ne '' && $lowest_load < 100);
837:
838: if (!$found_server) {
839: if (ref($spareshash->{'default'}) eq 'ARRAY') {
840: foreach my $try_server (@{ $spareshash->{'default'} }) {
841: if ($uint_dom) {
842: next unless (&spare_can_host($udom,$uint_dom,
843: $remotesessions,$try_server));
844: }
845: ($spare_server, $lowest_load) =
846: &compare_server_load($try_server, $spare_server, $lowest_load);
847: }
848: }
849: }
850: }
851:
852: if (!$want_server_name) {
853: my $protocol = 'http';
854: if ($protocol{$spare_server} eq 'https') {
855: $protocol = $protocol{$spare_server};
856: }
857: if (defined($spare_server)) {
858: my $hostname = &hostname($spare_server);
859: if (defined($hostname)) {
860: $spare_server = $protocol.'://'.$hostname;
861: }
862: }
863: }
864: return $spare_server;
865: }
866:
867: sub compare_server_load {
868: my ($try_server, $spare_server, $lowest_load) = @_;
869:
870: my $loadans = &reply('load', $try_server);
871: my $userloadans = &reply('userload',$try_server);
872:
873: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
874: return ($spare_server, $lowest_load); #didn't get a number from the server
875: }
876:
877: my $load;
878: if ($loadans =~ /\d/) {
879: if ($userloadans =~ /\d/) {
880: #both are numbers, pick the bigger one
881: $load = ($loadans > $userloadans) ? $loadans
882: : $userloadans;
883: } else {
884: $load = $loadans;
885: }
886: } else {
887: $load = $userloadans;
888: }
889:
890: if (($load =~ /\d/) && ($load < $lowest_load)) {
891: $spare_server = $try_server;
892: $lowest_load = $load;
893: }
894: return ($spare_server,$lowest_load);
895: }
896:
897: # --------------------------- ask offload servers if user already has a session
898: sub find_existing_session {
899: my ($udom,$uname) = @_;
900: my $spareshash = &this_host_spares($udom);
901: if (ref($spareshash) eq 'HASH') {
902: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
903: foreach my $try_server (@{ $spareshash->{'primary'} }) {
904: return $try_server if (&has_user_session($try_server, $udom, $uname));
905: }
906: }
907: if (ref($spareshash->{'default'}) eq 'ARRAY') {
908: foreach my $try_server (@{ $spareshash->{'default'} }) {
909: return $try_server if (&has_user_session($try_server, $udom, $uname));
910: }
911: }
912: }
913: return;
914: }
915:
916: # -------------------------------- ask if server already has a session for user
917: sub has_user_session {
918: my ($lonid,$udom,$uname) = @_;
919: my $result = &reply(join(':','userhassession',
920: map {&escape($_)} ($udom,$uname)),$lonid);
921: return 1 if ($result eq 'ok');
922:
923: return 0;
924: }
925:
926: # --------- determine least loaded server in a user's domain which allows login
927:
928: sub choose_server {
929: my ($udom,$checkloginvia) = @_;
930: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
931: my %servers = &get_servers($udom);
932: my $lowest_load = 30000;
933: my ($login_host,$hostname,$portal_path);
934: foreach my $lonhost (keys(%servers)) {
935: my $loginvia;
936: if ($checkloginvia) {
937: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
938: if ($loginvia) {
939: my ($server,$path) = split(/:/,$loginvia);
940: ($login_host, $lowest_load) =
941: &compare_server_load($server, $login_host, $lowest_load);
942: if ($login_host eq $server) {
943: $portal_path = $path;
944: }
945: } else {
946: ($login_host, $lowest_load) =
947: &compare_server_load($lonhost, $login_host, $lowest_load);
948: if ($login_host eq $lonhost) {
949: $portal_path = '';
950: }
951: }
952: } else {
953: ($login_host, $lowest_load) =
954: &compare_server_load($lonhost, $login_host, $lowest_load);
955: }
956: }
957: if ($login_host ne '') {
958: $hostname = &hostname($login_host);
959: }
960: return ($login_host,$hostname,$portal_path);
961: }
962:
963: # --------------------------------------------- Try to change a user's password
964:
965: sub changepass {
966: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
967: $currentpass = &escape($currentpass);
968: $newpass = &escape($newpass);
969: my $lonhost = $perlvar{'lonHostID'};
970: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
971: $server);
972: if (! $answer) {
973: &logthis("No reply on password change request to $server ".
974: "by $uname in domain $udom.");
975: } elsif ($answer =~ "^ok") {
976: &logthis("$uname in $udom successfully changed their password ".
977: "on $server.");
978: } elsif ($answer =~ "^pwchange_failure") {
979: &logthis("$uname in $udom was unable to change their password ".
980: "on $server. The action was blocked by either lcpasswd ".
981: "or pwchange");
982: } elsif ($answer =~ "^non_authorized") {
983: &logthis("$uname in $udom did not get their password correct when ".
984: "attempting to change it on $server.");
985: } elsif ($answer =~ "^auth_mode_error") {
986: &logthis("$uname in $udom attempted to change their password despite ".
987: "not being locally or internally authenticated on $server.");
988: } elsif ($answer =~ "^unknown_user") {
989: &logthis("$uname in $udom attempted to change their password ".
990: "on $server but were unable to because $server is not ".
991: "their home server.");
992: } elsif ($answer =~ "^refused") {
993: &logthis("$server refused to change $uname in $udom password because ".
994: "it was sent an unencrypted request to change the password.");
995: } elsif ($answer =~ "invalid_client") {
996: &logthis("$server refused to change $uname in $udom password because ".
997: "it was a reset by e-mail originating from an invalid server.");
998: }
999: return $answer;
1000: }
1001:
1002: # ----------------------- Try to determine user's current authentication scheme
1003:
1004: sub queryauthenticate {
1005: my ($uname,$udom)=@_;
1006: my $uhome=&homeserver($uname,$udom);
1007: if (!$uhome) {
1008: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1009: return 'no_host';
1010: }
1011: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1012: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1013: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1014: }
1015: return $answer;
1016: }
1017:
1018: # --------- Try to authenticate user from domain's lib servers (first this one)
1019:
1020: sub authenticate {
1021: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1022: $upass=&escape($upass);
1023: $uname= &LONCAPA::clean_username($uname);
1024: my $uhome=&homeserver($uname,$udom,1);
1025: my $newhome;
1026: if ((!$uhome) || ($uhome eq 'no_host')) {
1027: # Maybe the machine was offline and only re-appeared again recently?
1028: &reconlonc();
1029: # One more
1030: $uhome=&homeserver($uname,$udom,1);
1031: if (($uhome eq 'no_host') && $checkdefauth) {
1032: if (defined(&domain($udom,'primary'))) {
1033: $newhome=&domain($udom,'primary');
1034: }
1035: if ($newhome ne '') {
1036: $uhome = $newhome;
1037: }
1038: }
1039: if ((!$uhome) || ($uhome eq 'no_host')) {
1040: &logthis("User $uname at $udom is unknown in authenticate");
1041: return 'no_host';
1042: }
1043: }
1044: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1045: if ($answer eq 'authorized') {
1046: if ($newhome) {
1047: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1048: return 'no_account_on_host';
1049: } else {
1050: &logthis("User $uname at $udom authorized by $uhome");
1051: return $uhome;
1052: }
1053: }
1054: if ($answer eq 'non_authorized') {
1055: &logthis("User $uname at $udom rejected by $uhome");
1056: return 'no_host';
1057: }
1058: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1059: return 'no_host';
1060: }
1061:
1062: sub can_host_session {
1063: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1064: my $canhost = 1;
1065: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1066: if (ref($remotesessions) eq 'HASH') {
1067: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1068: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1069: $canhost = 0;
1070: } else {
1071: $canhost = 1;
1072: }
1073: }
1074: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1075: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1076: $canhost = 1;
1077: } else {
1078: $canhost = 0;
1079: }
1080: }
1081: if ($canhost) {
1082: if ($remotesessions->{'version'} ne '') {
1083: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1084: if ($reqmajor ne '' && $reqminor ne '') {
1085: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1086: my $major = $1;
1087: my $minor = $2;
1088: if (($major < $reqmajor ) ||
1089: (($major == $reqmajor) && ($minor < $reqminor))) {
1090: $canhost = 0;
1091: }
1092: } else {
1093: $canhost = 0;
1094: }
1095: }
1096: }
1097: }
1098: }
1099: if ($canhost) {
1100: if (ref($hostedsessions) eq 'HASH') {
1101: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1102: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1103: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1104: if (($uint_dom ne '') &&
1105: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1106: $canhost = 0;
1107: } else {
1108: $canhost = 1;
1109: }
1110: }
1111: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1112: if (($uint_dom ne '') &&
1113: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1114: $canhost = 1;
1115: } else {
1116: $canhost = 0;
1117: }
1118: }
1119: }
1120: }
1121: return $canhost;
1122: }
1123:
1124: sub spare_can_host {
1125: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1126: my $canhost=1;
1127: my @intdoms;
1128: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1129: if (ref($internet_names) eq 'ARRAY') {
1130: @intdoms = @{$internet_names};
1131: }
1132: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1133: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1134: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1135: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1136: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1137: $canhost = &can_host_session($udom,$try_server,$remoterev,
1138: $remotesessions,
1139: $defdomdefaults{'hostedsessions'});
1140: }
1141: return $canhost;
1142: }
1143:
1144: sub this_host_spares {
1145: my ($dom) = @_;
1146: my ($dom_in_use,$lonhost_in_use,$result);
1147: my @hosts = ¤t_machine_ids();
1148: foreach my $lonhost (@hosts) {
1149: if (&host_domain($lonhost) eq $dom) {
1150: $dom_in_use = $dom;
1151: $lonhost_in_use = $lonhost;
1152: last;
1153: }
1154: }
1155: if ($dom_in_use ne '') {
1156: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1157: }
1158: if (ref($result) ne 'HASH') {
1159: $lonhost_in_use = $perlvar{'lonHostID'};
1160: $dom_in_use = &host_domain($lonhost_in_use);
1161: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1162: if (ref($result) ne 'HASH') {
1163: $result = \%spareid;
1164: }
1165: }
1166: return $result;
1167: }
1168:
1169: sub spares_for_offload {
1170: my ($dom_in_use,$lonhost_in_use) = @_;
1171: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1172: if (defined($cached)) {
1173: return $result;
1174: } else {
1175: my $cachetime = 60*60*24;
1176: my %domconfig =
1177: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1178: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1179: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1180: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1181: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1182: }
1183: }
1184: }
1185: }
1186: return;
1187: }
1188:
1189: sub get_lonbalancer_config {
1190: my ($servers) = @_;
1191: my ($currbalancer,$currtargets);
1192: if (ref($servers) eq 'HASH') {
1193: foreach my $server (keys(%{$servers})) {
1194: my %what = (
1195: spareid => 1,
1196: perlvar => 1,
1197: );
1198: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1199: if ($result eq 'ok') {
1200: if (ref($returnhash) eq 'HASH') {
1201: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1202: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1203: $currbalancer = $server;
1204: $currtargets = {};
1205: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1206: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1207: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1208: }
1209: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1210: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1211: }
1212: }
1213: last;
1214: }
1215: }
1216: }
1217: }
1218: }
1219: }
1220: return ($currbalancer,$currtargets);
1221: }
1222:
1223: sub check_loadbalancing {
1224: my ($uname,$udom) = @_;
1225: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1226: $offloadto,$otherserver);
1227: my $lonhost = $perlvar{'lonHostID'};
1228: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1229: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1230: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1231: my $serverhomedom = &host_domain($lonhost);
1232:
1233: my $cachetime = 60*60*24;
1234:
1235: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1236: $dom_in_use = $udom;
1237: $homeintdom = 1;
1238: } else {
1239: $dom_in_use = $serverhomedom;
1240: }
1241: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1242: unless (defined($cached)) {
1243: my %domconfig =
1244: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1245: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1246: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1247: }
1248: }
1249: if (ref($result) eq 'HASH') {
1250: my $currbalancer = $result->{'lonhost'};
1251: my $currtargets = $result->{'targets'};
1252: my $currrules = $result->{'rules'};
1253: if ($currbalancer ne '') {
1254: my @hosts = ¤t_machine_ids();
1255: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1256: $is_balancer = 1;
1257: }
1258: }
1259: if ($is_balancer) {
1260: if (ref($currrules) eq 'HASH') {
1261: if ($homeintdom) {
1262: if ($uname ne '') {
1263: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1264: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1265: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1266: $rule_in_effect = $currrules->{'_LC_author'};
1267: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1268: $rule_in_effect = $currrules->{'_LC_adv'}
1269: }
1270: }
1271: if ($rule_in_effect eq '') {
1272: my %userenv = &userenvironment($udom,$uname,'inststatus');
1273: if ($userenv{'inststatus'} ne '') {
1274: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1275: my ($othertitle,$usertypes,$types) =
1276: &Apache::loncommon::sorted_inst_types($udom);
1277: if (ref($types) eq 'ARRAY') {
1278: foreach my $type (@{$types}) {
1279: if (grep(/^\Q$type\E$/,@statuses)) {
1280: if (exists($currrules->{$type})) {
1281: $rule_in_effect = $currrules->{$type};
1282: }
1283: }
1284: }
1285: }
1286: } else {
1287: if (exists($currrules->{'default'})) {
1288: $rule_in_effect = $currrules->{'default'};
1289: }
1290: }
1291: }
1292: } else {
1293: if (exists($currrules->{'default'})) {
1294: $rule_in_effect = $currrules->{'default'};
1295: }
1296: }
1297: } else {
1298: if ($currrules->{'_LC_external'} ne '') {
1299: $rule_in_effect = $currrules->{'_LC_external'};
1300: }
1301: }
1302: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1303: $uname,$udom);
1304: }
1305: }
1306: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1307: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1308: unless (defined($cached)) {
1309: my %domconfig =
1310: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1311: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1312: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1313: }
1314: }
1315: if (ref($result) eq 'HASH') {
1316: my $currbalancer = $result->{'lonhost'};
1317: my $currtargets = $result->{'targets'};
1318: my $currrules = $result->{'rules'};
1319:
1320: if ($currbalancer eq $lonhost) {
1321: $is_balancer = 1;
1322: if (ref($currrules) eq 'HASH') {
1323: if ($currrules->{'_LC_internetdom'} ne '') {
1324: $rule_in_effect = $currrules->{'_LC_internetdom'};
1325: }
1326: }
1327: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1328: $uname,$udom);
1329: }
1330: } else {
1331: if ($perlvar{'lonBalancer'} eq 'yes') {
1332: $is_balancer = 1;
1333: $offloadto = &this_host_spares($dom_in_use);
1334: }
1335: }
1336: } else {
1337: if ($perlvar{'lonBalancer'} eq 'yes') {
1338: $is_balancer = 1;
1339: $offloadto = &this_host_spares($dom_in_use);
1340: }
1341: }
1342: my $lowest_load = 30000;
1343: if (ref($offloadto) eq 'HASH') {
1344: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1345: foreach my $try_server (@{$offloadto->{'primary'}}) {
1346: ($otherserver,$lowest_load) =
1347: &compare_server_load($try_server,$otherserver,$lowest_load);
1348: }
1349: }
1350: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1351:
1352: if (!$found_server) {
1353: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1354: foreach my $try_server (@{$offloadto->{'default'}}) {
1355: ($otherserver,$lowest_load) =
1356: &compare_server_load($try_server,$otherserver,$lowest_load);
1357: }
1358: }
1359: }
1360: } elsif (ref($offloadto) eq 'ARRAY') {
1361: if (@{$offloadto} == 1) {
1362: $otherserver = $offloadto->[0];
1363: } elsif (@{$offloadto} > 1) {
1364: foreach my $try_server (@{$offloadto}) {
1365: ($otherserver,$lowest_load) =
1366: &compare_server_load($try_server,$otherserver,$lowest_load);
1367: }
1368: }
1369: }
1370: return ($is_balancer,$otherserver);
1371: }
1372:
1373: sub get_loadbalancer_targets {
1374: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1375: my $offloadto;
1376: if ($rule_in_effect eq '') {
1377: $offloadto = $currtargets;
1378: } else {
1379: if ($rule_in_effect eq 'homeserver') {
1380: my $homeserver = &homeserver($uname,$udom);
1381: if ($homeserver ne 'no_host') {
1382: $offloadto = [$homeserver];
1383: }
1384: } elsif ($rule_in_effect eq 'externalbalancer') {
1385: my %domconfig =
1386: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1387: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1388: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1389: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1390: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1391: }
1392: }
1393: } else {
1394: my %servers = &dom_servers($udom);
1395: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1396: if (&hostname($remotebalancer) ne '') {
1397: $offloadto = [$remotebalancer];
1398: }
1399: }
1400: } elsif (&hostname($rule_in_effect) ne '') {
1401: $offloadto = [$rule_in_effect];
1402: }
1403: }
1404: return $offloadto;
1405: }
1406:
1407: sub internet_dom_servers {
1408: my ($dom) = @_;
1409: my (%uniqservers,%servers);
1410: my $primaryserver = &hostname(&domain($dom,'primary'));
1411: my @machinedoms = &machine_domains($primaryserver);
1412: foreach my $mdom (@machinedoms) {
1413: my %currservers = %servers;
1414: my %server = &get_servers($mdom);
1415: %servers = (%currservers,%server);
1416: }
1417: my %by_hostname;
1418: foreach my $id (keys(%servers)) {
1419: push(@{$by_hostname{$servers{$id}}},$id);
1420: }
1421: foreach my $hostname (sort(keys(%by_hostname))) {
1422: if (@{$by_hostname{$hostname}} > 1) {
1423: my $match = 0;
1424: foreach my $id (@{$by_hostname{$hostname}}) {
1425: if (&host_domain($id) eq $dom) {
1426: $uniqservers{$id} = $hostname;
1427: $match = 1;
1428: }
1429: }
1430: unless ($match) {
1431: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1432: }
1433: } else {
1434: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1435: }
1436: }
1437: return %uniqservers;
1438: }
1439:
1440: # ---------------------- Find the homebase for a user from domain's lib servers
1441:
1442: my %homecache;
1443: sub homeserver {
1444: my ($uname,$udom,$ignoreBadCache)=@_;
1445: my $index="$uname:$udom";
1446:
1447: if (exists($homecache{$index})) { return $homecache{$index}; }
1448:
1449: my %servers = &get_servers($udom,'library');
1450: foreach my $tryserver (keys(%servers)) {
1451: next if ($ignoreBadCache ne 'true' &&
1452: exists($badServerCache{$tryserver}));
1453:
1454: my $answer=reply("home:$udom:$uname",$tryserver);
1455: if ($answer eq 'found') {
1456: delete($badServerCache{$tryserver});
1457: return $homecache{$index}=$tryserver;
1458: } elsif ($answer eq 'no_host') {
1459: $badServerCache{$tryserver}=1;
1460: }
1461: }
1462: return 'no_host';
1463: }
1464:
1465: # ------------------------------------- Find the usernames behind a list of IDs
1466:
1467: sub idget {
1468: my ($udom,@ids)=@_;
1469: my %returnhash=();
1470:
1471: my %servers = &get_servers($udom,'library');
1472: foreach my $tryserver (keys(%servers)) {
1473: my $idlist=join('&',@ids);
1474: $idlist=~tr/A-Z/a-z/;
1475: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1476: my @answer=();
1477: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1478: @answer=split(/\&/,$reply);
1479: } ;
1480: my $i;
1481: for ($i=0;$i<=$#ids;$i++) {
1482: if ($answer[$i]) {
1483: $returnhash{$ids[$i]}=$answer[$i];
1484: }
1485: }
1486: }
1487: return %returnhash;
1488: }
1489:
1490: # ------------------------------------- Find the IDs behind a list of usernames
1491:
1492: sub idrget {
1493: my ($udom,@unames)=@_;
1494: my %returnhash=();
1495: foreach my $uname (@unames) {
1496: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1497: }
1498: return %returnhash;
1499: }
1500:
1501: # ------------------------------- Store away a list of names and associated IDs
1502:
1503: sub idput {
1504: my ($udom,%ids)=@_;
1505: my %servers=();
1506: foreach my $uname (keys(%ids)) {
1507: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1508: my $uhom=&homeserver($uname,$udom);
1509: if ($uhom ne 'no_host') {
1510: my $id=&escape($ids{$uname});
1511: $id=~tr/A-Z/a-z/;
1512: my $esc_unam=&escape($uname);
1513: if ($servers{$uhom}) {
1514: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1515: } else {
1516: $servers{$uhom}=$id.'='.$esc_unam;
1517: }
1518: }
1519: }
1520: foreach my $server (keys(%servers)) {
1521: &critical('idput:'.$udom.':'.$servers{$server},$server);
1522: }
1523: }
1524:
1525: # ------------------------------dump from db file owned by domainconfig user
1526: sub dump_dom {
1527: my ($namespace,$udom,$regexp,$range)=@_;
1528: if (!$udom) {
1529: $udom=$env{'user.domain'};
1530: }
1531: my %returnhash;
1532: if ($udom) {
1533: my $uname = &get_domainconfiguser($udom);
1534: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1535: }
1536: return %returnhash;
1537: }
1538:
1539: # ------------------------------------------ get items from domain db files
1540:
1541: sub get_dom {
1542: my ($namespace,$storearr,$udom,$uhome)=@_;
1543: my $items='';
1544: foreach my $item (@$storearr) {
1545: $items.=&escape($item).'&';
1546: }
1547: $items=~s/\&$//;
1548: if (!$udom) {
1549: $udom=$env{'user.domain'};
1550: if (defined(&domain($udom,'primary'))) {
1551: $uhome=&domain($udom,'primary');
1552: } else {
1553: undef($uhome);
1554: }
1555: } else {
1556: if (!$uhome) {
1557: if (defined(&domain($udom,'primary'))) {
1558: $uhome=&domain($udom,'primary');
1559: }
1560: }
1561: }
1562: if ($udom && $uhome && ($uhome ne 'no_host')) {
1563: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1564: my %returnhash;
1565: if ($rep eq '' || $rep =~ /^error: 2 /) {
1566: return %returnhash;
1567: }
1568: my @pairs=split(/\&/,$rep);
1569: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1570: return @pairs;
1571: }
1572: my $i=0;
1573: foreach my $item (@$storearr) {
1574: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1575: $i++;
1576: }
1577: return %returnhash;
1578: } else {
1579: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1580: }
1581: }
1582:
1583: # -------------------------------------------- put items in domain db files
1584:
1585: sub put_dom {
1586: my ($namespace,$storehash,$udom,$uhome)=@_;
1587: if (!$udom) {
1588: $udom=$env{'user.domain'};
1589: if (defined(&domain($udom,'primary'))) {
1590: $uhome=&domain($udom,'primary');
1591: } else {
1592: undef($uhome);
1593: }
1594: } else {
1595: if (!$uhome) {
1596: if (defined(&domain($udom,'primary'))) {
1597: $uhome=&domain($udom,'primary');
1598: }
1599: }
1600: }
1601: if ($udom && $uhome && ($uhome ne 'no_host')) {
1602: my $items='';
1603: foreach my $item (keys(%$storehash)) {
1604: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1605: }
1606: $items=~s/\&$//;
1607: return &reply("putdom:$udom:$namespace:$items",$uhome);
1608: } else {
1609: &logthis("put_dom failed - no homeserver and/or domain");
1610: }
1611: }
1612:
1613: # --------------------- newput for items in db file owned by domainconfig user
1614: sub newput_dom {
1615: my ($namespace,$storehash,$udom) = @_;
1616: my $result;
1617: if (!$udom) {
1618: $udom=$env{'user.domain'};
1619: }
1620: if ($udom) {
1621: my $uname = &get_domainconfiguser($udom);
1622: $result = &newput($namespace,$storehash,$udom,$uname);
1623: }
1624: return $result;
1625: }
1626:
1627: # --------------------- delete for items in db file owned by domainconfig user
1628: sub del_dom {
1629: my ($namespace,$storearr,$udom)=@_;
1630: if (ref($storearr) eq 'ARRAY') {
1631: if (!$udom) {
1632: $udom=$env{'user.domain'};
1633: }
1634: if ($udom) {
1635: my $uname = &get_domainconfiguser($udom);
1636: return &del($namespace,$storearr,$udom,$uname);
1637: }
1638: }
1639: }
1640:
1641: # ----------------------------------construct domainconfig user for a domain
1642: sub get_domainconfiguser {
1643: my ($udom) = @_;
1644: return $udom.'-domainconfig';
1645: }
1646:
1647: sub retrieve_inst_usertypes {
1648: my ($udom) = @_;
1649: my (%returnhash,@order);
1650: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1651: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1652: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1653: %returnhash = %{$domdefs{'inststatustypes'}};
1654: @order = @{$domdefs{'inststatusorder'}};
1655: } else {
1656: if (defined(&domain($udom,'primary'))) {
1657: my $uhome=&domain($udom,'primary');
1658: my $rep=&reply("inst_usertypes:$udom",$uhome);
1659: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1660: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1661: return (\%returnhash,\@order);
1662: }
1663: my ($hashitems,$orderitems) = split(/:/,$rep);
1664: my @pairs=split(/\&/,$hashitems);
1665: foreach my $item (@pairs) {
1666: my ($key,$value)=split(/=/,$item,2);
1667: $key = &unescape($key);
1668: next if ($key =~ /^error: 2 /);
1669: $returnhash{$key}=&thaw_unescape($value);
1670: }
1671: my @esc_order = split(/\&/,$orderitems);
1672: foreach my $item (@esc_order) {
1673: push(@order,&unescape($item));
1674: }
1675: } else {
1676: &logthis("get_dom failed - no primary domain server for $udom");
1677: }
1678: }
1679: return (\%returnhash,\@order);
1680: }
1681:
1682: sub is_domainimage {
1683: my ($url) = @_;
1684: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1685: if (&domain($1) ne '') {
1686: return '1';
1687: }
1688: }
1689: return;
1690: }
1691:
1692: sub inst_directory_query {
1693: my ($srch) = @_;
1694: my $udom = $srch->{'srchdomain'};
1695: my %results;
1696: my $homeserver = &domain($udom,'primary');
1697: my $outcome;
1698: if ($homeserver ne '') {
1699: my $queryid=&reply("querysend:instdirsearch:".
1700: &escape($srch->{'srchby'}).':'.
1701: &escape($srch->{'srchterm'}).':'.
1702: &escape($srch->{'srchtype'}),$homeserver);
1703: my $host=&hostname($homeserver);
1704: if ($queryid !~/^\Q$host\E\_/) {
1705: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1706: return;
1707: }
1708: my $response = &get_query_reply($queryid);
1709: my $maxtries = 5;
1710: my $tries = 1;
1711: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1712: $response = &get_query_reply($queryid);
1713: $tries ++;
1714: }
1715:
1716: if (!&error($response) && $response ne 'refused') {
1717: if ($response eq 'unavailable') {
1718: $outcome = $response;
1719: } else {
1720: $outcome = 'ok';
1721: my @matches = split(/\n/,$response);
1722: foreach my $match (@matches) {
1723: my ($key,$value) = split(/=/,$match);
1724: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1725: }
1726: }
1727: }
1728: }
1729: return ($outcome,%results);
1730: }
1731:
1732: sub usersearch {
1733: my ($srch) = @_;
1734: my $dom = $srch->{'srchdomain'};
1735: my %results;
1736: my %libserv = &all_library();
1737: my $query = 'usersearch';
1738: foreach my $tryserver (keys(%libserv)) {
1739: if (&host_domain($tryserver) eq $dom) {
1740: my $host=&hostname($tryserver);
1741: my $queryid=
1742: &reply("querysend:".&escape($query).':'.
1743: &escape($srch->{'srchby'}).':'.
1744: &escape($srch->{'srchtype'}).':'.
1745: &escape($srch->{'srchterm'}),$tryserver);
1746: if ($queryid !~/^\Q$host\E\_/) {
1747: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1748: next;
1749: }
1750: my $reply = &get_query_reply($queryid);
1751: my $maxtries = 1;
1752: my $tries = 1;
1753: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1754: $reply = &get_query_reply($queryid);
1755: $tries ++;
1756: }
1757: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1758: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1759: } else {
1760: my @matches;
1761: if ($reply =~ /\n/) {
1762: @matches = split(/\n/,$reply);
1763: } else {
1764: @matches = split(/\&/,$reply);
1765: }
1766: foreach my $match (@matches) {
1767: my ($uname,$udom,%userhash);
1768: foreach my $entry (split(/:/,$match)) {
1769: my ($key,$value) =
1770: map {&unescape($_);} split(/=/,$entry);
1771: $userhash{$key} = $value;
1772: if ($key eq 'username') {
1773: $uname = $value;
1774: } elsif ($key eq 'domain') {
1775: $udom = $value;
1776: }
1777: }
1778: $results{$uname.':'.$udom} = \%userhash;
1779: }
1780: }
1781: }
1782: }
1783: return %results;
1784: }
1785:
1786: sub get_instuser {
1787: my ($udom,$uname,$id) = @_;
1788: my $homeserver = &domain($udom,'primary');
1789: my ($outcome,%results);
1790: if ($homeserver ne '') {
1791: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1792: &escape($id).':'.&escape($udom),$homeserver);
1793: my $host=&hostname($homeserver);
1794: if ($queryid !~/^\Q$host\E\_/) {
1795: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1796: return;
1797: }
1798: my $response = &get_query_reply($queryid);
1799: my $maxtries = 5;
1800: my $tries = 1;
1801: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1802: $response = &get_query_reply($queryid);
1803: $tries ++;
1804: }
1805: if (!&error($response) && $response ne 'refused') {
1806: if ($response eq 'unavailable') {
1807: $outcome = $response;
1808: } else {
1809: $outcome = 'ok';
1810: my @matches = split(/\n/,$response);
1811: foreach my $match (@matches) {
1812: my ($key,$value) = split(/=/,$match);
1813: $results{&unescape($key)} = &thaw_unescape($value);
1814: }
1815: }
1816: }
1817: }
1818: my %userinfo;
1819: if (ref($results{$uname}) eq 'HASH') {
1820: %userinfo = %{$results{$uname}};
1821: }
1822: return ($outcome,%userinfo);
1823: }
1824:
1825: sub inst_rulecheck {
1826: my ($udom,$uname,$id,$item,$rules) = @_;
1827: my %returnhash;
1828: if ($udom ne '') {
1829: if (ref($rules) eq 'ARRAY') {
1830: @{$rules} = map {&escape($_);} (@{$rules});
1831: my $rulestr = join(':',@{$rules});
1832: my $homeserver=&domain($udom,'primary');
1833: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1834: my $response;
1835: if ($item eq 'username') {
1836: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1837: ':'.&escape($uname).':'.$rulestr,
1838: $homeserver));
1839: } elsif ($item eq 'id') {
1840: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1841: ':'.&escape($id).':'.$rulestr,
1842: $homeserver));
1843: } elsif ($item eq 'selfcreate') {
1844: $response=&unescape(&reply('instselfcreatecheck:'.
1845: &escape($udom).':'.&escape($uname).
1846: ':'.$rulestr,$homeserver));
1847: }
1848: if ($response ne 'refused') {
1849: my @pairs=split(/\&/,$response);
1850: foreach my $item (@pairs) {
1851: my ($key,$value)=split(/=/,$item,2);
1852: $key = &unescape($key);
1853: next if ($key =~ /^error: 2 /);
1854: $returnhash{$key}=&thaw_unescape($value);
1855: }
1856: }
1857: }
1858: }
1859: }
1860: return %returnhash;
1861: }
1862:
1863: sub inst_userrules {
1864: my ($udom,$check) = @_;
1865: my (%ruleshash,@ruleorder);
1866: if ($udom ne '') {
1867: my $homeserver=&domain($udom,'primary');
1868: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1869: my $response;
1870: if ($check eq 'id') {
1871: $response=&reply('instidrules:'.&escape($udom),
1872: $homeserver);
1873: } elsif ($check eq 'email') {
1874: $response=&reply('instemailrules:'.&escape($udom),
1875: $homeserver);
1876: } else {
1877: $response=&reply('instuserrules:'.&escape($udom),
1878: $homeserver);
1879: }
1880: if (($response ne 'refused') && ($response ne 'error') &&
1881: ($response ne 'unknown_cmd') &&
1882: ($response ne 'no_such_host')) {
1883: my ($hashitems,$orderitems) = split(/:/,$response);
1884: my @pairs=split(/\&/,$hashitems);
1885: foreach my $item (@pairs) {
1886: my ($key,$value)=split(/=/,$item,2);
1887: $key = &unescape($key);
1888: next if ($key =~ /^error: 2 /);
1889: $ruleshash{$key}=&thaw_unescape($value);
1890: }
1891: my @esc_order = split(/\&/,$orderitems);
1892: foreach my $item (@esc_order) {
1893: push(@ruleorder,&unescape($item));
1894: }
1895: }
1896: }
1897: }
1898: return (\%ruleshash,\@ruleorder);
1899: }
1900:
1901: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1902:
1903: sub get_domain_defaults {
1904: my ($domain) = @_;
1905: my $cachetime = 60*60*24;
1906: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1907: if (defined($cached)) {
1908: if (ref($result) eq 'HASH') {
1909: return %{$result};
1910: }
1911: }
1912: my %domdefaults;
1913: my %domconfig =
1914: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1915: 'requestcourses','inststatus',
1916: 'coursedefaults','usersessions'],$domain);
1917: if (ref($domconfig{'defaults'}) eq 'HASH') {
1918: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1919: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1920: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1921: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1922: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1923: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1924: } else {
1925: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1926: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1927: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1928: }
1929: if (ref($domconfig{'quotas'}) eq 'HASH') {
1930: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1931: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1932: } else {
1933: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1934: }
1935: my @usertools = ('aboutme','blog','portfolio');
1936: foreach my $item (@usertools) {
1937: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1938: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1939: }
1940: }
1941: }
1942: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1943: foreach my $item ('official','unofficial','community') {
1944: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1945: }
1946: }
1947: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1948: foreach my $item ('inststatustypes','inststatusorder') {
1949: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1950: }
1951: }
1952: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1953: foreach my $item ('canuse_pdfforms') {
1954: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1955: }
1956: }
1957: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1958: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1959: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1960: }
1961: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1962: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1963: }
1964: }
1965: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1966: $cachetime);
1967: return %domdefaults;
1968: }
1969:
1970: # --------------------------------------------------- Assign a key to a student
1971:
1972: sub assign_access_key {
1973: #
1974: # a valid key looks like uname:udom#comments
1975: # comments are being appended
1976: #
1977: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1978: $kdom=
1979: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1980: $knum=
1981: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1982: $cdom=
1983: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1984: $cnum=
1985: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1986: $udom=$env{'user.name'} unless (defined($udom));
1987: $uname=$env{'user.domain'} unless (defined($uname));
1988: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1989: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1990: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1991: # assigned to this person
1992: # - this should not happen,
1993: # unless something went wrong
1994: # the first time around
1995: # ready to assign
1996: $logentry=$1.'; '.$logentry;
1997: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1998: $kdom,$knum) eq 'ok') {
1999: # key now belongs to user
2000: my $envkey='key.'.$cdom.'_'.$cnum;
2001: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2002: &appenv({'environment.'.$envkey => $ckey});
2003: return 'ok';
2004: } else {
2005: return
2006: 'error: Count not permanently assign key, will need to be re-entered later.';
2007: }
2008: } else {
2009: return 'error: Could not assign key, try again later.';
2010: }
2011: } elsif (!$existing{$ckey}) {
2012: # the key does not exist
2013: return 'error: The key does not exist';
2014: } else {
2015: # the key is somebody else's
2016: return 'error: The key is already in use';
2017: }
2018: }
2019:
2020: # ------------------------------------------ put an additional comment on a key
2021:
2022: sub comment_access_key {
2023: #
2024: # a valid key looks like uname:udom#comments
2025: # comments are being appended
2026: #
2027: my ($ckey,$cdom,$cnum,$logentry)=@_;
2028: $cdom=
2029: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2030: $cnum=
2031: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2032: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2033: if ($existing{$ckey}) {
2034: $existing{$ckey}.='; '.$logentry;
2035: # ready to assign
2036: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2037: $cdom,$cnum) eq 'ok') {
2038: return 'ok';
2039: } else {
2040: return 'error: Count not store comment.';
2041: }
2042: } else {
2043: # the key does not exist
2044: return 'error: The key does not exist';
2045: }
2046: }
2047:
2048: # ------------------------------------------------------ Generate a set of keys
2049:
2050: sub generate_access_keys {
2051: my ($number,$cdom,$cnum,$logentry)=@_;
2052: $cdom=
2053: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2054: $cnum=
2055: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2056: unless (&allowed('mky',$cdom)) { return 0; }
2057: unless (($cdom) && ($cnum)) { return 0; }
2058: if ($number>10000) { return 0; }
2059: sleep(2); # make sure don't get same seed twice
2060: srand(time()^($$+($$<<15))); # from "Programming Perl"
2061: my $total=0;
2062: for (my $i=1;$i<=$number;$i++) {
2063: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2064: sprintf("%lx",int(100000*rand)).'-'.
2065: sprintf("%lx",int(100000*rand));
2066: $newkey=~s/1/g/g; # folks mix up 1 and l
2067: $newkey=~s/0/h/g; # and also 0 and O
2068: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2069: if ($existing{$newkey}) {
2070: $i--;
2071: } else {
2072: if (&put('accesskeys',
2073: { $newkey => '# generated '.localtime().
2074: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2075: '; '.$logentry },
2076: $cdom,$cnum) eq 'ok') {
2077: $total++;
2078: }
2079: }
2080: }
2081: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2082: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2083: return $total;
2084: }
2085:
2086: # ------------------------------------------------------- Validate an accesskey
2087:
2088: sub validate_access_key {
2089: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2090: $cdom=
2091: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2092: $cnum=
2093: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2094: $udom=$env{'user.domain'} unless (defined($udom));
2095: $uname=$env{'user.name'} unless (defined($uname));
2096: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2097: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2098: }
2099:
2100: # ------------------------------------- Find the section of student in a course
2101: sub devalidate_getsection_cache {
2102: my ($udom,$unam,$courseid)=@_;
2103: my $hashid="$udom:$unam:$courseid";
2104: &devalidate_cache_new('getsection',$hashid);
2105: }
2106:
2107: sub courseid_to_courseurl {
2108: my ($courseid) = @_;
2109: #already url style courseid
2110: return $courseid if ($courseid =~ m{^/});
2111:
2112: if (exists($env{'course.'.$courseid.'.num'})) {
2113: my $cnum = $env{'course.'.$courseid.'.num'};
2114: my $cdom = $env{'course.'.$courseid.'.domain'};
2115: return "/$cdom/$cnum";
2116: }
2117:
2118: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2119: if (exists($courseinfo{'num'})) {
2120: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2121: }
2122:
2123: return undef;
2124: }
2125:
2126: sub getsection {
2127: my ($udom,$unam,$courseid)=@_;
2128: my $cachetime=1800;
2129:
2130: my $hashid="$udom:$unam:$courseid";
2131: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2132: if (defined($cached)) { return $result; }
2133:
2134: my %Pending;
2135: my %Expired;
2136: #
2137: # Each role can either have not started yet (pending), be active,
2138: # or have expired.
2139: #
2140: # If there is an active role, we are done.
2141: #
2142: # If there is more than one role which has not started yet,
2143: # choose the one which will start sooner
2144: # If there is one role which has not started yet, return it.
2145: #
2146: # If there is more than one expired role, choose the one which ended last.
2147: # If there is a role which has expired, return it.
2148: #
2149: $courseid = &courseid_to_courseurl($courseid);
2150: my $extra = &freeze_escape({'skipcheck' => 1});
2151: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
2152: foreach my $key (keys(%roleshash)) {
2153: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2154: my $section=$1;
2155: if ($key eq $courseid.'_st') { $section=''; }
2156: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2157: my $now=time;
2158: if (defined($end) && $end && ($now > $end)) {
2159: $Expired{$end}=$section;
2160: next;
2161: }
2162: if (defined($start) && $start && ($now < $start)) {
2163: $Pending{$start}=$section;
2164: next;
2165: }
2166: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2167: }
2168: #
2169: # Presumedly there will be few matching roles from the above
2170: # loop and the sorting time will be negligible.
2171: if (scalar(keys(%Pending))) {
2172: my ($time) = sort {$a <=> $b} keys(%Pending);
2173: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2174: }
2175: if (scalar(keys(%Expired))) {
2176: my @sorted = sort {$a <=> $b} keys(%Expired);
2177: my $time = pop(@sorted);
2178: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2179: }
2180: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2181: }
2182:
2183: sub save_cache {
2184: &purge_remembered();
2185: #&Apache::loncommon::validate_page();
2186: undef(%env);
2187: undef($env_loaded);
2188: }
2189:
2190: my $to_remember=-1;
2191: my %remembered;
2192: my %accessed;
2193: my $kicks=0;
2194: my $hits=0;
2195: sub make_key {
2196: my ($name,$id) = @_;
2197: if (length($id) > 65
2198: && length(&escape($id)) > 200) {
2199: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2200: }
2201: return &escape($name.':'.$id);
2202: }
2203:
2204: sub devalidate_cache_new {
2205: my ($name,$id,$debug) = @_;
2206: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2207: $id=&make_key($name,$id);
2208: $memcache->delete($id);
2209: delete($remembered{$id});
2210: delete($accessed{$id});
2211: }
2212:
2213: sub is_cached_new {
2214: my ($name,$id,$debug) = @_;
2215: $id=&make_key($name,$id);
2216: if (exists($remembered{$id})) {
2217: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2218: $accessed{$id}=[&gettimeofday()];
2219: $hits++;
2220: return ($remembered{$id},1);
2221: }
2222: my $value = $memcache->get($id);
2223: if (!(defined($value))) {
2224: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2225: return (undef,undef);
2226: }
2227: if ($value eq '__undef__') {
2228: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2229: $value=undef;
2230: }
2231: &make_room($id,$value,$debug);
2232: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2233: return ($value,1);
2234: }
2235:
2236: sub do_cache_new {
2237: my ($name,$id,$value,$time,$debug) = @_;
2238: $id=&make_key($name,$id);
2239: my $setvalue=$value;
2240: if (!defined($setvalue)) {
2241: $setvalue='__undef__';
2242: }
2243: if (!defined($time) ) {
2244: $time=600;
2245: }
2246: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2247: my $result = $memcache->set($id,$setvalue,$time);
2248: if (! $result) {
2249: &logthis("caching of id -> $id failed");
2250: $memcache->disconnect_all();
2251: }
2252: # need to make a copy of $value
2253: &make_room($id,$value,$debug);
2254: return $value;
2255: }
2256:
2257: sub make_room {
2258: my ($id,$value,$debug)=@_;
2259:
2260: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2261: : $value;
2262: if ($to_remember<0) { return; }
2263: $accessed{$id}=[&gettimeofday()];
2264: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2265: my $to_kick;
2266: my $max_time=0;
2267: foreach my $other (keys(%accessed)) {
2268: if (&tv_interval($accessed{$other}) > $max_time) {
2269: $to_kick=$other;
2270: $max_time=&tv_interval($accessed{$other});
2271: }
2272: }
2273: delete($remembered{$to_kick});
2274: delete($accessed{$to_kick});
2275: $kicks++;
2276: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2277: return;
2278: }
2279:
2280: sub purge_remembered {
2281: #&logthis("Tossing ".scalar(keys(%remembered)));
2282: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2283: undef(%remembered);
2284: undef(%accessed);
2285: }
2286: # ------------------------------------- Read an entry from a user's environment
2287:
2288: sub userenvironment {
2289: my ($udom,$unam,@what)=@_;
2290: my $items;
2291: foreach my $item (@what) {
2292: $items.=&escape($item).'&';
2293: }
2294: $items=~s/\&$//;
2295: my %returnhash=();
2296: my $uhome = &homeserver($unam,$udom);
2297: unless ($uhome eq 'no_host') {
2298: my @answer=split(/\&/,
2299: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2300: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2301: return %returnhash;
2302: }
2303: my $i;
2304: for ($i=0;$i<=$#what;$i++) {
2305: $returnhash{$what[$i]}=&unescape($answer[$i]);
2306: }
2307: }
2308: return %returnhash;
2309: }
2310:
2311: # ---------------------------------------------------------- Get a studentphoto
2312: sub studentphoto {
2313: my ($udom,$unam,$ext) = @_;
2314: my $home=&Apache::lonnet::homeserver($unam,$udom);
2315: if (defined($env{'request.course.id'})) {
2316: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2317: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2318: return(&retrievestudentphoto($udom,$unam,$ext));
2319: } else {
2320: my ($result,$perm_reqd)=
2321: &Apache::lonnet::auto_photo_permission($unam,$udom);
2322: if ($result eq 'ok') {
2323: if (!($perm_reqd eq 'yes')) {
2324: return(&retrievestudentphoto($udom,$unam,$ext));
2325: }
2326: }
2327: }
2328: }
2329: } else {
2330: my ($result,$perm_reqd) =
2331: &Apache::lonnet::auto_photo_permission($unam,$udom);
2332: if ($result eq 'ok') {
2333: if (!($perm_reqd eq 'yes')) {
2334: return(&retrievestudentphoto($udom,$unam,$ext));
2335: }
2336: }
2337: }
2338: return '/adm/lonKaputt/lonlogo_broken.gif';
2339: }
2340:
2341: sub retrievestudentphoto {
2342: my ($udom,$unam,$ext,$type) = @_;
2343: my $home=&Apache::lonnet::homeserver($unam,$udom);
2344: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2345: if ($ret eq 'ok') {
2346: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2347: if ($type eq 'thumbnail') {
2348: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2349: }
2350: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2351: return $tokenurl;
2352: } else {
2353: if ($type eq 'thumbnail') {
2354: return '/adm/lonKaputt/genericstudent_tn.gif';
2355: } else {
2356: return '/adm/lonKaputt/lonlogo_broken.gif';
2357: }
2358: }
2359: }
2360:
2361: # -------------------------------------------------------------------- New chat
2362:
2363: sub chatsend {
2364: my ($newentry,$anon,$group)=@_;
2365: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2366: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2367: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2368: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2369: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2370: &escape($newentry)).':'.$group,$chome);
2371: }
2372:
2373: # ------------------------------------------ Find current version of a resource
2374:
2375: sub getversion {
2376: my $fname=&clutter(shift);
2377: unless ($fname=~/^\/res\//) { return -1; }
2378: return ¤tversion(&filelocation('',$fname));
2379: }
2380:
2381: sub currentversion {
2382: my $fname=shift;
2383: my $author=$fname;
2384: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2385: my ($udom,$uname)=split(/\//,$author);
2386: my $home=&homeserver($uname,$udom);
2387: if ($home eq 'no_host') {
2388: return -1;
2389: }
2390: my $answer=&reply("currentversion:$fname",$home);
2391: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2392: return -1;
2393: }
2394: return $answer;
2395: }
2396:
2397: #
2398: # Return special version number of resource if set by override, empty otherwise
2399: #
2400: sub usedversion {
2401: my $fname=shift;
2402: unless ($fname) { $fname=$env{'request.uri'}; }
2403: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2404: if ($urlversion) { return $urlversion; }
2405: return '';
2406: }
2407:
2408: # ----------------------------- Subscribe to a resource, return URL if possible
2409:
2410: sub subscribe {
2411: my $fname=shift;
2412: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2413: $fname=~s/[\n\r]//g;
2414: my $author=$fname;
2415: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2416: my ($udom,$uname)=split(/\//,$author);
2417: my $home=homeserver($uname,$udom);
2418: if ($home eq 'no_host') {
2419: return 'not_found';
2420: }
2421: my $answer=reply("sub:$fname",$home);
2422: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2423: $answer.=' by '.$home;
2424: }
2425: return $answer;
2426: }
2427:
2428: # -------------------------------------------------------------- Replicate file
2429:
2430: sub repcopy {
2431: my $filename=shift;
2432: $filename=~s/\/+/\//g;
2433: my $londocroot = $perlvar{'lonDocRoot'};
2434: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2435: if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
2436: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2437: $filename=~m{^/*(uploaded|editupload)/}) {
2438: return &repcopy_userfile($filename);
2439: }
2440: $filename=~s/[\n\r]//g;
2441: my $transname="$filename.in.transfer";
2442: # FIXME: this should flock
2443: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2444: my $remoteurl=subscribe($filename);
2445: if ($remoteurl =~ /^con_lost by/) {
2446: &logthis("Subscribe returned $remoteurl: $filename");
2447: return 'unavailable';
2448: } elsif ($remoteurl eq 'not_found') {
2449: #&logthis("Subscribe returned not_found: $filename");
2450: return 'not_found';
2451: } elsif ($remoteurl =~ /^rejected by/) {
2452: &logthis("Subscribe returned $remoteurl: $filename");
2453: return 'forbidden';
2454: } elsif ($remoteurl eq 'directory') {
2455: return 'ok';
2456: } else {
2457: my $author=$filename;
2458: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2459: my ($udom,$uname)=split(/\//,$author);
2460: my $home=homeserver($uname,$udom);
2461: unless ($home eq $perlvar{'lonHostID'}) {
2462: my @parts=split(/\//,$filename);
2463: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2464: if ($path ne "$londocroot/res") {
2465: &logthis("Malconfiguration for replication: $filename");
2466: return 'bad_request';
2467: }
2468: my $count;
2469: for ($count=5;$count<$#parts;$count++) {
2470: $path.="/$parts[$count]";
2471: if ((-e $path)!=1) {
2472: mkdir($path,0777);
2473: }
2474: }
2475: my $ua=new LWP::UserAgent;
2476: my $request=new HTTP::Request('GET',"$remoteurl");
2477: my $response=$ua->request($request,$transname);
2478: if ($response->is_error()) {
2479: unlink($transname);
2480: my $message=$response->status_line;
2481: &logthis("<font color=\"blue\">WARNING:"
2482: ." LWP get: $message: $filename</font>");
2483: return 'unavailable';
2484: } else {
2485: if ($remoteurl!~/\.meta$/) {
2486: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2487: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2488: if ($mresponse->is_error()) {
2489: unlink($filename.'.meta');
2490: &logthis(
2491: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2492: }
2493: }
2494: rename($transname,$filename);
2495: return 'ok';
2496: }
2497: }
2498: }
2499: }
2500:
2501: # ------------------------------------------------ Get server side include body
2502: sub ssi_body {
2503: my ($filelink,%form)=@_;
2504: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2505: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2506: }
2507: my $output='';
2508: my $response;
2509: if ($filelink=~/^https?\:/) {
2510: ($output,$response)=&externalssi($filelink);
2511: } else {
2512: $filelink .= $filelink=~/\?/ ? '&' : '?';
2513: $filelink .= 'inhibitmenu=yes';
2514: ($output,$response)=&ssi($filelink,%form);
2515: }
2516: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2517: $output=~s/^.*?\<body[^\>]*\>//si;
2518: $output=~s/\<\/body\s*\>.*?$//si;
2519: if (wantarray) {
2520: return ($output, $response);
2521: } else {
2522: return $output;
2523: }
2524: }
2525:
2526: # --------------------------------------------------------- Server Side Include
2527:
2528: sub absolute_url {
2529: my ($host_name) = @_;
2530: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2531: if ($host_name eq '') {
2532: $host_name = $ENV{'SERVER_NAME'};
2533: }
2534: return $protocol.$host_name;
2535: }
2536:
2537: #
2538: # Server side include.
2539: # Parameters:
2540: # fn Possibly encrypted resource name/id.
2541: # form Hash that describes how the rendering should be done
2542: # and other things.
2543: # Returns:
2544: # Scalar context: The content of the response.
2545: # Array context: 2 element list of the content and the full response object.
2546: #
2547: sub ssi {
2548:
2549: my ($fn,%form)=@_;
2550: my $ua=new LWP::UserAgent;
2551: my $request;
2552:
2553: $form{'no_update_last_known'}=1;
2554: &Apache::lonenc::check_encrypt(\$fn);
2555: if (%form) {
2556: $request=new HTTP::Request('POST',&absolute_url().$fn);
2557: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2558: } else {
2559: $request=new HTTP::Request('GET',&absolute_url().$fn);
2560: }
2561:
2562: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2563: my $response=$ua->request($request);
2564:
2565: if (wantarray) {
2566: return ($response->content, $response);
2567: } else {
2568: return $response->content;
2569: }
2570: }
2571:
2572: sub externalssi {
2573: my ($url)=@_;
2574: my $ua=new LWP::UserAgent;
2575: my $request=new HTTP::Request('GET',$url);
2576: my $response=$ua->request($request);
2577: if (wantarray) {
2578: return ($response->content, $response);
2579: } else {
2580: return $response->content;
2581: }
2582: }
2583:
2584: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2585:
2586: sub allowuploaded {
2587: my ($srcurl,$url)=@_;
2588: $url=&clutter(&declutter($url));
2589: my $dir=$url;
2590: $dir=~s/\/[^\/]+$//;
2591: my %httpref=();
2592: my $httpurl=&hreflocation('',$url);
2593: $httpref{'httpref.'.$httpurl}=$srcurl;
2594: &Apache::lonnet::appenv(\%httpref);
2595: }
2596:
2597: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2598: # input: action, courseID, current domain, intended
2599: # path to file, source of file, instruction to parse file for objects,
2600: # ref to hash for embedded objects,
2601: # ref to hash for codebase of java objects.
2602: # reference to scalar to accommodate mime type determined
2603: # from File::MMagic if $parser = parse.
2604: #
2605: # output: url to file (if action was uploaddoc),
2606: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2607: #
2608: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2609: # course.
2610: #
2611: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2612: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2613: # course's home server.
2614: #
2615: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2616: # be copied from $source (current location) to
2617: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2618: # and will then be copied to
2619: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2620: # course's home server.
2621: #
2622: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2623: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2624: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2625: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2626: # in course's home server.
2627: #
2628:
2629: sub process_coursefile {
2630: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2631: $mimetype)=@_;
2632: my $fetchresult;
2633: my $home=&homeserver($docuname,$docudom);
2634: if ($action eq 'propagate') {
2635: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2636: $home);
2637: } else {
2638: my $fpath = '';
2639: my $fname = $file;
2640: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2641: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2642: my $filepath = &build_filepath($fpath);
2643: if ($action eq 'copy') {
2644: if ($source eq '') {
2645: $fetchresult = 'no source file';
2646: return $fetchresult;
2647: } else {
2648: my $destination = $filepath.'/'.$fname;
2649: rename($source,$destination);
2650: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2651: $home);
2652: }
2653: } elsif ($action eq 'uploaddoc') {
2654: open(my $fh,'>'.$filepath.'/'.$fname);
2655: print $fh $env{'form.'.$source};
2656: close($fh);
2657: if ($parser eq 'parse') {
2658: my $mm = new File::MMagic;
2659: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2660: if ($type eq 'text/html') {
2661: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2662: unless ($parse_result eq 'ok') {
2663: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2664: }
2665: }
2666: if (ref($mimetype)) {
2667: $$mimetype = $type;
2668: }
2669: }
2670: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2671: $home);
2672: if ($fetchresult eq 'ok') {
2673: return '/uploaded/'.$fpath.'/'.$fname;
2674: } else {
2675: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2676: ' to host '.$home.': '.$fetchresult);
2677: return '/adm/notfound.html';
2678: }
2679: }
2680: }
2681: unless ( $fetchresult eq 'ok') {
2682: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2683: ' to host '.$home.': '.$fetchresult);
2684: }
2685: return $fetchresult;
2686: }
2687:
2688: sub build_filepath {
2689: my ($fpath) = @_;
2690: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2691: unless ($fpath eq '') {
2692: my @parts=split('/',$fpath);
2693: foreach my $part (@parts) {
2694: $filepath.= '/'.$part;
2695: if ((-e $filepath)!=1) {
2696: mkdir($filepath,0777);
2697: }
2698: }
2699: }
2700: return $filepath;
2701: }
2702:
2703: sub store_edited_file {
2704: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2705: my $file = $primary_url;
2706: $file =~ s#^/uploaded/$docudom/$docuname/##;
2707: my $fpath = '';
2708: my $fname = $file;
2709: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2710: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2711: my $filepath = &build_filepath($fpath);
2712: open(my $fh,'>'.$filepath.'/'.$fname);
2713: print $fh $content;
2714: close($fh);
2715: my $home=&homeserver($docuname,$docudom);
2716: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2717: $home);
2718: if ($$fetchresult eq 'ok') {
2719: return '/uploaded/'.$fpath.'/'.$fname;
2720: } else {
2721: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2722: ' to host '.$home.': '.$$fetchresult);
2723: return '/adm/notfound.html';
2724: }
2725: }
2726:
2727: sub clean_filename {
2728: my ($fname,$args)=@_;
2729: # Replace Windows backslashes by forward slashes
2730: $fname=~s/\\/\//g;
2731: if (!$args->{'keep_path'}) {
2732: # Get rid of everything but the actual filename
2733: $fname=~s/^.*\/([^\/]+)$/$1/;
2734: }
2735: # Replace spaces by underscores
2736: $fname=~s/\s+/\_/g;
2737: # Replace all other weird characters by nothing
2738: $fname=~s{[^/\w\.\-]}{}g;
2739: # Replace all .\d. sequences with _\d. so they no longer look like version
2740: # numbers
2741: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2742: return $fname;
2743: }
2744: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2745: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2746: # image with the same aspect ratio as the original, but with dimensions which do
2747: # not exceed $resizewidth and $resizeheight.
2748:
2749: sub resizeImage {
2750: my ($img_path,$resizewidth,$resizeheight) = @_;
2751: my $ima = Image::Magick->new;
2752: my $resized;
2753: if (-e $img_path) {
2754: $ima->Read($img_path);
2755: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2756: my $width = $ima->Get('width');
2757: my $height = $ima->Get('height');
2758: if ($width > $resizewidth) {
2759: my $factor = $width/$resizewidth;
2760: my $newheight = $height/$factor;
2761: $ima->Scale(width=>$resizewidth,height=>$newheight);
2762: $resized = 1;
2763: }
2764: }
2765: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2766: my $width = $ima->Get('width');
2767: my $height = $ima->Get('height');
2768: if ($height > $resizeheight) {
2769: my $factor = $height/$resizeheight;
2770: my $newwidth = $width/$factor;
2771: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2772: $resized = 1;
2773: }
2774: }
2775: if ($resized) {
2776: $ima->Write($img_path);
2777: }
2778: }
2779: return;
2780: }
2781:
2782: # --------------- Take an uploaded file and put it into the userfiles directory
2783: # input: $formname - the contents of the file are in $env{"form.$formname"}
2784: # the desired filename is in $env{"form.$formname.filename"}
2785: # $context - possible values: coursedoc, existingfile, overwrite,
2786: # canceloverwrite, or ''.
2787: # if 'coursedoc': upload to the current course
2788: # if 'existingfile': write file to tmp/overwrites directory
2789: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2790: # $context is passed as argument to &finishuserfileupload
2791: # $subdir - directory in userfile to store the file into
2792: # $parser - instruction to parse file for objects ($parser = parse)
2793: # $allfiles - reference to hash for embedded objects
2794: # $codebase - reference to hash for codebase of java objects
2795: # $desuname - username for permanent storage of uploaded file
2796: # $dsetudom - domain for permanaent storage of uploaded file
2797: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2798: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2799: # $resizewidth - width (pixels) to which to resize uploaded image
2800: # $resizeheight - height (pixels) to which to resize uploaded image
2801: # $mimetype - reference to scalar to accommodate mime type determined
2802: # from File::MMagic if $parser = parse.
2803: #
2804: # output: url of file in userspace, or error: <message>
2805: # or /adm/notfound.html if failure to upload occurse
2806:
2807: sub userfileupload {
2808: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2809: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2810: if (!defined($subdir)) { $subdir='unknown'; }
2811: my $fname=$env{'form.'.$formname.'.filename'};
2812: $fname=&clean_filename($fname);
2813: # See if there is anything left
2814: unless ($fname) { return 'error: no uploaded file'; }
2815: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2816: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2817: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2818: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2819: my $now = time;
2820: my $filepath;
2821: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2822: $filepath = 'tmp/helprequests/'.$now;
2823: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2824: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2825: '_'.$env{'user.domain'}.'/pending';
2826: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2827: my ($docuname,$docudom);
2828: if ($destudom) {
2829: $docudom = $destudom;
2830: } else {
2831: $docudom = $env{'user.domain'};
2832: }
2833: if ($destuname) {
2834: $docuname = $destuname;
2835: } else {
2836: $docuname = $env{'user.name'};
2837: }
2838: if (exists($env{'form.group'})) {
2839: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2840: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2841: }
2842: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2843: if ($context eq 'canceloverwrite') {
2844: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2845: if (-e $tempfile) {
2846: my @info = stat($tempfile);
2847: if ($info[9] eq $env{'form.timestamp'}) {
2848: unlink($tempfile);
2849: }
2850: }
2851: return;
2852: }
2853: }
2854: # Create the directory if not present
2855: my @parts=split(/\//,$filepath);
2856: my $fullpath = $perlvar{'lonDaemons'};
2857: for (my $i=0;$i<@parts;$i++) {
2858: $fullpath .= '/'.$parts[$i];
2859: if ((-e $fullpath)!=1) {
2860: mkdir($fullpath,0777);
2861: }
2862: }
2863: open(my $fh,'>'.$fullpath.'/'.$fname);
2864: print $fh $env{'form.'.$formname};
2865: close($fh);
2866: if ($context eq 'existingfile') {
2867: my @info = stat($fullpath.'/'.$fname);
2868: return ($fullpath.'/'.$fname,$info[9]);
2869: } else {
2870: return $fullpath.'/'.$fname;
2871: }
2872: }
2873: if ($subdir eq 'scantron') {
2874: $fname = 'scantron_orig_'.$fname;
2875: } else {
2876: $fname="$subdir/$fname";
2877: }
2878: if ($context eq 'coursedoc') {
2879: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2880: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2881: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2882: return &finishuserfileupload($docuname,$docudom,
2883: $formname,$fname,$parser,$allfiles,
2884: $codebase,$thumbwidth,$thumbheight,
2885: $resizewidth,$resizeheight,$context,$mimetype);
2886: } else {
2887: $fname=$env{'form.folder'}.'/'.$fname;
2888: return &process_coursefile('uploaddoc',$docuname,$docudom,
2889: $fname,$formname,$parser,
2890: $allfiles,$codebase,$mimetype);
2891: }
2892: } elsif (defined($destuname)) {
2893: my $docuname=$destuname;
2894: my $docudom=$destudom;
2895: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2896: $parser,$allfiles,$codebase,
2897: $thumbwidth,$thumbheight,
2898: $resizewidth,$resizeheight,$context,$mimetype);
2899: } else {
2900: my $docuname=$env{'user.name'};
2901: my $docudom=$env{'user.domain'};
2902: if (exists($env{'form.group'})) {
2903: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2904: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2905: }
2906: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2907: $parser,$allfiles,$codebase,
2908: $thumbwidth,$thumbheight,
2909: $resizewidth,$resizeheight,$context,$mimetype);
2910: }
2911: }
2912:
2913: sub finishuserfileupload {
2914: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2915: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2916: my $path=$docudom.'/'.$docuname.'/';
2917: my $filepath=$perlvar{'lonDocRoot'};
2918:
2919: my ($fnamepath,$file,$fetchthumb);
2920: $file=$fname;
2921: if ($fname=~m|/|) {
2922: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2923: $path.=$fnamepath.'/';
2924: }
2925: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2926: my $count;
2927: for ($count=4;$count<=$#parts;$count++) {
2928: $filepath.="/$parts[$count]";
2929: if ((-e $filepath)!=1) {
2930: mkdir($filepath,0777);
2931: }
2932: }
2933:
2934: # Save the file
2935: {
2936: if (!open(FH,'>'.$filepath.'/'.$file)) {
2937: &logthis('Failed to create '.$filepath.'/'.$file);
2938: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2939: return '/adm/notfound.html';
2940: }
2941: if ($context eq 'overwrite') {
2942: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2943: my $target = $filepath.'/'.$file;
2944: if (-e $source) {
2945: my @info = stat($source);
2946: if ($info[9] eq $env{'form.timestamp'}) {
2947: unless (&File::Copy::move($source,$target)) {
2948: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2949: return "Moving from $source failed";
2950: }
2951: } else {
2952: return "Temporary file: $source had unexpected date/time for last modification";
2953: }
2954: } else {
2955: return "Temporary file: $source missing";
2956: }
2957: } elsif (!print FH ($env{'form.'.$formname})) {
2958: &logthis('Failed to write to '.$filepath.'/'.$file);
2959: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2960: return '/adm/notfound.html';
2961: }
2962: close(FH);
2963: if ($resizewidth && $resizeheight) {
2964: my $mm = new File::MMagic;
2965: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2966: if ($mime_type =~ m{^image/}) {
2967: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2968: }
2969: }
2970: }
2971: if ($parser eq 'parse') {
2972: my $mm = new File::MMagic;
2973: my $type = $mm->checktype_filename($filepath.'/'.$file);
2974: if ($type eq 'text/html') {
2975: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2976: $allfiles,$codebase);
2977: unless ($parse_result eq 'ok') {
2978: &logthis('Failed to parse '.$filepath.$file.
2979: ' for embedded media: '.$parse_result);
2980: }
2981: }
2982: if (ref($mimetype)) {
2983: $$mimetype = $type;
2984: }
2985: }
2986: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2987: my $input = $filepath.'/'.$file;
2988: my $output = $filepath.'/'.'tn-'.$file;
2989: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2990: system("convert -sample $thumbsize $input $output");
2991: if (-e $filepath.'/'.'tn-'.$file) {
2992: $fetchthumb = 1;
2993: }
2994: }
2995:
2996: # Notify homeserver to grep it
2997: #
2998: my $docuhome=&homeserver($docuname,$docudom);
2999: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3000: if ($fetchresult eq 'ok') {
3001: if ($fetchthumb) {
3002: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3003: if ($thumbresult ne 'ok') {
3004: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3005: $docuhome.': '.$thumbresult);
3006: }
3007: }
3008: #
3009: # Return the URL to it
3010: return '/uploaded/'.$path.$file;
3011: } else {
3012: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3013: ': '.$fetchresult);
3014: return '/adm/notfound.html';
3015: }
3016: }
3017:
3018: sub extract_embedded_items {
3019: my ($fullpath,$allfiles,$codebase,$content) = @_;
3020: my @state = ();
3021: my %javafiles = (
3022: codebase => '',
3023: code => '',
3024: archive => ''
3025: );
3026: my %mediafiles = (
3027: src => '',
3028: movie => '',
3029: );
3030: my $p;
3031: if ($content) {
3032: $p = HTML::LCParser->new($content);
3033: } else {
3034: $p = HTML::LCParser->new($fullpath);
3035: }
3036: while (my $t=$p->get_token()) {
3037: if ($t->[0] eq 'S') {
3038: my ($tagname, $attr) = ($t->[1],$t->[2]);
3039: push(@state, $tagname);
3040: if (lc($tagname) eq 'allow') {
3041: &add_filetype($allfiles,$attr->{'src'},'src');
3042: }
3043: if (lc($tagname) eq 'img') {
3044: &add_filetype($allfiles,$attr->{'src'},'src');
3045: }
3046: if (lc($tagname) eq 'a') {
3047: &add_filetype($allfiles,$attr->{'href'},'href');
3048: }
3049: if (lc($tagname) eq 'script') {
3050: if ($attr->{'archive'} =~ /\.jar$/i) {
3051: &add_filetype($allfiles,$attr->{'archive'},'archive');
3052: } else {
3053: &add_filetype($allfiles,$attr->{'src'},'src');
3054: }
3055: }
3056: if (lc($tagname) eq 'link') {
3057: if (lc($attr->{'rel'}) eq 'stylesheet') {
3058: &add_filetype($allfiles,$attr->{'href'},'href');
3059: }
3060: }
3061: if (lc($tagname) eq 'object' ||
3062: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3063: foreach my $item (keys(%javafiles)) {
3064: $javafiles{$item} = '';
3065: }
3066: }
3067: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3068: my $name = lc($attr->{'name'});
3069: foreach my $item (keys(%javafiles)) {
3070: if ($name eq $item) {
3071: $javafiles{$item} = $attr->{'value'};
3072: last;
3073: }
3074: }
3075: foreach my $item (keys(%mediafiles)) {
3076: if ($name eq $item) {
3077: &add_filetype($allfiles, $attr->{'value'}, 'value');
3078: last;
3079: }
3080: }
3081: }
3082: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3083: foreach my $item (keys(%javafiles)) {
3084: if ($attr->{$item}) {
3085: $javafiles{$item} = $attr->{$item};
3086: last;
3087: }
3088: }
3089: foreach my $item (keys(%mediafiles)) {
3090: if ($attr->{$item}) {
3091: &add_filetype($allfiles,$attr->{$item},$item);
3092: last;
3093: }
3094: }
3095: }
3096: } elsif ($t->[0] eq 'E') {
3097: my ($tagname) = ($t->[1]);
3098: if ($javafiles{'codebase'} ne '') {
3099: $javafiles{'codebase'} .= '/';
3100: }
3101: if (lc($tagname) eq 'applet' ||
3102: lc($tagname) eq 'object' ||
3103: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3104: ) {
3105: foreach my $item (keys(%javafiles)) {
3106: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3107: my $file=$javafiles{'codebase'}.$javafiles{$item};
3108: &add_filetype($allfiles,$file,$item);
3109: }
3110: }
3111: }
3112: pop @state;
3113: }
3114: }
3115: return 'ok';
3116: }
3117:
3118: sub add_filetype {
3119: my ($allfiles,$file,$type)=@_;
3120: if (exists($allfiles->{$file})) {
3121: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3122: push(@{$allfiles->{$file}}, &escape($type));
3123: }
3124: } else {
3125: @{$allfiles->{$file}} = (&escape($type));
3126: }
3127: }
3128:
3129: sub removeuploadedurl {
3130: my ($url)=@_;
3131: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3132: return &removeuserfile($uname,$udom,$fname);
3133: }
3134:
3135: sub removeuserfile {
3136: my ($docuname,$docudom,$fname)=@_;
3137: my $home=&homeserver($docuname,$docudom);
3138: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3139: if ($result eq 'ok') {
3140: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3141: my $metafile = $fname.'.meta';
3142: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3143: my $url = "/uploaded/$docudom/$docuname/$fname";
3144: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3145: my $sqlresult =
3146: &update_portfolio_table($docuname,$docudom,$file,
3147: 'portfolio_metadata',$group,
3148: 'delete');
3149: }
3150: }
3151: return $result;
3152: }
3153:
3154: sub mkdiruserfile {
3155: my ($docuname,$docudom,$dir)=@_;
3156: my $home=&homeserver($docuname,$docudom);
3157: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3158: }
3159:
3160: sub renameuserfile {
3161: my ($docuname,$docudom,$old,$new)=@_;
3162: my $home=&homeserver($docuname,$docudom);
3163: my $result = &reply("renameuserfile:$docudom:$docuname:".
3164: &escape("$old").':'.&escape("$new"),$home);
3165: if ($result eq 'ok') {
3166: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3167: my $oldmeta = $old.'.meta';
3168: my $newmeta = $new.'.meta';
3169: my $metaresult =
3170: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3171: my $url = "/uploaded/$docudom/$docuname/$old";
3172: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3173: my $sqlresult =
3174: &update_portfolio_table($docuname,$docudom,$file,
3175: 'portfolio_metadata',$group,
3176: 'delete');
3177: }
3178: }
3179: return $result;
3180: }
3181:
3182: # ------------------------------------------------------------------------- Log
3183:
3184: sub log {
3185: my ($dom,$nam,$hom,$what)=@_;
3186: return critical("log:$dom:$nam:$what",$hom);
3187: }
3188:
3189: # ------------------------------------------------------------------ Course Log
3190: #
3191: # This routine flushes several buffers of non-mission-critical nature
3192: #
3193:
3194: sub flushcourselogs {
3195: &logthis('Flushing log buffers');
3196: #
3197: # course logs
3198: # This is a log of all transactions in a course, which can be used
3199: # for data mining purposes
3200: #
3201: # It also collects the courseid database, which lists last transaction
3202: # times and course titles for all courseids
3203: #
3204: my %courseidbuffer=();
3205: foreach my $crsid (keys(%courselogs)) {
3206: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3207: &escape($courselogs{$crsid}),
3208: $coursehombuf{$crsid}) eq 'ok') {
3209: delete $courselogs{$crsid};
3210: } else {
3211: &logthis('Failed to flush log buffer for '.$crsid);
3212: if (length($courselogs{$crsid})>40000) {
3213: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3214: " exceeded maximum size, deleting.</font>");
3215: delete $courselogs{$crsid};
3216: }
3217: }
3218: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3219: 'description' => $coursedescrbuf{$crsid},
3220: 'inst_code' => $courseinstcodebuf{$crsid},
3221: 'type' => $coursetypebuf{$crsid},
3222: 'owner' => $courseownerbuf{$crsid},
3223: };
3224: }
3225: #
3226: # Write course id database (reverse lookup) to homeserver of courses
3227: # Is used in pickcourse
3228: #
3229: foreach my $crs_home (keys(%courseidbuffer)) {
3230: my $response = &courseidput(&host_domain($crs_home),
3231: $courseidbuffer{$crs_home},
3232: $crs_home,'timeonly');
3233: }
3234: #
3235: # File accesses
3236: # Writes to the dynamic metadata of resources to get hit counts, etc.
3237: #
3238: foreach my $entry (keys(%accesshash)) {
3239: if ($entry =~ /___count$/) {
3240: my ($dom,$name);
3241: ($dom,$name,undef)=
3242: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3243: if (! defined($dom) || $dom eq '' ||
3244: ! defined($name) || $name eq '') {
3245: my $cid = $env{'request.course.id'};
3246: $dom = $env{'request.'.$cid.'.domain'};
3247: $name = $env{'request.'.$cid.'.num'};
3248: }
3249: my $value = $accesshash{$entry};
3250: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3251: my %temphash=($url => $value);
3252: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3253: if ($result eq 'ok') {
3254: delete $accesshash{$entry};
3255: } elsif ($result eq 'unknown_cmd') {
3256: # Target server has old code running on it.
3257: my %temphash=($entry => $value);
3258: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3259: delete $accesshash{$entry};
3260: }
3261: }
3262: } else {
3263: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3264: my %temphash=($entry => $accesshash{$entry});
3265: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3266: delete $accesshash{$entry};
3267: }
3268: }
3269: }
3270: #
3271: # Roles
3272: # Reverse lookup of user roles for course faculty/staff and co-authorship
3273: #
3274: foreach my $entry (keys(%userrolehash)) {
3275: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3276: split(/\:/,$entry);
3277: if (&Apache::lonnet::put('nohist_userroles',
3278: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3279: $rudom,$runame) eq 'ok') {
3280: delete $userrolehash{$entry};
3281: }
3282: }
3283: #
3284: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3285: #
3286: my %domrolebuffer = ();
3287: foreach my $entry (keys(%domainrolehash)) {
3288: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3289: if ($domrolebuffer{$rudom}) {
3290: $domrolebuffer{$rudom}.='&'.&escape($entry).
3291: '='.&escape($domainrolehash{$entry});
3292: } else {
3293: $domrolebuffer{$rudom}.=&escape($entry).
3294: '='.&escape($domainrolehash{$entry});
3295: }
3296: delete $domainrolehash{$entry};
3297: }
3298: foreach my $dom (keys(%domrolebuffer)) {
3299: my %servers = &get_servers($dom,'library');
3300: foreach my $tryserver (keys(%servers)) {
3301: unless (&reply('domroleput:'.$dom.':'.
3302: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3303: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3304: }
3305: }
3306: }
3307: $dumpcount++;
3308: }
3309:
3310: sub courselog {
3311: my $what=shift;
3312: $what=time.':'.$what;
3313: unless ($env{'request.course.id'}) { return ''; }
3314: $coursedombuf{$env{'request.course.id'}}=
3315: $env{'course.'.$env{'request.course.id'}.'.domain'};
3316: $coursenumbuf{$env{'request.course.id'}}=
3317: $env{'course.'.$env{'request.course.id'}.'.num'};
3318: $coursehombuf{$env{'request.course.id'}}=
3319: $env{'course.'.$env{'request.course.id'}.'.home'};
3320: $coursedescrbuf{$env{'request.course.id'}}=
3321: $env{'course.'.$env{'request.course.id'}.'.description'};
3322: $courseinstcodebuf{$env{'request.course.id'}}=
3323: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3324: $courseownerbuf{$env{'request.course.id'}}=
3325: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3326: $coursetypebuf{$env{'request.course.id'}}=
3327: $env{'course.'.$env{'request.course.id'}.'.type'};
3328: if (defined $courselogs{$env{'request.course.id'}}) {
3329: $courselogs{$env{'request.course.id'}}.='&'.$what;
3330: } else {
3331: $courselogs{$env{'request.course.id'}}.=$what;
3332: }
3333: if (length($courselogs{$env{'request.course.id'}})>4048) {
3334: &flushcourselogs();
3335: }
3336: }
3337:
3338: sub courseacclog {
3339: my $fnsymb=shift;
3340: unless ($env{'request.course.id'}) { return ''; }
3341: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3342: if ($fnsymb=~/$LONCAPA::assess_re/) {
3343: $what.=':POST';
3344: # FIXME: Probably ought to escape things....
3345: foreach my $key (keys(%env)) {
3346: if ($key=~/^form\.(.*)/) {
3347: my $formitem = $1;
3348: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3349: $what.=':'.$formitem.'='.$env{$key};
3350: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3351: $what.=':'.$formitem.'='.$env{$key};
3352: }
3353: }
3354: }
3355: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3356: # FIXME: We should not be depending on a form parameter that someone
3357: # editing lonsearchcat.pm might change in the future.
3358: if ($env{'form.phase'} eq 'course_search') {
3359: $what.= ':POST';
3360: # FIXME: Probably ought to escape things....
3361: foreach my $element ('courseexp','crsfulltext','crsrelated',
3362: 'crsdiscuss') {
3363: $what.=':'.$element.'='.$env{'form.'.$element};
3364: }
3365: }
3366: }
3367: &courselog($what);
3368: }
3369:
3370: sub countacc {
3371: my $url=&declutter(shift);
3372: return if (! defined($url) || $url eq '');
3373: unless ($env{'request.course.id'}) { return ''; }
3374: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3375: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3376: $accesshash{$key}++;
3377: }
3378:
3379: sub linklog {
3380: my ($from,$to)=@_;
3381: $from=&declutter($from);
3382: $to=&declutter($to);
3383: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3384: $accesshash{$to.'___'.$from.'___goto'}=1;
3385: }
3386:
3387: sub userrolelog {
3388: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3389: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
3390: ($trole=~/^in/) || ($trole=~/^cc/) ||
3391: ($trole=~/^ep/) || ($trole=~/^cr/) ||
3392: ($trole=~/^ta/) || ($trole=~/^co/)) {
3393: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3394: $userrolehash
3395: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3396: =$tend.':'.$tstart;
3397: }
3398: if (($env{'request.role'} =~ /dc\./) &&
3399: (($trole=~/^au/) || ($trole=~/^in/) ||
3400: ($trole=~/^cc/) || ($trole=~/^ep/) ||
3401: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3402: ($trole=~/^co/))) {
3403: $userrolehash
3404: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3405: =$tend.':'.$tstart;
3406: }
3407: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3408: ($trole=~/^li/) || ($trole=~/^li/) ||
3409: ($trole=~/^au/) || ($trole=~/^dg/) ||
3410: ($trole=~/^sc/)) {
3411: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3412: $domainrolehash
3413: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3414: = $tend.':'.$tstart;
3415: }
3416: }
3417:
3418: sub courserolelog {
3419: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3420: if (($trole eq 'cc') || ($trole eq 'in') ||
3421: ($trole eq 'ep') || ($trole eq 'ad') ||
3422: ($trole eq 'ta') || ($trole eq 'st') ||
3423: ($trole=~/^cr/) || ($trole eq 'gr') ||
3424: ($trole eq 'co')) {
3425: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3426: my $cdom = $1;
3427: my $cnum = $2;
3428: my $sec = $3;
3429: my $namespace = 'rolelog';
3430: my %storehash = (
3431: role => $trole,
3432: start => $tstart,
3433: end => $tend,
3434: selfenroll => $selfenroll,
3435: context => $context,
3436: );
3437: if ($trole eq 'gr') {
3438: $namespace = 'groupslog';
3439: $storehash{'group'} = $sec;
3440: } else {
3441: $storehash{'section'} = $sec;
3442: }
3443: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3444: if (($trole ne 'st') || ($sec ne '')) {
3445: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3446: }
3447: }
3448: }
3449: return;
3450: }
3451:
3452: sub get_course_adv_roles {
3453: my ($cid,$codes) = @_;
3454: $cid=$env{'request.course.id'} unless (defined($cid));
3455: my %coursehash=&coursedescription($cid);
3456: my $crstype = &Apache::loncommon::course_type($cid);
3457: my %nothide=();
3458: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3459: if ($user !~ /:/) {
3460: $nothide{join(':',split(/[\@]/,$user))}=1;
3461: } else {
3462: $nothide{$user}=1;
3463: }
3464: }
3465: my %returnhash=();
3466: my %dumphash=
3467: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3468: my $now=time;
3469: my %privileged;
3470: foreach my $entry (keys(%dumphash)) {
3471: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3472: if (($tstart) && ($tstart<0)) { next; }
3473: if (($tend) && ($tend<$now)) { next; }
3474: if (($tstart) && ($now<$tstart)) { next; }
3475: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3476: if ($username eq '' || $domain eq '') { next; }
3477: unless (ref($privileged{$domain}) eq 'HASH') {
3478: my %dompersonnel =
3479: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3480: $privileged{$domain} = {};
3481: foreach my $server (keys(%dompersonnel)) {
3482: if (ref($dompersonnel{$server}) eq 'HASH') {
3483: foreach my $user (keys(%{$dompersonnel{$server}})) {
3484: my ($trole,$uname,$udom) = split(/:/,$user);
3485: $privileged{$udom}{$uname} = 1;
3486: }
3487: }
3488: }
3489: }
3490: if ((exists($privileged{$domain}{$username})) &&
3491: (!$nothide{$username.':'.$domain})) { next; }
3492: if ($role eq 'cr') { next; }
3493: if ($codes) {
3494: if ($section) { $role .= ':'.$section; }
3495: if ($returnhash{$role}) {
3496: $returnhash{$role}.=','.$username.':'.$domain;
3497: } else {
3498: $returnhash{$role}=$username.':'.$domain;
3499: }
3500: } else {
3501: my $key=&plaintext($role,$crstype);
3502: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3503: if ($returnhash{$key}) {
3504: $returnhash{$key}.=','.$username.':'.$domain;
3505: } else {
3506: $returnhash{$key}=$username.':'.$domain;
3507: }
3508: }
3509: }
3510: return %returnhash;
3511: }
3512:
3513: sub get_my_roles {
3514: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3515: unless (defined($uname)) { $uname=$env{'user.name'}; }
3516: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3517: my (%dumphash,%nothide);
3518: if ($context eq 'userroles') {
3519: my $extra = &freeze_escape({'skipcheck' => 1});
3520: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
3521: } else {
3522: %dumphash=
3523: &dump('nohist_userroles',$udom,$uname);
3524: if ($hidepriv) {
3525: my %coursehash=&coursedescription($udom.'_'.$uname);
3526: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3527: if ($user !~ /:/) {
3528: $nothide{join(':',split(/[\@]/,$user))} = 1;
3529: } else {
3530: $nothide{$user} = 1;
3531: }
3532: }
3533: }
3534: }
3535: my %returnhash=();
3536: my $now=time;
3537: my %privileged;
3538: foreach my $entry (keys(%dumphash)) {
3539: my ($role,$tend,$tstart);
3540: if ($context eq 'userroles') {
3541: next if ($entry =~ /^rolesdef/);
3542: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3543: } else {
3544: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3545: }
3546: if (($tstart) && ($tstart<0)) { next; }
3547: my $status = 'active';
3548: if (($tend) && ($tend<=$now)) {
3549: $status = 'previous';
3550: }
3551: if (($tstart) && ($now<$tstart)) {
3552: $status = 'future';
3553: }
3554: if (ref($types) eq 'ARRAY') {
3555: if (!grep(/^\Q$status\E$/,@{$types})) {
3556: next;
3557: }
3558: } else {
3559: if ($status ne 'active') {
3560: next;
3561: }
3562: }
3563: my ($rolecode,$username,$domain,$section,$area);
3564: if ($context eq 'userroles') {
3565: ($area,$rolecode) = split(/_/,$entry);
3566: (undef,$domain,$username,$section) = split(/\//,$area);
3567: } else {
3568: ($role,$username,$domain,$section) = split(/\:/,$entry);
3569: }
3570: if (ref($roledoms) eq 'ARRAY') {
3571: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3572: next;
3573: }
3574: }
3575: if (ref($roles) eq 'ARRAY') {
3576: if (!grep(/^\Q$role\E$/,@{$roles})) {
3577: if ($role =~ /^cr\//) {
3578: if (!grep(/^cr$/,@{$roles})) {
3579: next;
3580: }
3581: } elsif ($role =~ /^gr\//) {
3582: if (!grep(/^gr$/,@{$roles})) {
3583: next;
3584: }
3585: } else {
3586: next;
3587: }
3588: }
3589: }
3590: if ($hidepriv) {
3591: if ($context eq 'userroles') {
3592: if ((&privileged($username,$domain)) &&
3593: (!$nothide{$username.':'.$domain})) {
3594: next;
3595: }
3596: } else {
3597: unless (ref($privileged{$domain}) eq 'HASH') {
3598: my %dompersonnel =
3599: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3600: $privileged{$domain} = {};
3601: if (keys(%dompersonnel)) {
3602: foreach my $server (keys(%dompersonnel)) {
3603: if (ref($dompersonnel{$server}) eq 'HASH') {
3604: foreach my $user (keys(%{$dompersonnel{$server}})) {
3605: my ($trole,$uname,$udom) = split(/:/,$user);
3606: $privileged{$udom}{$uname} = $trole;
3607: }
3608: }
3609: }
3610: }
3611: }
3612: if (exists($privileged{$domain}{$username})) {
3613: if (!$nothide{$username.':'.$domain}) {
3614: next;
3615: }
3616: }
3617: }
3618: }
3619: if ($withsec) {
3620: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3621: $tstart.':'.$tend;
3622: } else {
3623: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3624: }
3625: }
3626: return %returnhash;
3627: }
3628:
3629: # ----------------------------------------------------- Frontpage Announcements
3630: #
3631: #
3632:
3633: sub postannounce {
3634: my ($server,$text)=@_;
3635: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3636: unless ($text=~/\w/) { $text=''; }
3637: return &reply('setannounce:'.&escape($text),$server);
3638: }
3639:
3640: sub getannounce {
3641:
3642: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3643: my $announcement='';
3644: while (my $line = <$fh>) { $announcement .= $line; }
3645: close($fh);
3646: if ($announcement=~/\w/) {
3647: return
3648: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3649: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3650: } else {
3651: return '';
3652: }
3653: } else {
3654: return '';
3655: }
3656: }
3657:
3658: # ---------------------------------------------------------- Course ID routines
3659: # Deal with domain's nohist_courseid.db files
3660: #
3661:
3662: sub courseidput {
3663: my ($domain,$storehash,$coursehome,$caller) = @_;
3664: return unless (ref($storehash) eq 'HASH');
3665: my $outcome;
3666: if ($caller eq 'timeonly') {
3667: my $cids = '';
3668: foreach my $item (keys(%$storehash)) {
3669: $cids.=&escape($item).'&';
3670: }
3671: $cids=~s/\&$//;
3672: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3673: $coursehome);
3674: } else {
3675: my $items = '';
3676: foreach my $item (keys(%$storehash)) {
3677: $items.= &escape($item).'='.
3678: &freeze_escape($$storehash{$item}).'&';
3679: }
3680: $items=~s/\&$//;
3681: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3682: $coursehome);
3683: }
3684: if ($outcome eq 'unknown_cmd') {
3685: my $what;
3686: foreach my $cid (keys(%$storehash)) {
3687: $what .= &escape($cid).'=';
3688: foreach my $item ('description','inst_code','owner','type') {
3689: $what .= &escape($storehash->{$cid}{$item}).':';
3690: }
3691: $what =~ s/\:$/&/;
3692: }
3693: $what =~ s/\&$//;
3694: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3695: } else {
3696: return $outcome;
3697: }
3698: }
3699:
3700: sub courseiddump {
3701: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3702: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3703: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3704: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3705: my $as_hash = 1;
3706: my %returnhash;
3707: if (!$domfilter) { $domfilter=''; }
3708: my %libserv = &all_library();
3709: foreach my $tryserver (keys(%libserv)) {
3710: if ( ( $hostidflag == 1
3711: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3712: || (!defined($hostidflag)) ) {
3713:
3714: if (($domfilter eq '') ||
3715: (&host_domain($tryserver) eq $domfilter)) {
3716: my $rep =
3717: &reply('courseiddump:'.&host_domain($tryserver).':'.
3718: $sincefilter.':'.&escape($descfilter).':'.
3719: &escape($instcodefilter).':'.&escape($ownerfilter).
3720: ':'.&escape($coursefilter).':'.&escape($typefilter).
3721: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3722: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3723: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3724: &escape($cc_clone).':'.$cloneonly.':'.
3725: &escape($createdbefore).':'.&escape($createdafter).':'.
3726: &escape($creationcontext).':'.$domcloner,
3727: $tryserver);
3728: my @pairs=split(/\&/,$rep);
3729: foreach my $item (@pairs) {
3730: my ($key,$value)=split(/\=/,$item,2);
3731: $key = &unescape($key);
3732: next if ($key =~ /^error: 2 /);
3733: my $result = &thaw_unescape($value);
3734: if (ref($result) eq 'HASH') {
3735: $returnhash{$key}=$result;
3736: } else {
3737: my @responses = split(/:/,$value);
3738: my @items = ('description','inst_code','owner','type');
3739: for (my $i=0; $i<@responses; $i++) {
3740: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3741: }
3742: }
3743: }
3744: }
3745: }
3746: }
3747: return %returnhash;
3748: }
3749:
3750: sub courselastaccess {
3751: my ($cdom,$cnum,$hostidref) = @_;
3752: my %returnhash;
3753: if ($cdom && $cnum) {
3754: my $chome = &homeserver($cnum,$cdom);
3755: if ($chome ne 'no_host') {
3756: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3757: &extract_lastaccess(\%returnhash,$rep);
3758: }
3759: } else {
3760: if (!$cdom) { $cdom=''; }
3761: my %libserv = &all_library();
3762: foreach my $tryserver (keys(%libserv)) {
3763: if (ref($hostidref) eq 'ARRAY') {
3764: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3765: }
3766: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3767: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3768: &extract_lastaccess(\%returnhash,$rep);
3769: }
3770: }
3771: }
3772: return %returnhash;
3773: }
3774:
3775: sub extract_lastaccess {
3776: my ($returnhash,$rep) = @_;
3777: if (ref($returnhash) eq 'HASH') {
3778: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3779: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3780: $rep eq '') {
3781: my @pairs=split(/\&/,$rep);
3782: foreach my $item (@pairs) {
3783: my ($key,$value)=split(/\=/,$item,2);
3784: $key = &unescape($key);
3785: next if ($key =~ /^error: 2 /);
3786: $returnhash->{$key} = &thaw_unescape($value);
3787: }
3788: }
3789: }
3790: return;
3791: }
3792:
3793: # ---------------------------------------------------------- DC e-mail
3794:
3795: sub dcmailput {
3796: my ($domain,$msgid,$message,$server)=@_;
3797: my $status = &Apache::lonnet::critical(
3798: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3799: &escape($message),$server);
3800: return $status;
3801: }
3802:
3803: sub dcmaildump {
3804: my ($dom,$startdate,$enddate,$senders) = @_;
3805: my %returnhash=();
3806:
3807: if (defined(&domain($dom,'primary'))) {
3808: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3809: &escape($enddate).':';
3810: my @esc_senders=map { &escape($_)} @$senders;
3811: $cmd.=&escape(join('&',@esc_senders));
3812: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3813: my ($key,$value) = split(/\=/,$line,2);
3814: if (($key) && ($value)) {
3815: $returnhash{&unescape($key)} = &unescape($value);
3816: }
3817: }
3818: }
3819: return %returnhash;
3820: }
3821: # ---------------------------------------------------------- Domain roles
3822:
3823: sub get_domain_roles {
3824: my ($dom,$roles,$startdate,$enddate)=@_;
3825: if ((!defined($startdate)) || ($startdate eq '')) {
3826: $startdate = '.';
3827: }
3828: if ((!defined($enddate)) || ($enddate eq '')) {
3829: $enddate = '.';
3830: }
3831: my $rolelist;
3832: if (ref($roles) eq 'ARRAY') {
3833: $rolelist = join(':',@{$roles});
3834: }
3835: my %personnel = ();
3836:
3837: my %servers = &get_servers($dom,'library');
3838: foreach my $tryserver (keys(%servers)) {
3839: %{$personnel{$tryserver}}=();
3840: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3841: &escape($startdate).':'.
3842: &escape($enddate).':'.
3843: &escape($rolelist), $tryserver))) {
3844: my ($key,$value) = split(/\=/,$line,2);
3845: if (($key) && ($value)) {
3846: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3847: }
3848: }
3849: }
3850: return %personnel;
3851: }
3852:
3853: # ----------------------------------------------------------- Interval timing
3854:
3855: sub get_first_access {
3856: my ($type,$argsymb)=@_;
3857: my ($symb,$courseid,$udom,$uname)=&whichuser();
3858: if ($argsymb) { $symb=$argsymb; }
3859: my ($map,$id,$res)=&decode_symb($symb);
3860: if ($type eq 'course') {
3861: $res='course';
3862: } elsif ($type eq 'map') {
3863: $res=&symbread($map);
3864: } else {
3865: $res=$symb;
3866: }
3867: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3868: return $times{"$courseid\0$res"};
3869: }
3870:
3871: sub set_first_access {
3872: my ($type)=@_;
3873: my ($symb,$courseid,$udom,$uname)=&whichuser();
3874: my ($map,$id,$res)=&decode_symb($symb);
3875: if ($type eq 'course') {
3876: $res='course';
3877: } elsif ($type eq 'map') {
3878: $res=&symbread($map);
3879: } else {
3880: $res=$symb;
3881: }
3882: my $firstaccess=&get_first_access($type,$symb);
3883: if (!$firstaccess) {
3884: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3885: }
3886: return 'already_set';
3887: }
3888:
3889: # --------------------------------------------- Set Expire Date for Spreadsheet
3890:
3891: sub expirespread {
3892: my ($uname,$udom,$stype,$usymb)=@_;
3893: my $cid=$env{'request.course.id'};
3894: if ($cid) {
3895: my $now=time;
3896: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3897: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3898: $env{'course.'.$cid.'.num'}.
3899: ':nohist_expirationdates:'.
3900: &escape($key).'='.$now,
3901: $env{'course.'.$cid.'.home'})
3902: }
3903: return 'ok';
3904: }
3905:
3906: # ----------------------------------------------------- Devalidate Spreadsheets
3907:
3908: sub devalidate {
3909: my ($symb,$uname,$udom)=@_;
3910: my $cid=$env{'request.course.id'};
3911: if ($cid) {
3912: # delete the stored spreadsheets for
3913: # - the student level sheet of this user in course's homespace
3914: # - the assessment level sheet for this resource
3915: # for this user in user's homespace
3916: # - current conditional state info
3917: my $key=$uname.':'.$udom.':';
3918: my $status=
3919: &del('nohist_calculatedsheets',
3920: [$key.'studentcalc:'],
3921: $env{'course.'.$cid.'.domain'},
3922: $env{'course.'.$cid.'.num'})
3923: .' '.
3924: &del('nohist_calculatedsheets_'.$cid,
3925: [$key.'assesscalc:'.$symb],$udom,$uname);
3926: unless ($status eq 'ok ok') {
3927: &logthis('Could not devalidate spreadsheet '.
3928: $uname.' at '.$udom.' for '.
3929: $symb.': '.$status);
3930: }
3931: &delenv('user.state.'.$cid);
3932: }
3933: }
3934:
3935: sub get_scalar {
3936: my ($string,$end) = @_;
3937: my $value;
3938: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3939: $value = $1;
3940: } elsif ($$string =~ s/^([^&]*?)&//) {
3941: $value = $1;
3942: }
3943: return &unescape($value);
3944: }
3945:
3946: sub array2str {
3947: my (@array) = @_;
3948: my $result=&arrayref2str(\@array);
3949: $result=~s/^__ARRAY_REF__//;
3950: $result=~s/__END_ARRAY_REF__$//;
3951: return $result;
3952: }
3953:
3954: sub arrayref2str {
3955: my ($arrayref) = @_;
3956: my $result='__ARRAY_REF__';
3957: foreach my $elem (@$arrayref) {
3958: if(ref($elem) eq 'ARRAY') {
3959: $result.=&arrayref2str($elem).'&';
3960: } elsif(ref($elem) eq 'HASH') {
3961: $result.=&hashref2str($elem).'&';
3962: } elsif(ref($elem)) {
3963: #print("Got a ref of ".(ref($elem))." skipping.");
3964: } else {
3965: $result.=&escape($elem).'&';
3966: }
3967: }
3968: $result=~s/\&$//;
3969: $result .= '__END_ARRAY_REF__';
3970: return $result;
3971: }
3972:
3973: sub hash2str {
3974: my (%hash) = @_;
3975: my $result=&hashref2str(\%hash);
3976: $result=~s/^__HASH_REF__//;
3977: $result=~s/__END_HASH_REF__$//;
3978: return $result;
3979: }
3980:
3981: sub hashref2str {
3982: my ($hashref)=@_;
3983: my $result='__HASH_REF__';
3984: foreach my $key (sort(keys(%$hashref))) {
3985: if (ref($key) eq 'ARRAY') {
3986: $result.=&arrayref2str($key).'=';
3987: } elsif (ref($key) eq 'HASH') {
3988: $result.=&hashref2str($key).'=';
3989: } elsif (ref($key)) {
3990: $result.='=';
3991: #print("Got a ref of ".(ref($key))." skipping.");
3992: } else {
3993: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
3994: }
3995:
3996: if(ref($hashref->{$key}) eq 'ARRAY') {
3997: $result.=&arrayref2str($hashref->{$key}).'&';
3998: } elsif(ref($hashref->{$key}) eq 'HASH') {
3999: $result.=&hashref2str($hashref->{$key}).'&';
4000: } elsif(ref($hashref->{$key})) {
4001: $result.='&';
4002: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4003: } else {
4004: $result.=&escape($hashref->{$key}).'&';
4005: }
4006: }
4007: $result=~s/\&$//;
4008: $result .= '__END_HASH_REF__';
4009: return $result;
4010: }
4011:
4012: sub str2hash {
4013: my ($string)=@_;
4014: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4015: return %$hash;
4016: }
4017:
4018: sub str2hashref {
4019: my ($string) = @_;
4020:
4021: my %hash;
4022:
4023: if($string !~ /^__HASH_REF__/) {
4024: if (! ($string eq '' || !defined($string))) {
4025: $hash{'error'}='Not hash reference';
4026: }
4027: return (\%hash, $string);
4028: }
4029:
4030: $string =~ s/^__HASH_REF__//;
4031:
4032: while($string !~ /^__END_HASH_REF__/) {
4033: #key
4034: my $key='';
4035: if($string =~ /^__HASH_REF__/) {
4036: ($key, $string)=&str2hashref($string);
4037: if(defined($key->{'error'})) {
4038: $hash{'error'}='Bad data';
4039: return (\%hash, $string);
4040: }
4041: } elsif($string =~ /^__ARRAY_REF__/) {
4042: ($key, $string)=&str2arrayref($string);
4043: if($key->[0] eq 'Array reference error') {
4044: $hash{'error'}='Bad data';
4045: return (\%hash, $string);
4046: }
4047: } else {
4048: $string =~ s/^(.*?)=//;
4049: $key=&unescape($1);
4050: }
4051: $string =~ s/^=//;
4052:
4053: #value
4054: my $value='';
4055: if($string =~ /^__HASH_REF__/) {
4056: ($value, $string)=&str2hashref($string);
4057: if(defined($value->{'error'})) {
4058: $hash{'error'}='Bad data';
4059: return (\%hash, $string);
4060: }
4061: } elsif($string =~ /^__ARRAY_REF__/) {
4062: ($value, $string)=&str2arrayref($string);
4063: if($value->[0] eq 'Array reference error') {
4064: $hash{'error'}='Bad data';
4065: return (\%hash, $string);
4066: }
4067: } else {
4068: $value=&get_scalar(\$string,'__END_HASH_REF__');
4069: }
4070: $string =~ s/^&//;
4071:
4072: $hash{$key}=$value;
4073: }
4074:
4075: $string =~ s/^__END_HASH_REF__//;
4076:
4077: return (\%hash, $string);
4078: }
4079:
4080: sub str2array {
4081: my ($string)=@_;
4082: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4083: return @$array;
4084: }
4085:
4086: sub str2arrayref {
4087: my ($string) = @_;
4088: my @array;
4089:
4090: if($string !~ /^__ARRAY_REF__/) {
4091: if (! ($string eq '' || !defined($string))) {
4092: $array[0]='Array reference error';
4093: }
4094: return (\@array, $string);
4095: }
4096:
4097: $string =~ s/^__ARRAY_REF__//;
4098:
4099: while($string !~ /^__END_ARRAY_REF__/) {
4100: my $value='';
4101: if($string =~ /^__HASH_REF__/) {
4102: ($value, $string)=&str2hashref($string);
4103: if(defined($value->{'error'})) {
4104: $array[0] ='Array reference error';
4105: return (\@array, $string);
4106: }
4107: } elsif($string =~ /^__ARRAY_REF__/) {
4108: ($value, $string)=&str2arrayref($string);
4109: if($value->[0] eq 'Array reference error') {
4110: $array[0] ='Array reference error';
4111: return (\@array, $string);
4112: }
4113: } else {
4114: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4115: }
4116: $string =~ s/^&//;
4117:
4118: push(@array, $value);
4119: }
4120:
4121: $string =~ s/^__END_ARRAY_REF__//;
4122:
4123: return (\@array, $string);
4124: }
4125:
4126: # -------------------------------------------------------------------Temp Store
4127:
4128: sub tmpreset {
4129: my ($symb,$namespace,$domain,$stuname) = @_;
4130: if (!$symb) {
4131: $symb=&symbread();
4132: if (!$symb) { $symb= $env{'request.url'}; }
4133: }
4134: $symb=escape($symb);
4135:
4136: if (!$namespace) { $namespace=$env{'request.state'}; }
4137: $namespace=~s/\//\_/g;
4138: $namespace=~s/\W//g;
4139:
4140: if (!$domain) { $domain=$env{'user.domain'}; }
4141: if (!$stuname) { $stuname=$env{'user.name'}; }
4142: if ($domain eq 'public' && $stuname eq 'public') {
4143: $stuname=$ENV{'REMOTE_ADDR'};
4144: }
4145: my $path=LONCAPA::tempdir();
4146: my %hash;
4147: if (tie(%hash,'GDBM_File',
4148: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4149: &GDBM_WRCREAT(),0640)) {
4150: foreach my $key (keys(%hash)) {
4151: if ($key=~ /:$symb/) {
4152: delete($hash{$key});
4153: }
4154: }
4155: }
4156: }
4157:
4158: sub tmpstore {
4159: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4160:
4161: if (!$symb) {
4162: $symb=&symbread();
4163: if (!$symb) { $symb= $env{'request.url'}; }
4164: }
4165: $symb=escape($symb);
4166:
4167: if (!$namespace) {
4168: # I don't think we would ever want to store this for a course.
4169: # it seems this will only be used if we don't have a course.
4170: #$namespace=$env{'request.course.id'};
4171: #if (!$namespace) {
4172: $namespace=$env{'request.state'};
4173: #}
4174: }
4175: $namespace=~s/\//\_/g;
4176: $namespace=~s/\W//g;
4177: if (!$domain) { $domain=$env{'user.domain'}; }
4178: if (!$stuname) { $stuname=$env{'user.name'}; }
4179: if ($domain eq 'public' && $stuname eq 'public') {
4180: $stuname=$ENV{'REMOTE_ADDR'};
4181: }
4182: my $now=time;
4183: my %hash;
4184: my $path=LONCAPA::tempdir();
4185: if (tie(%hash,'GDBM_File',
4186: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4187: &GDBM_WRCREAT(),0640)) {
4188: $hash{"version:$symb"}++;
4189: my $version=$hash{"version:$symb"};
4190: my $allkeys='';
4191: foreach my $key (keys(%$storehash)) {
4192: $allkeys.=$key.':';
4193: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4194: }
4195: $hash{"$version:$symb:timestamp"}=$now;
4196: $allkeys.='timestamp';
4197: $hash{"$version:keys:$symb"}=$allkeys;
4198: if (untie(%hash)) {
4199: return 'ok';
4200: } else {
4201: return "error:$!";
4202: }
4203: } else {
4204: return "error:$!";
4205: }
4206: }
4207:
4208: # -----------------------------------------------------------------Temp Restore
4209:
4210: sub tmprestore {
4211: my ($symb,$namespace,$domain,$stuname) = @_;
4212:
4213: if (!$symb) {
4214: $symb=&symbread();
4215: if (!$symb) { $symb= $env{'request.url'}; }
4216: }
4217: $symb=escape($symb);
4218:
4219: if (!$namespace) { $namespace=$env{'request.state'}; }
4220:
4221: if (!$domain) { $domain=$env{'user.domain'}; }
4222: if (!$stuname) { $stuname=$env{'user.name'}; }
4223: if ($domain eq 'public' && $stuname eq 'public') {
4224: $stuname=$ENV{'REMOTE_ADDR'};
4225: }
4226: my %returnhash;
4227: $namespace=~s/\//\_/g;
4228: $namespace=~s/\W//g;
4229: my %hash;
4230: my $path=LONCAPA::tempdir();
4231: if (tie(%hash,'GDBM_File',
4232: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4233: &GDBM_READER(),0640)) {
4234: my $version=$hash{"version:$symb"};
4235: $returnhash{'version'}=$version;
4236: my $scope;
4237: for ($scope=1;$scope<=$version;$scope++) {
4238: my $vkeys=$hash{"$scope:keys:$symb"};
4239: my @keys=split(/:/,$vkeys);
4240: my $key;
4241: $returnhash{"$scope:keys"}=$vkeys;
4242: foreach $key (@keys) {
4243: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4244: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4245: }
4246: }
4247: if (!(untie(%hash))) {
4248: return "error:$!";
4249: }
4250: } else {
4251: return "error:$!";
4252: }
4253: return %returnhash;
4254: }
4255:
4256: # ----------------------------------------------------------------------- Store
4257:
4258: sub store {
4259: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4260: my $home='';
4261:
4262: if ($stuname) { $home=&homeserver($stuname,$domain); }
4263:
4264: $symb=&symbclean($symb);
4265: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4266:
4267: if (!$domain) { $domain=$env{'user.domain'}; }
4268: if (!$stuname) { $stuname=$env{'user.name'}; }
4269:
4270: &devalidate($symb,$stuname,$domain);
4271:
4272: $symb=escape($symb);
4273: if (!$namespace) {
4274: unless ($namespace=$env{'request.course.id'}) {
4275: return '';
4276: }
4277: }
4278: if (!$home) { $home=$env{'user.home'}; }
4279:
4280: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4281: $$storehash{'host'}=$perlvar{'lonHostID'};
4282:
4283: my $namevalue='';
4284: foreach my $key (keys(%$storehash)) {
4285: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4286: }
4287: $namevalue=~s/\&$//;
4288: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4289: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4290: }
4291:
4292: # -------------------------------------------------------------- Critical Store
4293:
4294: sub cstore {
4295: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4296: my $home='';
4297:
4298: if ($stuname) { $home=&homeserver($stuname,$domain); }
4299:
4300: $symb=&symbclean($symb);
4301: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4302:
4303: if (!$domain) { $domain=$env{'user.domain'}; }
4304: if (!$stuname) { $stuname=$env{'user.name'}; }
4305:
4306: &devalidate($symb,$stuname,$domain);
4307:
4308: $symb=escape($symb);
4309: if (!$namespace) {
4310: unless ($namespace=$env{'request.course.id'}) {
4311: return '';
4312: }
4313: }
4314: if (!$home) { $home=$env{'user.home'}; }
4315:
4316: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4317: $$storehash{'host'}=$perlvar{'lonHostID'};
4318:
4319: my $namevalue='';
4320: foreach my $key (keys(%$storehash)) {
4321: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4322: }
4323: $namevalue=~s/\&$//;
4324: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4325: return critical
4326: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4327: }
4328:
4329: # --------------------------------------------------------------------- Restore
4330:
4331: sub restore {
4332: my ($symb,$namespace,$domain,$stuname) = @_;
4333: my $home='';
4334:
4335: if ($stuname) { $home=&homeserver($stuname,$domain); }
4336:
4337: if (!$symb) {
4338: unless ($symb=escape(&symbread())) { return ''; }
4339: } else {
4340: $symb=&escape(&symbclean($symb));
4341: }
4342: if (!$namespace) {
4343: unless ($namespace=$env{'request.course.id'}) {
4344: return '';
4345: }
4346: }
4347: if (!$domain) { $domain=$env{'user.domain'}; }
4348: if (!$stuname) { $stuname=$env{'user.name'}; }
4349: if (!$home) { $home=$env{'user.home'}; }
4350: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4351:
4352: my %returnhash=();
4353: foreach my $line (split(/\&/,$answer)) {
4354: my ($name,$value)=split(/\=/,$line);
4355: $returnhash{&unescape($name)}=&thaw_unescape($value);
4356: }
4357: my $version;
4358: for ($version=1;$version<=$returnhash{'version'};$version++) {
4359: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4360: $returnhash{$item}=$returnhash{$version.':'.$item};
4361: }
4362: }
4363: return %returnhash;
4364: }
4365:
4366: # ---------------------------------------------------------- Course Description
4367: #
4368: #
4369:
4370: sub coursedescription {
4371: my ($courseid,$args)=@_;
4372: $courseid=~s/^\///;
4373: $courseid=~s/\_/\//g;
4374: my ($cdomain,$cnum)=split(/\//,$courseid);
4375: my $chome=&homeserver($cnum,$cdomain);
4376: my $normalid=$cdomain.'_'.$cnum;
4377: # need to always cache even if we get errors otherwise we keep
4378: # trying and trying and trying to get the course description.
4379: my %envhash=();
4380: my %returnhash=();
4381:
4382: my $expiretime=600;
4383: if ($env{'request.course.id'} eq $normalid) {
4384: $expiretime=120;
4385: }
4386:
4387: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4388: if (!$args->{'freshen_cache'}
4389: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4390: foreach my $key (keys(%env)) {
4391: next if ($key !~ /^\Q$prefix\E(.*)/);
4392: my ($setting) = $1;
4393: $returnhash{$setting} = $env{$key};
4394: }
4395: return %returnhash;
4396: }
4397:
4398: # get the data again
4399:
4400: if (!$args->{'one_time'}) {
4401: $envhash{'course.'.$normalid.'.last_cache'}=time;
4402: }
4403:
4404: if ($chome ne 'no_host') {
4405: %returnhash=&dump('environment',$cdomain,$cnum);
4406: if (!exists($returnhash{'con_lost'})) {
4407: my $username = $env{'user.name'}; # Defult username
4408: if(defined $args->{'user'}) {
4409: $username = $args->{'user'};
4410: }
4411: $returnhash{'home'}= $chome;
4412: $returnhash{'domain'} = $cdomain;
4413: $returnhash{'num'} = $cnum;
4414: if (!defined($returnhash{'type'})) {
4415: $returnhash{'type'} = 'Course';
4416: }
4417: while (my ($name,$value) = each %returnhash) {
4418: $envhash{'course.'.$normalid.'.'.$name}=$value;
4419: }
4420: $returnhash{'url'}=&clutter($returnhash{'url'});
4421: $returnhash{'fn'}=LONCAPA::tempdir() .
4422: $username.'_'.$cdomain.'_'.$cnum;
4423: $envhash{'course.'.$normalid.'.home'}=$chome;
4424: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4425: $envhash{'course.'.$normalid.'.num'}=$cnum;
4426: }
4427: }
4428: if (!$args->{'one_time'}) {
4429: &appenv(\%envhash);
4430: }
4431: return %returnhash;
4432: }
4433:
4434: sub update_released_required {
4435: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4436: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4437: $cid = $env{'request.course.id'};
4438: $cdom = $env{'course.'.$cid.'.domain'};
4439: $cnum = $env{'course.'.$cid.'.num'};
4440: $chome = $env{'course.'.$cid.'.home'};
4441: }
4442: if ($needsrelease) {
4443: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4444: my $needsupdate;
4445: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4446: $needsupdate = 1;
4447: } else {
4448: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4449: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4450: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4451: $needsupdate = 1;
4452: }
4453: }
4454: if ($needsupdate) {
4455: my %needshash = (
4456: 'internal.releaserequired' => $needsrelease,
4457: );
4458: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4459: if ($putresult eq 'ok') {
4460: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4461: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4462: if (ref($crsinfo{$cid}) eq 'HASH') {
4463: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4464: &courseidput($cdom,\%crsinfo,$chome,'notime');
4465: }
4466: }
4467: }
4468: }
4469: return;
4470: }
4471:
4472: # -------------------------------------------------See if a user is privileged
4473:
4474: sub privileged {
4475: my ($username,$domain)=@_;
4476: my $rolesdump=&reply("dump:$domain:$username:roles",
4477: &homeserver($username,$domain));
4478: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4479: ($rolesdump =~ /^error:/)) {
4480: return 0;
4481: }
4482: my $now=time;
4483: if ($rolesdump ne '') {
4484: foreach my $entry (split(/&/,$rolesdump)) {
4485: if ($entry!~/^rolesdef_/) {
4486: my ($area,$role)=split(/=/,$entry);
4487: $area=~s/\_\w\w$//;
4488: my ($trole,$tend,$tstart)=split(/_/,$role);
4489: if (($trole eq 'dc') || ($trole eq 'su')) {
4490: my $active=1;
4491: if ($tend) {
4492: if ($tend<$now) { $active=0; }
4493: }
4494: if ($tstart) {
4495: if ($tstart>$now) { $active=0; }
4496: }
4497: if ($active) { return 1; }
4498: }
4499: }
4500: }
4501: }
4502: return 0;
4503: }
4504:
4505: # -------------------------------------------------------- Get user privileges
4506:
4507: sub rolesinit {
4508: my ($domain,$username,$authhost)=@_;
4509: my $now=time;
4510: my %userroles = ('user.login.time' => $now);
4511: my $extra = &freeze_escape({'skipcheck' => 1});
4512: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
4513: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4514: ($rolesdump =~ /^error:/)) {
4515: return \%userroles;
4516: }
4517: my %allroles=();
4518: my %allgroups=();
4519:
4520: if ($rolesdump ne '') {
4521: foreach my $entry (split(/&/,$rolesdump)) {
4522: if ($entry!~/^rolesdef_/) {
4523: my ($area,$role)=split(/=/,$entry);
4524: $area=~s/\_\w\w$//;
4525: my ($trole,$tend,$tstart,$group_privs);
4526: if ($role=~/^cr/) {
4527: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4528: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
4529: ($tend,$tstart)=split('_',$trest);
4530: } else {
4531: $trole=$role;
4532: }
4533: } elsif ($role =~ m|^gr/|) {
4534: ($trole,$tend,$tstart) = split(/_/,$role);
4535: next if ($tstart eq '-1');
4536: ($trole,$group_privs) = split(/\//,$trole);
4537: $group_privs = &unescape($group_privs);
4538: } else {
4539: ($trole,$tend,$tstart)=split(/_/,$role);
4540: }
4541: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4542: $username);
4543: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4544: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4545: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
4546: if (($area ne '') && ($trole ne '')) {
4547: my $spec=$trole.'.'.$area;
4548: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4549: if ($trole =~ /^cr\//) {
4550: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4551: } elsif ($trole eq 'gr') {
4552: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4553: } else {
4554: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4555: }
4556: }
4557: }
4558: }
4559: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4560: $userroles{'user.adv'} = $adv;
4561: $userroles{'user.author'} = $author;
4562: $env{'user.adv'}=$adv;
4563: }
4564: return \%userroles;
4565: }
4566:
4567: sub set_arearole {
4568: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4569: # log the associated role with the area
4570: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4571: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4572: }
4573:
4574: sub custom_roleprivs {
4575: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4576: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4577: my $homsvr=homeserver($rauthor,$rdomain);
4578: if (&hostname($homsvr) ne '') {
4579: my ($rdummy,$roledef)=
4580: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4581: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4582: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4583: if (defined($syspriv)) {
4584: if ($trest =~ /^$match_community$/) {
4585: $syspriv =~ s/bre\&S//;
4586: }
4587: $$allroles{'cm./'}.=':'.$syspriv;
4588: $$allroles{$spec.'./'}.=':'.$syspriv;
4589: }
4590: if ($tdomain ne '') {
4591: if (defined($dompriv)) {
4592: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4593: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4594: }
4595: if (($trest ne '') && (defined($coursepriv))) {
4596: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4597: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4598: }
4599: }
4600: }
4601: }
4602: }
4603:
4604: sub group_roleprivs {
4605: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4606: my $access = 1;
4607: my $now = time;
4608: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4609: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4610: if ($access) {
4611: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4612: $$allgroups{$course}{$group} .=':'.$group_privs;
4613: }
4614: }
4615:
4616: sub standard_roleprivs {
4617: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4618: if (defined($pr{$trole.':s'})) {
4619: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4620: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4621: }
4622: if ($tdomain ne '') {
4623: if (defined($pr{$trole.':d'})) {
4624: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4625: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4626: }
4627: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4628: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4629: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4630: }
4631: }
4632: }
4633:
4634: sub set_userprivs {
4635: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4636: my $author=0;
4637: my $adv=0;
4638: my %grouproles = ();
4639: if (keys(%{$allgroups}) > 0) {
4640: my @groupkeys;
4641: foreach my $role (keys(%{$allroles})) {
4642: push(@groupkeys,$role);
4643: }
4644: if (ref($groups_roles) eq 'HASH') {
4645: foreach my $key (keys(%{$groups_roles})) {
4646: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4647: push(@groupkeys,$key);
4648: }
4649: }
4650: }
4651: if (@groupkeys > 0) {
4652: foreach my $role (@groupkeys) {
4653: my ($trole,$area,$sec,$extendedarea);
4654: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4655: $trole = $1;
4656: $area = $2;
4657: $sec = $3;
4658: $extendedarea = $area.$sec;
4659: if (exists($$allgroups{$area})) {
4660: foreach my $group (keys(%{$$allgroups{$area}})) {
4661: my $spec = $trole.'.'.$extendedarea;
4662: $grouproles{$spec.'.'.$area.'/'.$group} =
4663: $$allgroups{$area}{$group};
4664: }
4665: }
4666: }
4667: }
4668: }
4669: }
4670: foreach my $group (keys(%grouproles)) {
4671: $$allroles{$group} = $grouproles{$group};
4672: }
4673: foreach my $role (keys(%{$allroles})) {
4674: my %thesepriv;
4675: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4676: foreach my $item (split(/:/,$$allroles{$role})) {
4677: if ($item ne '') {
4678: my ($privilege,$restrictions)=split(/&/,$item);
4679: if ($restrictions eq '') {
4680: $thesepriv{$privilege}='F';
4681: } elsif ($thesepriv{$privilege} ne 'F') {
4682: $thesepriv{$privilege}.=$restrictions;
4683: }
4684: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4685: }
4686: }
4687: my $thesestr='';
4688: foreach my $priv (sort(keys(%thesepriv))) {
4689: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4690: }
4691: $userroles->{'user.priv.'.$role} = $thesestr;
4692: }
4693: return ($author,$adv);
4694: }
4695:
4696: sub role_status {
4697: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4698: my @pwhere = ();
4699: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4700: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4701: unless (!defined($$role) || $$role eq '') {
4702: $$where=join('.',@pwhere);
4703: $$trolecode=$$role.'.'.$$where;
4704: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4705: $$tstatus='is';
4706: if ($$tstart && $$tstart>$update) {
4707: $$tstatus='future';
4708: if ($$tstart<$now) {
4709: if ($$tstart && $$tstart>$refresh) {
4710: if (($$where ne '') && ($$role ne '')) {
4711: my (%allroles,%allgroups,$group_privs,
4712: %groups_roles,@rolecodes);
4713: my %userroles = (
4714: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4715: );
4716: @rolecodes = ('cm');
4717: my $spec=$$role.'.'.$$where;
4718: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4719: if ($$role =~ /^cr\//) {
4720: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4721: push(@rolecodes,'cr');
4722: } elsif ($$role eq 'gr') {
4723: push(@rolecodes,$$role);
4724: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4725: $env{'user.name'});
4726: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4727: (undef,my $group_privs) = split(/\//,$trole);
4728: $group_privs = &unescape($group_privs);
4729: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4730: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4731: &get_groups_roles($tdomain,$trest,
4732: \%course_roles,\@rolecodes,
4733: \%groups_roles);
4734: } else {
4735: push(@rolecodes,$$role);
4736: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4737: }
4738: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4739: &appenv(\%userroles,\@rolecodes);
4740: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4741: }
4742: }
4743: $$tstatus = 'is';
4744: }
4745: }
4746: if ($$tend) {
4747: if ($$tend<$update) {
4748: $$tstatus='expired';
4749: } elsif ($$tend<$now) {
4750: $$tstatus='will_not';
4751: }
4752: }
4753: }
4754: }
4755: }
4756:
4757: sub get_groups_roles {
4758: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4759: return unless((ref($cdom_courseroles) eq 'HASH') &&
4760: (ref($rolecodes) eq 'ARRAY') &&
4761: (ref($groups_roles) eq 'HASH'));
4762: if (keys(%{$cdom_courseroles}) > 0) {
4763: my ($cnum) = ($rest =~ /^($match_courseid)/);
4764: if ($cdom ne '' && $cnum ne '') {
4765: foreach my $key (keys(%{$cdom_courseroles})) {
4766: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4767: my $crsrole = $1;
4768: my $crssec = $2;
4769: if ($crsrole =~ /^cr/) {
4770: unless (grep(/^cr$/,@{$rolecodes})) {
4771: push(@{$rolecodes},'cr');
4772: }
4773: } else {
4774: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4775: push(@{$rolecodes},$crsrole);
4776: }
4777: }
4778: my $rolekey = "$crsrole./$cdom/$cnum";
4779: if ($crssec ne '') {
4780: $rolekey .= "/$crssec";
4781: }
4782: $rolekey .= './';
4783: $groups_roles->{$rolekey} = $rolecodes;
4784: }
4785: }
4786: }
4787: }
4788: return;
4789: }
4790:
4791: sub delete_env_groupprivs {
4792: my ($where,$courseroles,$possroles) = @_;
4793: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4794: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4795: unless (ref($courseroles->{$udom}) eq 'HASH') {
4796: %{$courseroles->{$udom}} =
4797: &get_my_roles('','','userroles',['active'],
4798: $possroles,[$udom],1);
4799: }
4800: if (ref($courseroles->{$udom}) eq 'HASH') {
4801: foreach my $item (keys(%{$courseroles->{$udom}})) {
4802: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4803: my $area = '/'.$cdom.'/'.$cnum;
4804: my $privkey = "user.priv.$crsrole.$area";
4805: if ($crssec ne '') {
4806: $privkey .= '/'.$crssec;
4807: }
4808: $privkey .= ".$area/$group";
4809: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4810: }
4811: }
4812: return;
4813: }
4814:
4815: sub check_adhoc_privs {
4816: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
4817: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4818: if ($env{$cckey}) {
4819: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4820: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4821: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4822: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4823: }
4824: } else {
4825: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4826: }
4827: }
4828:
4829: sub set_adhoc_privileges {
4830: # role can be cc or ca
4831: my ($dcdom,$pickedcourse,$role,$caller) = @_;
4832: my $area = '/'.$dcdom.'/'.$pickedcourse;
4833: my $spec = $role.'.'.$area;
4834: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4835: $env{'user.name'});
4836: my %ccrole = ();
4837: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4838: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4839: &appenv(\%userroles,[$role,'cm']);
4840: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4841: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4842: &appenv( {'request.role' => $spec,
4843: 'request.role.domain' => $dcdom,
4844: 'request.course.sec' => ''
4845: }
4846: );
4847: my $tadv=0;
4848: if (&allowed('adv') eq 'F') { $tadv=1; }
4849: &appenv({'request.role.adv' => $tadv});
4850: }
4851: }
4852:
4853: # --------------------------------------------------------------- get interface
4854:
4855: sub get {
4856: my ($namespace,$storearr,$udomain,$uname)=@_;
4857: my $items='';
4858: foreach my $item (@$storearr) {
4859: $items.=&escape($item).'&';
4860: }
4861: $items=~s/\&$//;
4862: if (!$udomain) { $udomain=$env{'user.domain'}; }
4863: if (!$uname) { $uname=$env{'user.name'}; }
4864: my $uhome=&homeserver($uname,$udomain);
4865:
4866: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4867: my @pairs=split(/\&/,$rep);
4868: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4869: return @pairs;
4870: }
4871: my %returnhash=();
4872: my $i=0;
4873: foreach my $item (@$storearr) {
4874: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4875: $i++;
4876: }
4877: return %returnhash;
4878: }
4879:
4880: # --------------------------------------------------------------- del interface
4881:
4882: sub del {
4883: my ($namespace,$storearr,$udomain,$uname)=@_;
4884: my $items='';
4885: foreach my $item (@$storearr) {
4886: $items.=&escape($item).'&';
4887: }
4888:
4889: $items=~s/\&$//;
4890: if (!$udomain) { $udomain=$env{'user.domain'}; }
4891: if (!$uname) { $uname=$env{'user.name'}; }
4892: my $uhome=&homeserver($uname,$udomain);
4893: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4894: }
4895:
4896: # -------------------------------------------------------------- dump interface
4897:
4898: sub dump {
4899: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
4900: if (!$udomain) { $udomain=$env{'user.domain'}; }
4901: if (!$uname) { $uname=$env{'user.name'}; }
4902: my $uhome=&homeserver($uname,$udomain);
4903: if ($regexp) {
4904: $regexp=&escape($regexp);
4905: } else {
4906: $regexp='.';
4907: }
4908: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
4909: my @pairs=split(/\&/,$rep);
4910: my %returnhash=();
4911: if (!($rep =~ /^error/ )) {
4912: foreach my $item (@pairs) {
4913: my ($key,$value)=split(/=/,$item,2);
4914: $key = &unescape($key);
4915: next if ($key =~ /^error: 2 /);
4916: $returnhash{$key}=&thaw_unescape($value);
4917: }
4918: }
4919: return %returnhash;
4920: }
4921:
4922:
4923: # --------------------------------------------------------- dumpstore interface
4924:
4925: sub dumpstore {
4926: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4927: if (!$udomain) { $udomain=$env{'user.domain'}; }
4928: if (!$uname) { $uname=$env{'user.name'}; }
4929: my $uhome=&homeserver($uname,$udomain);
4930: if ($regexp) {
4931: $regexp=&escape($regexp);
4932: } else {
4933: $regexp='.';
4934: }
4935: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4936: my @pairs=split(/\&/,$rep);
4937: my %returnhash=();
4938: foreach my $item (@pairs) {
4939: my ($key,$value)=split(/=/,$item,2);
4940: next if ($key =~ /^error: 2 /);
4941: $returnhash{$key}=&thaw_unescape($value);
4942: }
4943: return %returnhash;
4944: }
4945:
4946: # -------------------------------------------------------------- keys interface
4947:
4948: sub getkeys {
4949: my ($namespace,$udomain,$uname)=@_;
4950: if (!$udomain) { $udomain=$env{'user.domain'}; }
4951: if (!$uname) { $uname=$env{'user.name'}; }
4952: my $uhome=&homeserver($uname,$udomain);
4953: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4954: my @keyarray=();
4955: foreach my $key (split(/\&/,$rep)) {
4956: next if ($key =~ /^error: 2 /);
4957: push(@keyarray,&unescape($key));
4958: }
4959: return @keyarray;
4960: }
4961:
4962: # --------------------------------------------------------------- currentdump
4963: sub currentdump {
4964: my ($courseid,$sdom,$sname)=@_;
4965: $courseid = $env{'request.course.id'} if (! defined($courseid));
4966: $sdom = $env{'user.domain'} if (! defined($sdom));
4967: $sname = $env{'user.name'} if (! defined($sname));
4968: my $uhome = &homeserver($sname,$sdom);
4969: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4970: return if ($rep =~ /^(error:|no_such_host)/);
4971: #
4972: my %returnhash=();
4973: #
4974: if ($rep eq "unknown_cmd") {
4975: # an old lond will not know currentdump
4976: # Do a dump and make it look like a currentdump
4977: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4978: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4979: my %hash = @tmp;
4980: @tmp=();
4981: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4982: } else {
4983: my @pairs=split(/\&/,$rep);
4984: foreach my $pair (@pairs) {
4985: my ($key,$value)=split(/=/,$pair,2);
4986: my ($symb,$param) = split(/:/,$key);
4987: $returnhash{&unescape($symb)}->{&unescape($param)} =
4988: &thaw_unescape($value);
4989: }
4990: }
4991: return %returnhash;
4992: }
4993:
4994: sub convert_dump_to_currentdump{
4995: my %hash = %{shift()};
4996: my %returnhash;
4997: # Code ripped from lond, essentially. The only difference
4998: # here is the unescaping done by lonnet::dump(). Conceivably
4999: # we might run in to problems with parameter names =~ /^v\./
5000: while (my ($key,$value) = each(%hash)) {
5001: my ($v,$symb,$param) = split(/:/,$key);
5002: $symb = &unescape($symb);
5003: $param = &unescape($param);
5004: next if ($v eq 'version' || $symb eq 'keys');
5005: next if (exists($returnhash{$symb}) &&
5006: exists($returnhash{$symb}->{$param}) &&
5007: $returnhash{$symb}->{'v.'.$param} > $v);
5008: $returnhash{$symb}->{$param}=$value;
5009: $returnhash{$symb}->{'v.'.$param}=$v;
5010: }
5011: #
5012: # Remove all of the keys in the hashes which keep track of
5013: # the version of the parameter.
5014: while (my ($symb,$param_hash) = each(%returnhash)) {
5015: # use a foreach because we are going to delete from the hash.
5016: foreach my $key (keys(%$param_hash)) {
5017: delete($param_hash->{$key}) if ($key =~ /^v\./);
5018: }
5019: }
5020: return \%returnhash;
5021: }
5022:
5023: # ------------------------------------------------------ critical inc interface
5024:
5025: sub cinc {
5026: return &inc(@_,'critical');
5027: }
5028:
5029: # --------------------------------------------------------------- inc interface
5030:
5031: sub inc {
5032: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5033: if (!$udomain) { $udomain=$env{'user.domain'}; }
5034: if (!$uname) { $uname=$env{'user.name'}; }
5035: my $uhome=&homeserver($uname,$udomain);
5036: my $items='';
5037: if (! ref($store)) {
5038: # got a single value, so use that instead
5039: $items = &escape($store).'=&';
5040: } elsif (ref($store) eq 'SCALAR') {
5041: $items = &escape($$store).'=&';
5042: } elsif (ref($store) eq 'ARRAY') {
5043: $items = join('=&',map {&escape($_);} @{$store});
5044: } elsif (ref($store) eq 'HASH') {
5045: while (my($key,$value) = each(%{$store})) {
5046: $items.= &escape($key).'='.&escape($value).'&';
5047: }
5048: }
5049: $items=~s/\&$//;
5050: if ($critical) {
5051: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5052: } else {
5053: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5054: }
5055: }
5056:
5057: # --------------------------------------------------------------- put interface
5058:
5059: sub put {
5060: my ($namespace,$storehash,$udomain,$uname)=@_;
5061: if (!$udomain) { $udomain=$env{'user.domain'}; }
5062: if (!$uname) { $uname=$env{'user.name'}; }
5063: my $uhome=&homeserver($uname,$udomain);
5064: my $items='';
5065: foreach my $item (keys(%$storehash)) {
5066: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5067: }
5068: $items=~s/\&$//;
5069: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5070: }
5071:
5072: # ------------------------------------------------------------ newput interface
5073:
5074: sub newput {
5075: my ($namespace,$storehash,$udomain,$uname)=@_;
5076: if (!$udomain) { $udomain=$env{'user.domain'}; }
5077: if (!$uname) { $uname=$env{'user.name'}; }
5078: my $uhome=&homeserver($uname,$udomain);
5079: my $items='';
5080: foreach my $key (keys(%$storehash)) {
5081: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5082: }
5083: $items=~s/\&$//;
5084: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5085: }
5086:
5087: # --------------------------------------------------------- putstore interface
5088:
5089: sub putstore {
5090: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5091: if (!$udomain) { $udomain=$env{'user.domain'}; }
5092: if (!$uname) { $uname=$env{'user.name'}; }
5093: my $uhome=&homeserver($uname,$udomain);
5094: my $items='';
5095: foreach my $key (keys(%$storehash)) {
5096: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5097: }
5098: $items=~s/\&$//;
5099: my $esc_symb=&escape($symb);
5100: my $esc_v=&escape($version);
5101: my $reply =
5102: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5103: $uhome);
5104: if ($reply eq 'unknown_cmd') {
5105: # gfall back to way things use to be done
5106: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5107: $uname);
5108: }
5109: return $reply;
5110: }
5111:
5112: sub old_putstore {
5113: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5114: if (!$udomain) { $udomain=$env{'user.domain'}; }
5115: if (!$uname) { $uname=$env{'user.name'}; }
5116: my $uhome=&homeserver($uname,$udomain);
5117: my %newstorehash;
5118: foreach my $item (keys(%$storehash)) {
5119: my $key = $version.':'.&escape($symb).':'.$item;
5120: $newstorehash{$key} = $storehash->{$item};
5121: }
5122: my $items='';
5123: my %allitems = ();
5124: foreach my $item (keys(%newstorehash)) {
5125: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5126: my $key = $1.':keys:'.$2;
5127: $allitems{$key} .= $3.':';
5128: }
5129: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5130: }
5131: foreach my $item (keys(%allitems)) {
5132: $allitems{$item} =~ s/\:$//;
5133: $items.= $item.'='.$allitems{$item}.'&';
5134: }
5135: $items=~s/\&$//;
5136: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5137: }
5138:
5139: # ------------------------------------------------------ critical put interface
5140:
5141: sub cput {
5142: my ($namespace,$storehash,$udomain,$uname)=@_;
5143: if (!$udomain) { $udomain=$env{'user.domain'}; }
5144: if (!$uname) { $uname=$env{'user.name'}; }
5145: my $uhome=&homeserver($uname,$udomain);
5146: my $items='';
5147: foreach my $item (keys(%$storehash)) {
5148: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5149: }
5150: $items=~s/\&$//;
5151: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5152: }
5153:
5154: # -------------------------------------------------------------- eget interface
5155:
5156: sub eget {
5157: my ($namespace,$storearr,$udomain,$uname)=@_;
5158: my $items='';
5159: foreach my $item (@$storearr) {
5160: $items.=&escape($item).'&';
5161: }
5162: $items=~s/\&$//;
5163: if (!$udomain) { $udomain=$env{'user.domain'}; }
5164: if (!$uname) { $uname=$env{'user.name'}; }
5165: my $uhome=&homeserver($uname,$udomain);
5166: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5167: my @pairs=split(/\&/,$rep);
5168: my %returnhash=();
5169: my $i=0;
5170: foreach my $item (@$storearr) {
5171: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5172: $i++;
5173: }
5174: return %returnhash;
5175: }
5176:
5177: # ------------------------------------------------------------ tmpput interface
5178: sub tmpput {
5179: my ($storehash,$server,$context)=@_;
5180: my $items='';
5181: foreach my $item (keys(%$storehash)) {
5182: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5183: }
5184: $items=~s/\&$//;
5185: if (defined($context)) {
5186: $items .= ':'.&escape($context);
5187: }
5188: return &reply("tmpput:$items",$server);
5189: }
5190:
5191: # ------------------------------------------------------------ tmpget interface
5192: sub tmpget {
5193: my ($token,$server)=@_;
5194: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5195: my $rep=&reply("tmpget:$token",$server);
5196: my %returnhash;
5197: foreach my $item (split(/\&/,$rep)) {
5198: my ($key,$value)=split(/=/,$item);
5199: next if ($key =~ /^error: 2 /);
5200: $returnhash{&unescape($key)}=&thaw_unescape($value);
5201: }
5202: return %returnhash;
5203: }
5204:
5205: # ------------------------------------------------------------ tmpdel interface
5206: sub tmpdel {
5207: my ($token,$server)=@_;
5208: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5209: return &reply("tmpdel:$token",$server);
5210: }
5211:
5212: # -------------------------------------------------- portfolio access checking
5213:
5214: sub portfolio_access {
5215: my ($requrl) = @_;
5216: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5217: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5218: if ($result) {
5219: my %setters;
5220: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5221: my ($startblock,$endblock) =
5222: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5223: if ($startblock && $endblock) {
5224: return 'B';
5225: }
5226: } else {
5227: my ($startblock,$endblock) =
5228: &Apache::loncommon::blockcheck(\%setters,'port');
5229: if ($startblock && $endblock) {
5230: return 'B';
5231: }
5232: }
5233: }
5234: if ($result eq 'ok') {
5235: return 'F';
5236: } elsif ($result =~ /^[^:]+:guest_/) {
5237: return 'A';
5238: }
5239: return '';
5240: }
5241:
5242: sub get_portfolio_access {
5243: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5244:
5245: if (!ref($access_hash)) {
5246: my $current_perms = &get_portfile_permissions($udom,$unum);
5247: my %access_controls = &get_access_controls($current_perms,$group,
5248: $file_name);
5249: $access_hash = $access_controls{$file_name};
5250: }
5251:
5252: my ($public,$guest,@domains,@users,@courses,@groups);
5253: my $now = time;
5254: if (ref($access_hash) eq 'HASH') {
5255: foreach my $key (keys(%{$access_hash})) {
5256: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5257: if ($start > $now) {
5258: next;
5259: }
5260: if ($end && $end<$now) {
5261: next;
5262: }
5263: if ($scope eq 'public') {
5264: $public = $key;
5265: last;
5266: } elsif ($scope eq 'guest') {
5267: $guest = $key;
5268: } elsif ($scope eq 'domains') {
5269: push(@domains,$key);
5270: } elsif ($scope eq 'users') {
5271: push(@users,$key);
5272: } elsif ($scope eq 'course') {
5273: push(@courses,$key);
5274: } elsif ($scope eq 'group') {
5275: push(@groups,$key);
5276: }
5277: }
5278: if ($public) {
5279: return 'ok';
5280: }
5281: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5282: if ($guest) {
5283: return $guest;
5284: }
5285: } else {
5286: if (@domains > 0) {
5287: foreach my $domkey (@domains) {
5288: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5289: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5290: return 'ok';
5291: }
5292: }
5293: }
5294: }
5295: if (@users > 0) {
5296: foreach my $userkey (@users) {
5297: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5298: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5299: if (ref($item) eq 'HASH') {
5300: if (($item->{'uname'} eq $env{'user.name'}) &&
5301: ($item->{'udom'} eq $env{'user.domain'})) {
5302: return 'ok';
5303: }
5304: }
5305: }
5306: }
5307: }
5308: }
5309: my %roleshash;
5310: my @courses_and_groups = @courses;
5311: push(@courses_and_groups,@groups);
5312: if (@courses_and_groups > 0) {
5313: my (%allgroups,%allroles);
5314: my ($start,$end,$role,$sec,$group);
5315: foreach my $envkey (%env) {
5316: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5317: my $cid = $2.'_'.$3;
5318: if ($1 eq 'gr') {
5319: $group = $4;
5320: $allgroups{$cid}{$group} = $env{$envkey};
5321: } else {
5322: if ($4 eq '') {
5323: $sec = 'none';
5324: } else {
5325: $sec = $4;
5326: }
5327: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5328: }
5329: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5330: my $cid = $2.'_'.$3;
5331: if ($4 eq '') {
5332: $sec = 'none';
5333: } else {
5334: $sec = $4;
5335: }
5336: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5337: }
5338: }
5339: if (keys(%allroles) == 0) {
5340: return;
5341: }
5342: foreach my $key (@courses_and_groups) {
5343: my %content = %{$$access_hash{$key}};
5344: my $cnum = $content{'number'};
5345: my $cdom = $content{'domain'};
5346: my $cid = $cdom.'_'.$cnum;
5347: if (!exists($allroles{$cid})) {
5348: next;
5349: }
5350: foreach my $role_id (keys(%{$content{'roles'}})) {
5351: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5352: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5353: my @status = @{$content{'roles'}{$role_id}{'access'}};
5354: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5355: foreach my $role (keys(%{$allroles{$cid}})) {
5356: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5357: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5358: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5359: if (grep/^all$/,@sections) {
5360: return 'ok';
5361: } else {
5362: if (grep/^$sec$/,@sections) {
5363: return 'ok';
5364: }
5365: }
5366: }
5367: }
5368: if (keys(%{$allgroups{$cid}}) == 0) {
5369: if (grep/^none$/,@groups) {
5370: return 'ok';
5371: }
5372: } else {
5373: if (grep/^all$/,@groups) {
5374: return 'ok';
5375: }
5376: foreach my $group (keys(%{$allgroups{$cid}})) {
5377: if (grep/^$group$/,@groups) {
5378: return 'ok';
5379: }
5380: }
5381: }
5382: }
5383: }
5384: }
5385: }
5386: }
5387: if ($guest) {
5388: return $guest;
5389: }
5390: }
5391: }
5392: return;
5393: }
5394:
5395: sub course_group_datechecker {
5396: my ($dates,$now,$status) = @_;
5397: my ($start,$end) = split(/\./,$dates);
5398: if (!$start && !$end) {
5399: return 'ok';
5400: }
5401: if (grep/^active$/,@{$status}) {
5402: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5403: return 'ok';
5404: }
5405: }
5406: if (grep/^previous$/,@{$status}) {
5407: if ($end > $now ) {
5408: return 'ok';
5409: }
5410: }
5411: if (grep/^future$/,@{$status}) {
5412: if ($start > $now) {
5413: return 'ok';
5414: }
5415: }
5416: return;
5417: }
5418:
5419: sub parse_portfolio_url {
5420: my ($url) = @_;
5421:
5422: my ($type,$udom,$unum,$group,$file_name);
5423:
5424: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5425: $type = 1;
5426: $udom = $1;
5427: $unum = $2;
5428: $file_name = $3;
5429: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5430: $type = 2;
5431: $udom = $1;
5432: $unum = $2;
5433: $group = $3;
5434: $file_name = $3.'/'.$4;
5435: }
5436: if (wantarray) {
5437: return ($type,$udom,$unum,$file_name,$group);
5438: }
5439: return $type;
5440: }
5441:
5442: sub is_portfolio_url {
5443: my ($url) = @_;
5444: return scalar(&parse_portfolio_url($url));
5445: }
5446:
5447: sub is_portfolio_file {
5448: my ($file) = @_;
5449: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5450: return 1;
5451: }
5452: return;
5453: }
5454:
5455: sub usertools_access {
5456: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
5457: my ($access,%tools);
5458: if ($context eq '') {
5459: $context = 'tools';
5460: }
5461: if ($context eq 'requestcourses') {
5462: %tools = (
5463: official => 1,
5464: unofficial => 1,
5465: community => 1,
5466: );
5467: } else {
5468: %tools = (
5469: aboutme => 1,
5470: blog => 1,
5471: portfolio => 1,
5472: );
5473: }
5474: return if (!defined($tools{$tool}));
5475:
5476: if ((!defined($udom)) || (!defined($uname))) {
5477: $udom = $env{'user.domain'};
5478: $uname = $env{'user.name'};
5479: }
5480:
5481: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5482: if ($action ne 'reload') {
5483: if ($context eq 'requestcourses') {
5484: return $env{'environment.canrequest.'.$tool};
5485: } else {
5486: return $env{'environment.availabletools.'.$tool};
5487: }
5488: }
5489: }
5490:
5491: my ($toolstatus,$inststatus);
5492:
5493: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5494: ($action ne 'reload')) {
5495: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5496: $inststatus = $env{'environment.inststatus'};
5497: } else {
5498: if (ref($userenvref) eq 'HASH') {
5499: $toolstatus = $userenvref->{$context.'.'.$tool};
5500: $inststatus = $userenvref->{'inststatus'};
5501: } else {
5502: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5503: $toolstatus = $userenv{$context.'.'.$tool};
5504: $inststatus = $userenv{'inststatus'};
5505: }
5506: }
5507:
5508: if ($toolstatus ne '') {
5509: if ($toolstatus) {
5510: $access = 1;
5511: } else {
5512: $access = 0;
5513: }
5514: return $access;
5515: }
5516:
5517: my ($is_adv,%domdef);
5518: if (ref($is_advref) eq 'HASH') {
5519: $is_adv = $is_advref->{'is_adv'};
5520: } else {
5521: $is_adv = &is_advanced_user($udom,$uname);
5522: }
5523: if (ref($domdefref) eq 'HASH') {
5524: %domdef = %{$domdefref};
5525: } else {
5526: %domdef = &get_domain_defaults($udom);
5527: }
5528: if (ref($domdef{$tool}) eq 'HASH') {
5529: if ($is_adv) {
5530: if ($domdef{$tool}{'_LC_adv'} ne '') {
5531: if ($domdef{$tool}{'_LC_adv'}) {
5532: $access = 1;
5533: } else {
5534: $access = 0;
5535: }
5536: return $access;
5537: }
5538: }
5539: if ($inststatus ne '') {
5540: my ($hasaccess,$hasnoaccess);
5541: foreach my $affiliation (split(/:/,$inststatus)) {
5542: if ($domdef{$tool}{$affiliation} ne '') {
5543: if ($domdef{$tool}{$affiliation}) {
5544: $hasaccess = 1;
5545: } else {
5546: $hasnoaccess = 1;
5547: }
5548: }
5549: }
5550: if ($hasaccess || $hasnoaccess) {
5551: if ($hasaccess) {
5552: $access = 1;
5553: } elsif ($hasnoaccess) {
5554: $access = 0;
5555: }
5556: return $access;
5557: }
5558: } else {
5559: if ($domdef{$tool}{'default'} ne '') {
5560: if ($domdef{$tool}{'default'}) {
5561: $access = 1;
5562: } elsif ($domdef{$tool}{'default'} == 0) {
5563: $access = 0;
5564: }
5565: return $access;
5566: }
5567: }
5568: } else {
5569: if ($context eq 'tools') {
5570: $access = 1;
5571: } else {
5572: $access = 0;
5573: }
5574: return $access;
5575: }
5576: }
5577:
5578: sub is_course_owner {
5579: my ($cdom,$cnum,$udom,$uname) = @_;
5580: if (($udom eq '') || ($uname eq '')) {
5581: $udom = $env{'user.domain'};
5582: $uname = $env{'user.name'};
5583: }
5584: unless (($udom eq '') || ($uname eq '')) {
5585: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5586: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5587: return 1;
5588: } else {
5589: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5590: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5591: return 1;
5592: }
5593: }
5594: }
5595: }
5596: return;
5597: }
5598:
5599: sub is_advanced_user {
5600: my ($udom,$uname) = @_;
5601: if ($udom ne '' && $uname ne '') {
5602: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5603: if (wantarray) {
5604: return ($env{'user.adv'},$env{'user.author'});
5605: } else {
5606: return $env{'user.adv'};
5607: }
5608: }
5609: }
5610: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5611: my %allroles;
5612: my ($is_adv,$is_author);
5613: foreach my $role (keys(%roleshash)) {
5614: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5615: my $area = '/'.$tdomain.'/'.$trest;
5616: if ($sec ne '') {
5617: $area .= '/'.$sec;
5618: }
5619: if (($area ne '') && ($trole ne '')) {
5620: my $spec=$trole.'.'.$area;
5621: if ($trole =~ /^cr\//) {
5622: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5623: } elsif ($trole ne 'gr') {
5624: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5625: }
5626: if ($trole eq 'au') {
5627: $is_author = 1;
5628: }
5629: }
5630: }
5631: foreach my $role (keys(%allroles)) {
5632: last if ($is_adv);
5633: foreach my $item (split(/:/,$allroles{$role})) {
5634: if ($item ne '') {
5635: my ($privilege,$restrictions)=split(/&/,$item);
5636: if ($privilege eq 'adv') {
5637: $is_adv = 1;
5638: last;
5639: }
5640: }
5641: }
5642: }
5643: if (wantarray) {
5644: return ($is_adv,$is_author);
5645: }
5646: return $is_adv;
5647: }
5648:
5649: sub check_can_request {
5650: my ($dom,$can_request,$request_domains) = @_;
5651: my $canreq = 0;
5652: my ($types,$typename) = &Apache::loncommon::course_types();
5653: my @options = ('approval','validate','autolimit');
5654: my $optregex = join('|',@options);
5655: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5656: foreach my $type (@{$types}) {
5657: if (&usertools_access($env{'user.name'},
5658: $env{'user.domain'},
5659: $type,undef,'requestcourses')) {
5660: $canreq ++;
5661: if (ref($request_domains) eq 'HASH') {
5662: push(@{$request_domains->{$type}},$env{'user.domain'});
5663: }
5664: if ($dom eq $env{'user.domain'}) {
5665: $can_request->{$type} = 1;
5666: }
5667: }
5668: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5669: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5670: if (@curr > 0) {
5671: foreach my $item (@curr) {
5672: if (ref($request_domains) eq 'HASH') {
5673: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5674: if ($otherdom ne '') {
5675: if (ref($request_domains->{$type}) eq 'ARRAY') {
5676: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5677: push(@{$request_domains->{$type}},$otherdom);
5678: }
5679: } else {
5680: push(@{$request_domains->{$type}},$otherdom);
5681: }
5682: }
5683: }
5684: }
5685: unless($dom eq $env{'user.domain'}) {
5686: $canreq ++;
5687: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5688: $can_request->{$type} = 1;
5689: }
5690: }
5691: }
5692: }
5693: }
5694: }
5695: return $canreq;
5696: }
5697:
5698: # ---------------------------------------------- Custom access rule evaluation
5699:
5700: sub customaccess {
5701: my ($priv,$uri)=@_;
5702: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5703: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5704: $udom = &LONCAPA::clean_domain($udom);
5705: $ucrs = &LONCAPA::clean_username($ucrs);
5706: my $access=0;
5707: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5708: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5709: if ($type eq 'user') {
5710: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5711: my ($tdom,$tuname)=split(m{/},$scope);
5712: if ($tdom) {
5713: if ($tdom ne $env{'user.domain'}) { next; }
5714: }
5715: if ($tuname) {
5716: if ($tuname ne $env{'user.name'}) { next; }
5717: }
5718: $access=($effect eq 'allow');
5719: last;
5720: }
5721: } else {
5722: if ($role) {
5723: if ($role ne $urole) { next; }
5724: }
5725: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5726: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5727: if ($tdom) {
5728: if ($tdom ne $udom) { next; }
5729: }
5730: if ($tcrs) {
5731: if ($tcrs ne $ucrs) { next; }
5732: }
5733: if ($tsec) {
5734: if ($tsec ne $usec) { next; }
5735: }
5736: $access=($effect eq 'allow');
5737: last;
5738: }
5739: if ($realm eq '' && $role eq '') {
5740: $access=($effect eq 'allow');
5741: }
5742: }
5743: }
5744: return $access;
5745: }
5746:
5747: # ------------------------------------------------- Check for a user privilege
5748:
5749: sub allowed {
5750: my ($priv,$uri,$symb,$role)=@_;
5751: my $ver_orguri=$uri;
5752: $uri=&deversion($uri);
5753: my $orguri=$uri;
5754: $uri=&declutter($uri);
5755:
5756: if ($priv eq 'evb') {
5757: # Evade communication block restrictions for specified role in a course
5758: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5759: return $1;
5760: } else {
5761: return;
5762: }
5763: }
5764:
5765: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5766: # Free bre access to adm and meta resources
5767: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5768: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5769: && ($priv eq 'bre')) {
5770: return 'F';
5771: }
5772:
5773: # Free bre access to user's own portfolio contents
5774: my ($space,$domain,$name,@dir)=split('/',$uri);
5775: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5776: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5777: my %setters;
5778: my ($startblock,$endblock) =
5779: &Apache::loncommon::blockcheck(\%setters,'port');
5780: if ($startblock && $endblock) {
5781: return 'B';
5782: } else {
5783: return 'F';
5784: }
5785: }
5786:
5787: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5788: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5789: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5790: if (exists($env{'request.course.id'})) {
5791: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5792: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5793: if (($domain eq $cdom) && ($name eq $cnum)) {
5794: my $courseprivid=$env{'request.course.id'};
5795: $courseprivid=~s/\_/\//;
5796: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5797: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5798: return $1;
5799: } else {
5800: if ($env{'request.course.sec'}) {
5801: $courseprivid.='/'.$env{'request.course.sec'};
5802: }
5803: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5804: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5805: return $2;
5806: }
5807: }
5808: }
5809: }
5810: }
5811:
5812: # Free bre to public access
5813:
5814: if ($priv eq 'bre') {
5815: my $copyright=&metadata($uri,'copyright');
5816: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5817: return 'F';
5818: }
5819: if ($copyright eq 'priv') {
5820: $uri=~/([^\/]+)\/([^\/]+)\//;
5821: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5822: return '';
5823: }
5824: }
5825: if ($copyright eq 'domain') {
5826: $uri=~/([^\/]+)\/([^\/]+)\//;
5827: unless (($env{'user.domain'} eq $1) ||
5828: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5829: return '';
5830: }
5831: }
5832: if ($env{'request.role'}=~ /li\.\//) {
5833: # Library role, so allow browsing of resources in this domain.
5834: return 'F';
5835: }
5836: if ($copyright eq 'custom') {
5837: unless (&customaccess($priv,$uri)) { return ''; }
5838: }
5839: }
5840: # Domain coordinator is trying to create a course
5841: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5842: # uri is the requested domain in this case.
5843: # comparison to 'request.role.domain' shows if the user has selected
5844: # a role of dc for the domain in question.
5845: return 'F' if ($uri eq $env{'request.role.domain'});
5846: }
5847:
5848: my $thisallowed='';
5849: my $statecond=0;
5850: my $courseprivid='';
5851:
5852: my $ownaccess;
5853: # Community Coordinator or Assistant Co-author browsing resource space.
5854: if (($priv eq 'bro') && ($env{'user.author'})) {
5855: if ($uri eq '') {
5856: $ownaccess = 1;
5857: } else {
5858: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5859: my $udom = $env{'user.domain'};
5860: my $uname = $env{'user.name'};
5861: if ($uri =~ m{^\Q$udom\E/?$}) {
5862: $ownaccess = 1;
5863: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
5864: unless ($uri =~ m{\.\./}) {
5865: $ownaccess = 1;
5866: }
5867: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5868: my $now = time;
5869: if ($uri =~ m{^([^/]+)/?$}) {
5870: my $adom = $1;
5871: foreach my $key (keys(%env)) {
5872: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
5873: my ($start,$end) = split('.',$env{$key});
5874: if (($now >= $start) && (!$end || $end < $now)) {
5875: $ownaccess = 1;
5876: last;
5877: }
5878: }
5879: }
5880: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5881: my $adom = $1;
5882: my $aname = $2;
5883: foreach my $role ('ca','aa') {
5884: if ($env{"user.role.$role./$adom/$aname"}) {
5885: my ($start,$end) =
5886: split('.',$env{"user.role.$role./$adom/$aname"});
5887: if (($now >= $start) && (!$end || $end < $now)) {
5888: $ownaccess = 1;
5889: last;
5890: }
5891: }
5892: }
5893: }
5894: }
5895: }
5896: }
5897: }
5898:
5899: # Course
5900:
5901: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5902: unless (($priv eq 'bro') && (!$ownaccess)) {
5903: $thisallowed.=$1;
5904: }
5905: }
5906:
5907: # Domain
5908:
5909: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5910: =~/\Q$priv\E\&([^\:]*)/) {
5911: unless (($priv eq 'bro') && (!$ownaccess)) {
5912: $thisallowed.=$1;
5913: }
5914: }
5915:
5916: # User who is not author or co-author might still be able to edit
5917: # resource of an author in the domain (e.g., if Domain Coordinator).
5918: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
5919: (&allowed('mdc',$env{'request.course.id'}))) {
5920: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
5921: $thisallowed.=$1;
5922: }
5923: }
5924:
5925: # Course: uri itself is a course
5926: my $courseuri=$uri;
5927: $courseuri=~s/\_(\d)/\/$1/;
5928: $courseuri=~s/^([^\/])/\/$1/;
5929:
5930: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5931: =~/\Q$priv\E\&([^\:]*)/) {
5932: unless (($priv eq 'bro') && (!$ownaccess)) {
5933: $thisallowed.=$1;
5934: }
5935: }
5936:
5937: # URI is an uploaded document for this course, default permissions don't matter
5938: # not allowing 'edit' access (editupload) to uploaded course docs
5939: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5940: $thisallowed='';
5941: my ($match)=&is_on_map($uri);
5942: if ($match) {
5943: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5944: =~/\Q$priv\E\&([^\:]*)/) {
5945: $thisallowed.=$1;
5946: }
5947: } else {
5948: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5949: if ($refuri) {
5950: if ($refuri =~ m|^/adm/|) {
5951: $thisallowed='F';
5952: } else {
5953: $refuri=&declutter($refuri);
5954: my ($match) = &is_on_map($refuri);
5955: if ($match) {
5956: $thisallowed='F';
5957: }
5958: }
5959: }
5960: }
5961: }
5962:
5963: if ($priv eq 'bre'
5964: && $thisallowed ne 'F'
5965: && $thisallowed ne '2'
5966: && &is_portfolio_url($uri)) {
5967: $thisallowed = &portfolio_access($uri);
5968: }
5969:
5970: # Full access at system, domain or course-wide level? Exit.
5971: if ($thisallowed=~/F/) {
5972: return 'F';
5973: }
5974:
5975: # If this is generating or modifying users, exit with special codes
5976:
5977: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5978: if (($priv eq 'cca') || ($priv eq 'caa')) {
5979: my ($audom,$auname)=split('/',$uri);
5980: # no author name given, so this just checks on the general right to make a co-author in this domain
5981: unless ($auname) { return $thisallowed; }
5982: # an author name is given, so we are about to actually make a co-author for a certain account
5983: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5984: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5985: ($audom ne $env{'request.role.domain'}))) { return ''; }
5986: }
5987: return $thisallowed;
5988: }
5989: #
5990: # Gathered so far: system, domain and course wide privileges
5991: #
5992: # Course: See if uri or referer is an individual resource that is part of
5993: # the course
5994:
5995: if ($env{'request.course.id'}) {
5996:
5997: $courseprivid=$env{'request.course.id'};
5998: if ($env{'request.course.sec'}) {
5999: $courseprivid.='/'.$env{'request.course.sec'};
6000: }
6001: $courseprivid=~s/\_/\//;
6002: my $checkreferer=1;
6003: my ($match,$cond)=&is_on_map($uri);
6004: if ($match) {
6005: $statecond=$cond;
6006: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6007: =~/\Q$priv\E\&([^\:]*)/) {
6008: $thisallowed.=$1;
6009: $checkreferer=0;
6010: }
6011: }
6012:
6013: if ($checkreferer) {
6014: my $refuri=$env{'httpref.'.$orguri};
6015: unless ($refuri) {
6016: foreach my $key (keys(%env)) {
6017: if ($key=~/^httpref\..*\*/) {
6018: my $pattern=$key;
6019: $pattern=~s/^httpref\.\/res\///;
6020: $pattern=~s/\*/\[\^\/\]\+/g;
6021: $pattern=~s/\//\\\//g;
6022: if ($orguri=~/$pattern/) {
6023: $refuri=$env{$key};
6024: }
6025: }
6026: }
6027: }
6028:
6029: if ($refuri) {
6030: $refuri=&declutter($refuri);
6031: my ($match,$cond)=&is_on_map($refuri);
6032: if ($match) {
6033: my $refstatecond=$cond;
6034: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6035: =~/\Q$priv\E\&([^\:]*)/) {
6036: $thisallowed.=$1;
6037: $uri=$refuri;
6038: $statecond=$refstatecond;
6039: }
6040: }
6041: }
6042: }
6043: }
6044:
6045: #
6046: # Gathered now: all privileges that could apply, and condition number
6047: #
6048: #
6049: # Full or no access?
6050: #
6051:
6052: if ($thisallowed=~/F/) {
6053: return 'F';
6054: }
6055:
6056: unless ($thisallowed) {
6057: return '';
6058: }
6059:
6060: # Restrictions exist, deal with them
6061: #
6062: # C:according to course preferences
6063: # R:according to resource settings
6064: # L:unless locked
6065: # X:according to user session state
6066: #
6067:
6068: # Possibly locked functionality, check all courses
6069: # Locks might take effect only after 10 minutes cache expiration for other
6070: # courses, and 2 minutes for current course
6071:
6072: my $envkey;
6073: if ($thisallowed=~/L/) {
6074: foreach $envkey (keys(%env)) {
6075: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6076: my $courseid=$2;
6077: my $roleid=$1.'.'.$2;
6078: $courseid=~s/^\///;
6079: my $expiretime=600;
6080: if ($env{'request.role'} eq $roleid) {
6081: $expiretime=120;
6082: }
6083: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6084: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6085: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6086: &coursedescription($courseid,{'freshen_cache' => 1});
6087: }
6088: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6089: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6090: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6091: &log($env{'user.domain'},$env{'user.name'},
6092: $env{'user.home'},
6093: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6094: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6095: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6096: return '';
6097: }
6098: }
6099: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6100: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6101: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6102: &log($env{'user.domain'},$env{'user.name'},
6103: $env{'user.home'},
6104: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6105: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6106: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6107: return '';
6108: }
6109: }
6110: }
6111: }
6112: }
6113:
6114: #
6115: # Rest of the restrictions depend on selected course
6116: #
6117:
6118: unless ($env{'request.course.id'}) {
6119: if ($thisallowed eq 'A') {
6120: return 'A';
6121: } elsif ($thisallowed eq 'B') {
6122: return 'B';
6123: } else {
6124: return '1';
6125: }
6126: }
6127:
6128: #
6129: # Now user is definitely in a course
6130: #
6131:
6132:
6133: # Course preferences
6134:
6135: if ($thisallowed=~/C/) {
6136: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6137: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6138: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6139: =~/\Q$rolecode\E/) {
6140: if (($priv ne 'pch') && ($priv ne 'plc')) {
6141: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6142: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6143: $env{'request.course.id'});
6144: }
6145: return '';
6146: }
6147:
6148: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6149: =~/\Q$unamedom\E/) {
6150: if (($priv ne 'pch') && ($priv ne 'plc')) {
6151: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6152: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6153: $env{'request.course.id'});
6154: }
6155: return '';
6156: }
6157: }
6158:
6159: # Resource preferences
6160:
6161: if ($thisallowed=~/R/) {
6162: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6163: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6164: if (($priv ne 'pch') && ($priv ne 'plc')) {
6165: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6166: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6167: }
6168: return '';
6169: }
6170: }
6171:
6172: # Restricted by state or randomout?
6173:
6174: if ($thisallowed=~/X/) {
6175: if ($env{'acc.randomout'}) {
6176: if (!$symb) { $symb=&symbread($uri,1); }
6177: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6178: return '';
6179: }
6180: }
6181: if (&condval($statecond)) {
6182: return '2';
6183: } else {
6184: return '';
6185: }
6186: }
6187:
6188: if ($thisallowed eq 'A') {
6189: return 'A';
6190: } elsif ($thisallowed eq 'B') {
6191: return 'B';
6192: }
6193: return 'F';
6194: }
6195: #
6196: # Removes the versino from a URI and
6197: # splits it in to its filename and path to the filename.
6198: # Seems like File::Basename could have done this more clearly.
6199: # Parameters:
6200: # $uri - input URI
6201: # Returns:
6202: # Two element list consisting of
6203: # $pathname - the URI up to and excluding the trailing /
6204: # $filename - The part of the URI following the last /
6205: # NOTE:
6206: # Another realization of this is simply:
6207: # use File::Basename;
6208: # ...
6209: # $uri = shift;
6210: # $filename = basename($uri);
6211: # $path = dirname($uri);
6212: # return ($filename, $path);
6213: #
6214: # The implementation below is probably faster however.
6215: #
6216: sub split_uri_for_cond {
6217: my $uri=&deversion(&declutter(shift));
6218: my @uriparts=split(/\//,$uri);
6219: my $filename=pop(@uriparts);
6220: my $pathname=join('/',@uriparts);
6221: return ($pathname,$filename);
6222: }
6223: # --------------------------------------------------- Is a resource on the map?
6224:
6225: sub is_on_map {
6226: my ($pathname,$filename) = &split_uri_for_cond(shift);
6227: #Trying to find the conditional for the file
6228: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
6229: /\&\Q$filename\E\:([\d\|]+)\&/);
6230: if ($match) {
6231: return (1,$1);
6232: } else {
6233: return (0,0);
6234: }
6235: }
6236:
6237: # --------------------------------------------------------- Get symb from alias
6238:
6239: sub get_symb_from_alias {
6240: my $symb=shift;
6241: my ($map,$resid,$url)=&decode_symb($symb);
6242: # Already is a symb
6243: if ($url) { return $symb; }
6244: # Must be an alias
6245: my $aliassymb='';
6246: my %bighash;
6247: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6248: &GDBM_READER(),0640)) {
6249: my $rid=$bighash{'mapalias_'.$symb};
6250: if ($rid) {
6251: my ($mapid,$resid)=split(/\./,$rid);
6252: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6253: $resid,$bighash{'src_'.$rid});
6254: }
6255: untie %bighash;
6256: }
6257: return $aliassymb;
6258: }
6259:
6260: # ----------------------------------------------------------------- Define Role
6261:
6262: sub definerole {
6263: if (allowed('mcr','/')) {
6264: my ($rolename,$sysrole,$domrole,$courole)=@_;
6265: foreach my $role (split(':',$sysrole)) {
6266: my ($crole,$cqual)=split(/\&/,$role);
6267: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6268: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6269: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6270: return "refused:s:$crole&$cqual";
6271: }
6272: }
6273: }
6274: foreach my $role (split(':',$domrole)) {
6275: my ($crole,$cqual)=split(/\&/,$role);
6276: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6277: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6278: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
6279: return "refused:d:$crole&$cqual";
6280: }
6281: }
6282: }
6283: foreach my $role (split(':',$courole)) {
6284: my ($crole,$cqual)=split(/\&/,$role);
6285: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6286: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6287: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6288: return "refused:c:$crole&$cqual";
6289: }
6290: }
6291: }
6292: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6293: "$env{'user.domain'}:$env{'user.name'}:".
6294: "rolesdef_$rolename=".
6295: escape($sysrole.'_'.$domrole.'_'.$courole);
6296: return reply($command,$env{'user.home'});
6297: } else {
6298: return 'refused';
6299: }
6300: }
6301:
6302: # ---------------- Make a metadata query against the network of library servers
6303:
6304: sub metadata_query {
6305: my ($query,$custom,$customshow,$server_array)=@_;
6306: my %rhash;
6307: my %libserv = &all_library();
6308: my @server_list = (defined($server_array) ? @$server_array
6309: : keys(%libserv) );
6310: for my $server (@server_list) {
6311: unless ($custom or $customshow) {
6312: my $reply=&reply("querysend:".&escape($query),$server);
6313: $rhash{$server}=$reply;
6314: }
6315: else {
6316: my $reply=&reply("querysend:".&escape($query).':'.
6317: &escape($custom).':'.&escape($customshow),
6318: $server);
6319: $rhash{$server}=$reply;
6320: }
6321: }
6322: return \%rhash;
6323: }
6324:
6325: # ----------------------------------------- Send log queries and wait for reply
6326:
6327: sub log_query {
6328: my ($uname,$udom,$query,%filters)=@_;
6329: my $uhome=&homeserver($uname,$udom);
6330: if ($uhome eq 'no_host') { return 'error: no_host'; }
6331: my $uhost=&hostname($uhome);
6332: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
6333: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6334: $uhome);
6335: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
6336: return get_query_reply($queryid);
6337: }
6338:
6339: # -------------------------- Update MySQL table for portfolio file
6340:
6341: sub update_portfolio_table {
6342: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
6343: if ($group ne '') {
6344: $file_name =~s /^\Q$group\E//;
6345: }
6346: my $homeserver = &homeserver($uname,$udom);
6347: my $queryid=
6348: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6349: ':'.&escape($file_name).':'.$action,$homeserver);
6350: my $reply = &get_query_reply($queryid);
6351: return $reply;
6352: }
6353:
6354: # -------------------------- Update MySQL allusers table
6355:
6356: sub update_allusers_table {
6357: my ($uname,$udom,$names) = @_;
6358: my $homeserver = &homeserver($uname,$udom);
6359: my $queryid=
6360: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6361: 'lastname='.&escape($names->{'lastname'}).'%%'.
6362: 'firstname='.&escape($names->{'firstname'}).'%%'.
6363: 'middlename='.&escape($names->{'middlename'}).'%%'.
6364: 'generation='.&escape($names->{'generation'}).'%%'.
6365: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6366: 'id='.&escape($names->{'id'}),$homeserver);
6367: return;
6368: }
6369:
6370: # ------- Request retrieval of institutional classlists for course(s)
6371:
6372: sub fetch_enrollment_query {
6373: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6374: my $homeserver;
6375: my $maxtries = 1;
6376: if ($context eq 'automated') {
6377: $homeserver = $perlvar{'lonHostID'};
6378: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6379: } else {
6380: $homeserver = &homeserver($cnum,$dom);
6381: }
6382: my $host=&hostname($homeserver);
6383: my $cmd = '';
6384: foreach my $affiliate (keys(%{$affiliatesref})) {
6385: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6386: }
6387: $cmd =~ s/%%$//;
6388: $cmd = &escape($cmd);
6389: my $query = 'fetchenrollment';
6390: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6391: unless ($queryid=~/^\Q$host\E\_/) {
6392: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6393: return 'error: '.$queryid;
6394: }
6395: my $reply = &get_query_reply($queryid);
6396: my $tries = 1;
6397: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6398: $reply = &get_query_reply($queryid);
6399: $tries ++;
6400: }
6401: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6402: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6403: } else {
6404: my @responses = split(/:/,$reply);
6405: if ($homeserver eq $perlvar{'lonHostID'}) {
6406: foreach my $line (@responses) {
6407: my ($key,$value) = split(/=/,$line,2);
6408: $$replyref{$key} = $value;
6409: }
6410: } else {
6411: my $pathname = LONCAPA::tempdir();
6412: foreach my $line (@responses) {
6413: my ($key,$value) = split(/=/,$line);
6414: $$replyref{$key} = $value;
6415: if ($value > 0) {
6416: foreach my $item (@{$$affiliatesref{$key}}) {
6417: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6418: my $destname = $pathname.'/'.$filename;
6419: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6420: if ($xml_classlist =~ /^error/) {
6421: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6422: } else {
6423: if ( open(FILE,">$destname") ) {
6424: print FILE &unescape($xml_classlist);
6425: close(FILE);
6426: } else {
6427: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6428: }
6429: }
6430: }
6431: }
6432: }
6433: }
6434: return 'ok';
6435: }
6436: return 'error';
6437: }
6438:
6439: sub get_query_reply {
6440: my $queryid=shift;
6441: my $replyfile=LONCAPA::tempdir().$queryid;
6442: my $reply='';
6443: for (1..100) {
6444: sleep 2;
6445: if (-e $replyfile.'.end') {
6446: if (open(my $fh,$replyfile)) {
6447: $reply = join('',<$fh>);
6448: close($fh);
6449: } else { return 'error: reply_file_error'; }
6450: return &unescape($reply);
6451: }
6452: }
6453: return 'timeout:'.$queryid;
6454: }
6455:
6456: sub courselog_query {
6457: #
6458: # possible filters:
6459: # url: url or symb
6460: # username
6461: # domain
6462: # action: view, submit, grade
6463: # start: timestamp
6464: # end: timestamp
6465: #
6466: my (%filters)=@_;
6467: unless ($env{'request.course.id'}) { return 'no_course'; }
6468: if ($filters{'url'}) {
6469: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6470: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6471: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6472: }
6473: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6474: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6475: return &log_query($cname,$cdom,'courselog',%filters);
6476: }
6477:
6478: sub userlog_query {
6479: #
6480: # possible filters:
6481: # action: log check role
6482: # start: timestamp
6483: # end: timestamp
6484: #
6485: my ($uname,$udom,%filters)=@_;
6486: return &log_query($uname,$udom,'userlog',%filters);
6487: }
6488:
6489: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6490:
6491: sub auto_run {
6492: my ($cnum,$cdom) = @_;
6493: my $response = 0;
6494: my $settings;
6495: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6496: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6497: $settings = $domconfig{'autoenroll'};
6498: if ($settings->{'run'} eq '1') {
6499: $response = 1;
6500: }
6501: } else {
6502: my $homeserver;
6503: if (&is_course($cdom,$cnum)) {
6504: $homeserver = &homeserver($cnum,$cdom);
6505: } else {
6506: $homeserver = &domain($cdom,'primary');
6507: }
6508: if ($homeserver ne 'no_host') {
6509: $response = &reply('autorun:'.$cdom,$homeserver);
6510: }
6511: }
6512: return $response;
6513: }
6514:
6515: sub auto_get_sections {
6516: my ($cnum,$cdom,$inst_coursecode) = @_;
6517: my $homeserver;
6518: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6519: $homeserver = &homeserver($cnum,$cdom);
6520: }
6521: if (!defined($homeserver)) {
6522: if ($cdom =~ /^$match_domain$/) {
6523: $homeserver = &domain($cdom,'primary');
6524: }
6525: }
6526: my @secs;
6527: if (defined($homeserver)) {
6528: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6529: unless ($response eq 'refused') {
6530: @secs = split(/:/,$response);
6531: }
6532: }
6533: return @secs;
6534: }
6535:
6536: sub auto_new_course {
6537: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6538: my $homeserver = &homeserver($cnum,$cdom);
6539: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6540: return $response;
6541: }
6542:
6543: sub auto_validate_courseID {
6544: my ($cnum,$cdom,$inst_course_id) = @_;
6545: my $homeserver = &homeserver($cnum,$cdom);
6546: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6547: return $response;
6548: }
6549:
6550: sub auto_validate_instcode {
6551: my ($cnum,$cdom,$instcode,$owner) = @_;
6552: my ($homeserver,$response);
6553: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6554: $homeserver = &homeserver($cnum,$cdom);
6555: }
6556: if (!defined($homeserver)) {
6557: if ($cdom =~ /^$match_domain$/) {
6558: $homeserver = &domain($cdom,'primary');
6559: }
6560: }
6561: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6562: &escape($instcode).':'.&escape($owner),$homeserver));
6563: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6564: return ($outcome,$description);
6565: }
6566:
6567: sub auto_create_password {
6568: my ($cnum,$cdom,$authparam,$udom) = @_;
6569: my ($homeserver,$response);
6570: my $create_passwd = 0;
6571: my $authchk = '';
6572: if ($udom =~ /^$match_domain$/) {
6573: $homeserver = &domain($udom,'primary');
6574: }
6575: if ($homeserver eq '') {
6576: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6577: $homeserver = &homeserver($cnum,$cdom);
6578: }
6579: }
6580: if ($homeserver eq '') {
6581: $authchk = 'nodomain';
6582: } else {
6583: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6584: if ($response eq 'refused') {
6585: $authchk = 'refused';
6586: } else {
6587: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6588: }
6589: }
6590: return ($authparam,$create_passwd,$authchk);
6591: }
6592:
6593: sub auto_photo_permission {
6594: my ($cnum,$cdom,$students) = @_;
6595: my $homeserver = &homeserver($cnum,$cdom);
6596: my ($outcome,$perm_reqd,$conditions) =
6597: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6598: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6599: return (undef,undef);
6600: }
6601: return ($outcome,$perm_reqd,$conditions);
6602: }
6603:
6604: sub auto_checkphotos {
6605: my ($uname,$udom,$pid) = @_;
6606: my $homeserver = &homeserver($uname,$udom);
6607: my ($result,$resulttype);
6608: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6609: &escape($uname).':'.&escape($pid),
6610: $homeserver));
6611: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6612: return (undef,undef);
6613: }
6614: if ($outcome) {
6615: ($result,$resulttype) = split(/:/,$outcome);
6616: }
6617: return ($result,$resulttype);
6618: }
6619:
6620: sub auto_photochoice {
6621: my ($cnum,$cdom) = @_;
6622: my $homeserver = &homeserver($cnum,$cdom);
6623: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6624: &escape($cdom),
6625: $homeserver)));
6626: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6627: return (undef,undef);
6628: }
6629: return ($update,$comment);
6630: }
6631:
6632: sub auto_photoupdate {
6633: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6634: my $homeserver = &homeserver($cnum,$dom);
6635: my $host=&hostname($homeserver);
6636: my $cmd = '';
6637: my $maxtries = 1;
6638: foreach my $affiliate (keys(%{$affiliatesref})) {
6639: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6640: }
6641: $cmd =~ s/%%$//;
6642: $cmd = &escape($cmd);
6643: my $query = 'institutionalphotos';
6644: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6645: unless ($queryid=~/^\Q$host\E\_/) {
6646: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6647: return 'error: '.$queryid;
6648: }
6649: my $reply = &get_query_reply($queryid);
6650: my $tries = 1;
6651: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6652: $reply = &get_query_reply($queryid);
6653: $tries ++;
6654: }
6655: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6656: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6657: } else {
6658: my @responses = split(/:/,$reply);
6659: my $outcome = shift(@responses);
6660: foreach my $item (@responses) {
6661: my ($key,$value) = split(/=/,$item);
6662: $$photo{$key} = $value;
6663: }
6664: return $outcome;
6665: }
6666: return 'error';
6667: }
6668:
6669: sub auto_instcode_format {
6670: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6671: $cat_order) = @_;
6672: my $courses = '';
6673: my @homeservers;
6674: if ($caller eq 'global') {
6675: my %servers = &get_servers($codedom,'library');
6676: foreach my $tryserver (keys(%servers)) {
6677: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6678: push(@homeservers,$tryserver);
6679: }
6680: }
6681: } elsif ($caller eq 'requests') {
6682: if ($codedom =~ /^$match_domain$/) {
6683: my $chome = &domain($codedom,'primary');
6684: unless ($chome eq 'no_host') {
6685: push(@homeservers,$chome);
6686: }
6687: }
6688: } else {
6689: push(@homeservers,&homeserver($caller,$codedom));
6690: }
6691: foreach my $code (keys(%{$instcodes})) {
6692: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
6693: }
6694: chop($courses);
6695: my $ok_response = 0;
6696: my $response;
6697: while (@homeservers > 0 && $ok_response == 0) {
6698: my $server = shift(@homeservers);
6699: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6700: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6701: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
6702: split(/:/,$response);
6703: %{$codes} = (%{$codes},&str2hash($codes_str));
6704: push(@{$codetitles},&str2array($codetitles_str));
6705: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6706: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6707: $ok_response = 1;
6708: }
6709: }
6710: if ($ok_response) {
6711: return 'ok';
6712: } else {
6713: return $response;
6714: }
6715: }
6716:
6717: sub auto_instcode_defaults {
6718: my ($domain,$returnhash,$code_order) = @_;
6719: my @homeservers;
6720:
6721: my %servers = &get_servers($domain,'library');
6722: foreach my $tryserver (keys(%servers)) {
6723: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6724: push(@homeservers,$tryserver);
6725: }
6726: }
6727:
6728: my $response;
6729: foreach my $server (@homeservers) {
6730: $response=&reply('autoinstcodedefaults:'.$domain,$server);
6731: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6732:
6733: foreach my $pair (split(/\&/,$response)) {
6734: my ($name,$value)=split(/\=/,$pair);
6735: if ($name eq 'code_order') {
6736: @{$code_order} = split(/\&/,&unescape($value));
6737: } else {
6738: $returnhash->{&unescape($name)}=&unescape($value);
6739: }
6740: }
6741: return 'ok';
6742: }
6743:
6744: return $response;
6745: }
6746:
6747: sub auto_possible_instcodes {
6748: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6749: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6750: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6751: return;
6752: }
6753: my (@homeservers,$uhome);
6754: if (defined(&domain($domain,'primary'))) {
6755: $uhome=&domain($domain,'primary');
6756: push(@homeservers,&domain($domain,'primary'));
6757: } else {
6758: my %servers = &get_servers($domain,'library');
6759: foreach my $tryserver (keys(%servers)) {
6760: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6761: push(@homeservers,$tryserver);
6762: }
6763: }
6764: }
6765: my $response;
6766: foreach my $server (@homeservers) {
6767: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6768: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6769: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6770: split(':',$response);
6771: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6772: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
6773: foreach my $item (split('&',$cat_title)) {
6774: my ($name,$value)=split('=',$item);
6775: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
6776: }
6777: foreach my $item (split('&',$cat_order)) {
6778: my ($name,$value)=split('=',$item);
6779: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
6780: }
6781: return 'ok';
6782: }
6783: return $response;
6784: }
6785:
6786: sub auto_courserequest_checks {
6787: my ($dom) = @_;
6788: my ($homeserver,%validations);
6789: if ($dom =~ /^$match_domain$/) {
6790: $homeserver = &domain($dom,'primary');
6791: }
6792: unless ($homeserver eq 'no_host') {
6793: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6794: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6795: my @items = split(/&/,$response);
6796: foreach my $item (@items) {
6797: my ($key,$value) = split('=',$item);
6798: $validations{&unescape($key)} = &thaw_unescape($value);
6799: }
6800: }
6801: }
6802: return %validations;
6803: }
6804:
6805: sub auto_courserequest_validation {
6806: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6807: my ($homeserver,$response);
6808: if ($dom =~ /^$match_domain$/) {
6809: $homeserver = &domain($dom,'primary');
6810: }
6811: unless ($homeserver eq 'no_host') {
6812:
6813: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
6814: ':'.&escape($crstype).':'.&escape($inststatuslist).
6815: ':'.&escape($instcode).':'.&escape($instseclist),
6816: $homeserver));
6817: }
6818: return $response;
6819: }
6820:
6821: sub auto_validate_class_sec {
6822: my ($cdom,$cnum,$owners,$inst_class) = @_;
6823: my $homeserver = &homeserver($cnum,$cdom);
6824: my $ownerlist;
6825: if (ref($owners) eq 'ARRAY') {
6826: $ownerlist = join(',',@{$owners});
6827: } else {
6828: $ownerlist = $owners;
6829: }
6830: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
6831: &escape($ownerlist).':'.$cdom,$homeserver);
6832: return $response;
6833: }
6834:
6835: # ------------------------------------------------------- Course Group routines
6836:
6837: sub get_coursegroups {
6838: my ($cdom,$cnum,$group,$namespace) = @_;
6839: return(&dump($namespace,$cdom,$cnum,$group));
6840: }
6841:
6842: sub modify_coursegroup {
6843: my ($cdom,$cnum,$groupsettings) = @_;
6844: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6845: }
6846:
6847: sub toggle_coursegroup_status {
6848: my ($cdom,$cnum,$group,$action) = @_;
6849: my ($from_namespace,$to_namespace);
6850: if ($action eq 'delete') {
6851: $from_namespace = 'coursegroups';
6852: $to_namespace = 'deleted_groups';
6853: } else {
6854: $from_namespace = 'deleted_groups';
6855: $to_namespace = 'coursegroups';
6856: }
6857: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
6858: if (my $tmp = &error(%curr_group)) {
6859: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6860: return ('read error',$tmp);
6861: } else {
6862: my %savedsettings = %curr_group;
6863: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
6864: my $deloutcome;
6865: if ($result eq 'ok') {
6866: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
6867: } else {
6868: return ('write error',$result);
6869: }
6870: if ($deloutcome eq 'ok') {
6871: return 'ok';
6872: } else {
6873: return ('delete error',$deloutcome);
6874: }
6875: }
6876: }
6877:
6878: sub modify_group_roles {
6879: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
6880: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6881: my $role = 'gr/'.&escape($userprivs);
6882: my ($uname,$udom) = split(/:/,$user);
6883: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
6884: if ($result eq 'ok') {
6885: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6886: }
6887: return $result;
6888: }
6889:
6890: sub modify_coursegroup_membership {
6891: my ($cdom,$cnum,$membership) = @_;
6892: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6893: return $result;
6894: }
6895:
6896: sub get_active_groups {
6897: my ($udom,$uname,$cdom,$cnum) = @_;
6898: my $now = time;
6899: my %groups = ();
6900: foreach my $key (keys(%env)) {
6901: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
6902: my ($start,$end) = split(/\./,$env{$key});
6903: if (($end!=0) && ($end<$now)) { next; }
6904: if (($start!=0) && ($start>$now)) { next; }
6905: if ($1 eq $cdom && $2 eq $cnum) {
6906: $groups{$3} = $env{$key} ;
6907: }
6908: }
6909: }
6910: return %groups;
6911: }
6912:
6913: sub get_group_membership {
6914: my ($cdom,$cnum,$group) = @_;
6915: return(&dump('groupmembership',$cdom,$cnum,$group));
6916: }
6917:
6918: sub get_users_groups {
6919: my ($udom,$uname,$courseid) = @_;
6920: my @usersgroups;
6921: my $cachetime=1800;
6922:
6923: my $hashid="$udom:$uname:$courseid";
6924: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6925: if (defined($cached)) {
6926: @usersgroups = split(/:/,$grouplist);
6927: } else {
6928: $grouplist = '';
6929: my $courseurl = &courseid_to_courseurl($courseid);
6930: my $extra = &freeze_escape({'skipcheck' => 1});
6931: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
6932: my $access_end = $env{'course.'.$courseid.
6933: '.default_enrollment_end_date'};
6934: my $now = time;
6935: foreach my $key (keys(%roleshash)) {
6936: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6937: my $group = $1;
6938: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6939: my $start = $2;
6940: my $end = $1;
6941: if ($start == -1) { next; } # deleted from group
6942: if (($start!=0) && ($start>$now)) { next; }
6943: if (($end!=0) && ($end<$now)) {
6944: if ($access_end && $access_end < $now) {
6945: if ($access_end - $end < 86400) {
6946: push(@usersgroups,$group);
6947: }
6948: }
6949: next;
6950: }
6951: push(@usersgroups,$group);
6952: }
6953: }
6954: }
6955: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6956: $grouplist = join(':',@usersgroups);
6957: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6958: }
6959: return @usersgroups;
6960: }
6961:
6962: sub devalidate_getgroups_cache {
6963: my ($udom,$uname,$cdom,$cnum)=@_;
6964: my $courseid = $cdom.'_'.$cnum;
6965:
6966: my $hashid="$udom:$uname:$courseid";
6967: &devalidate_cache_new('getgroups',$hashid);
6968: }
6969:
6970: # ------------------------------------------------------------------ Plain Text
6971:
6972: sub plaintext {
6973: my ($short,$type,$cid,$forcedefault) = @_;
6974: if ($short =~ m{^cr/}) {
6975: return (split('/',$short))[-1];
6976: }
6977: if (!defined($cid)) {
6978: $cid = $env{'request.course.id'};
6979: }
6980: my %rolenames = (
6981: Course => 'std',
6982: Community => 'alt1',
6983: );
6984: if ($cid ne '') {
6985: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6986: unless ($forcedefault) {
6987: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6988: &Apache::lonlocal::mt_escape(\$roletext);
6989: return &Apache::lonlocal::mt($roletext);
6990: }
6991: }
6992: }
6993: if ((defined($type)) && (defined($rolenames{$type})) &&
6994: (defined($rolenames{$type})) &&
6995: (defined($prp{$short}{$rolenames{$type}}))) {
6996: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6997: } elsif ($cid ne '') {
6998: my $crstype = $env{'course.'.$cid.'.type'};
6999: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7000: (defined($prp{$short}{$rolenames{$crstype}}))) {
7001: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7002: }
7003: }
7004: return &Apache::lonlocal::mt($prp{$short}{'std'});
7005: }
7006:
7007: # ----------------------------------------------------------------- Assign Role
7008:
7009: sub assignrole {
7010: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7011: $context)=@_;
7012: my $mrole;
7013: if ($role =~ /^cr\//) {
7014: my $cwosec=$url;
7015: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7016: unless (&allowed('ccr',$cwosec)) {
7017: my $refused = 1;
7018: if ($context eq 'requestcourses') {
7019: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7020: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7021: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7022: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7023: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7024: if ($crsenv{'internal.courseowner'} eq
7025: $env{'user.name'}.':'.$env{'user.domain'}) {
7026: $refused = '';
7027: }
7028: }
7029: }
7030: }
7031: }
7032: if ($refused) {
7033: &logthis('Refused custom assignrole: '.
7034: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7035: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7036: return 'refused';
7037: }
7038: }
7039: $mrole='cr';
7040: } elsif ($role =~ /^gr\//) {
7041: my $cwogrp=$url;
7042: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7043: unless (&allowed('mdg',$cwogrp)) {
7044: &logthis('Refused group assignrole: '.
7045: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7046: $env{'user.name'}.' at '.$env{'user.domain'});
7047: return 'refused';
7048: }
7049: $mrole='gr';
7050: } else {
7051: my $cwosec=$url;
7052: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7053: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7054: my $refused;
7055: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7056: if (!(&allowed('c'.$role,$url))) {
7057: $refused = 1;
7058: }
7059: } else {
7060: $refused = 1;
7061: }
7062: if ($refused) {
7063: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7064: if (!$selfenroll && $context eq 'course') {
7065: my %crsenv;
7066: if ($role eq 'cc' || $role eq 'co') {
7067: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7068: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7069: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7070: if ($crsenv{'internal.courseowner'} eq
7071: $env{'user.name'}.':'.$env{'user.domain'}) {
7072: $refused = '';
7073: }
7074: }
7075: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7076: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7077: if ($crsenv{'internal.courseowner'} eq
7078: $env{'user.name'}.':'.$env{'user.domain'}) {
7079: $refused = '';
7080: }
7081: }
7082: }
7083: }
7084: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7085: $refused = '';
7086: } elsif ($context eq 'requestcourses') {
7087: my @possroles = ('st','ta','ep','in','cc','co');
7088: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7089: my $wrongcc;
7090: if ($cnum =~ /^$match_community$/) {
7091: $wrongcc = 1 if ($role eq 'cc');
7092: } else {
7093: $wrongcc = 1 if ($role eq 'co');
7094: }
7095: unless ($wrongcc) {
7096: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7097: if ($crsenv{'internal.courseowner'} eq
7098: $env{'user.name'}.':'.$env{'user.domain'}) {
7099: $refused = '';
7100: }
7101: }
7102: }
7103: }
7104: if ($refused) {
7105: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7106: ' '.$role.' '.$end.' '.$start.' by '.
7107: $env{'user.name'}.' at '.$env{'user.domain'});
7108: return 'refused';
7109: }
7110: }
7111: } elsif ($role eq 'au') {
7112: if ($url ne '/'.$udom.'/') {
7113: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7114: ' to assign author role for '.$uname.':'.$udom.
7115: ' in domain: '.$url.' refused (wrong domain).');
7116: return 'refused';
7117: }
7118: }
7119: $mrole=$role;
7120: }
7121: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7122: "$udom:$uname:$url".'_'."$mrole=$role";
7123: if ($end) { $command.='_'.$end; }
7124: if ($start) {
7125: if ($end) {
7126: $command.='_'.$start;
7127: } else {
7128: $command.='_0_'.$start;
7129: }
7130: }
7131: my $origstart = $start;
7132: my $origend = $end;
7133: my $delflag;
7134: # actually delete
7135: if ($deleteflag) {
7136: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
7137: # modify command to delete the role
7138: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
7139: "$udom:$uname:$url".'_'."$mrole";
7140: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
7141: # set start and finish to negative values for userrolelog
7142: $start=-1;
7143: $end=-1;
7144: $delflag = 1;
7145: }
7146: }
7147: # send command
7148: my $answer=&reply($command,&homeserver($uname,$udom));
7149: # log new user role if status is ok
7150: if ($answer eq 'ok') {
7151: &userrolelog($role,$uname,$udom,$url,$start,$end);
7152: # for course roles, perform group memberships changes triggered by role change.
7153: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
7154: unless ($role =~ /^gr/) {
7155: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
7156: $origstart,$selfenroll,$context);
7157: }
7158: if ($role eq 'cc') {
7159: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7160: }
7161: }
7162: return $answer;
7163: }
7164:
7165: sub autoupdate_coowners {
7166: my ($url,$end,$start,$uname,$udom) = @_;
7167: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7168: if (($cdom ne '') && ($cnum ne '')) {
7169: my $now = time;
7170: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7171: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7172: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7173: my $instcode = $coursehash{'internal.coursecode'};
7174: if ($instcode ne '') {
7175: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7176: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
7177: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
7178: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7179: if ($result eq 'valid') {
7180: if ($coursehash{'internal.co-owners'}) {
7181: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7182: push(@newcoowners,$coowner);
7183: }
7184: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7185: push(@newcoowners,$uname.':'.$udom);
7186: }
7187: @newcoowners = sort(@newcoowners);
7188: } else {
7189: push(@newcoowners,$uname.':'.$udom);
7190: }
7191: } else {
7192: if ($coursehash{'internal.co-owners'}) {
7193: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7194: unless ($coowner eq $uname.':'.$udom) {
7195: push(@newcoowners,$coowner);
7196: }
7197: }
7198: unless (@newcoowners > 0) {
7199: $delcoowners = 1;
7200: $coowners = '';
7201: }
7202: }
7203: }
7204: if (@newcoowners || $delcoowners) {
7205: &store_coowners($cdom,$cnum,$coursehash{'home'},
7206: $delcoowners,@newcoowners);
7207: }
7208: }
7209: }
7210: }
7211: }
7212: }
7213: }
7214:
7215: sub store_coowners {
7216: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7217: my $cid = $cdom.'_'.$cnum;
7218: my ($coowners,$delresult,$putresult);
7219: if (@newcoowners) {
7220: $coowners = join(',',@newcoowners);
7221: my %coownershash = (
7222: 'internal.co-owners' => $coowners,
7223: );
7224: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7225: if ($putresult eq 'ok') {
7226: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7227: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7228: }
7229: }
7230: }
7231: if ($delcoowners) {
7232: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7233: if ($delresult eq 'ok') {
7234: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7235: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7236: }
7237: }
7238: }
7239: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7240: my %crsinfo =
7241: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7242: if (ref($crsinfo{$cid}) eq 'HASH') {
7243: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7244: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7245: }
7246: }
7247: }
7248:
7249: # -------------------------------------------------- Modify user authentication
7250: # Overrides without validation
7251:
7252: sub modifyuserauth {
7253: my ($udom,$uname,$umode,$upass)=@_;
7254: my $uhome=&homeserver($uname,$udom);
7255: unless (&allowed('mau',$udom)) { return 'refused'; }
7256: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
7257: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7258: ' in domain '.$env{'request.role.domain'});
7259: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7260: &escape($upass),$uhome);
7261: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
7262: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7263: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7264: &log($udom,,$uname,$uhome,
7265: 'Authentication changed by '.$env{'user.domain'}.', '.
7266: $env{'user.name'}.', '.$umode.
7267: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7268: unless ($reply eq 'ok') {
7269: &logthis('Authentication mode error: '.$reply);
7270: return 'error: '.$reply;
7271: }
7272: return 'ok';
7273: }
7274:
7275: # --------------------------------------------------------------- Modify a user
7276:
7277: sub modifyuser {
7278: my ($udom, $uname, $uid,
7279: $umode, $upass, $first,
7280: $middle, $last, $gene,
7281: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
7282: $udom= &LONCAPA::clean_domain($udom);
7283: $uname=&LONCAPA::clean_username($uname);
7284: my $showcandelete = 'none';
7285: if (ref($candelete) eq 'ARRAY') {
7286: if (@{$candelete} > 0) {
7287: $showcandelete = join(', ',@{$candelete});
7288: }
7289: }
7290: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
7291: $umode.', '.$first.', '.$middle.', '.
7292: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
7293: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7294: ' desiredhome not specified').
7295: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7296: ' in domain '.$env{'request.role.domain'});
7297: my $uhome=&homeserver($uname,$udom,'true');
7298: my $newuser;
7299: if ($uhome eq 'no_host') {
7300: $newuser = 1;
7301: }
7302: # ----------------------------------------------------------------- Create User
7303: if (($uhome eq 'no_host') &&
7304: (($umode && $upass) || ($umode eq 'localauth'))) {
7305: my $unhome='';
7306: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
7307: $unhome = $desiredhome;
7308: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7309: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
7310: } else { # load balancing routine for determining $unhome
7311: my $loadm=10000000;
7312: my %servers = &get_servers($udom,'library');
7313: foreach my $tryserver (keys(%servers)) {
7314: my $answer=reply('load',$tryserver);
7315: if (($answer=~/\d+/) && ($answer<$loadm)) {
7316: $loadm=$answer;
7317: $unhome=$tryserver;
7318: }
7319: }
7320: }
7321: if (($unhome eq '') || ($unhome eq 'no_host')) {
7322: return 'error: unable to find a home server for '.$uname.
7323: ' in domain '.$udom;
7324: }
7325: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7326: &escape($upass),$unhome);
7327: unless ($reply eq 'ok') {
7328: return 'error: '.$reply;
7329: }
7330: $uhome=&homeserver($uname,$udom,'true');
7331: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
7332: return 'error: unable verify users home machine.';
7333: }
7334: } # End of creation of new user
7335: # ---------------------------------------------------------------------- Add ID
7336: if ($uid) {
7337: $uid=~tr/A-Z/a-z/;
7338: my %uidhash=&idrget($udom,$uname);
7339: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7340: && (!$forceid)) {
7341: unless ($uid eq $uidhash{$uname}) {
7342: return 'error: user id "'.$uid.'" does not match '.
7343: 'current user id "'.$uidhash{$uname}.'".';
7344: }
7345: } else {
7346: &idput($udom,($uname => $uid));
7347: }
7348: }
7349: # -------------------------------------------------------------- Add names, etc
7350: my @tmp=&get('environment',
7351: ['firstname','middlename','lastname','generation','id',
7352: 'permanentemail','inststatus'],
7353: $udom,$uname);
7354: my (%names,%oldnames);
7355: if ($tmp[0] =~ m/^error:.*/) {
7356: %names=();
7357: } else {
7358: %names = @tmp;
7359: %oldnames = %names;
7360: }
7361: #
7362: # If name, email and/or uid are blank (e.g., because an uploaded file
7363: # of users did not contain them), do not overwrite existing values
7364: # unless field is in $candelete array ref.
7365: #
7366:
7367: my @fields = ('firstname','middlename','lastname','generation',
7368: 'permanentemail','id');
7369: my %newvalues;
7370: if (ref($candelete) eq 'ARRAY') {
7371: foreach my $field (@fields) {
7372: if (grep(/^\Q$field\E$/,@{$candelete})) {
7373: if ($field eq 'firstname') {
7374: $names{$field} = $first;
7375: } elsif ($field eq 'middlename') {
7376: $names{$field} = $middle;
7377: } elsif ($field eq 'lastname') {
7378: $names{$field} = $last;
7379: } elsif ($field eq 'generation') {
7380: $names{$field} = $gene;
7381: } elsif ($field eq 'permanentemail') {
7382: $names{$field} = $email;
7383: } elsif ($field eq 'id') {
7384: $names{$field} = $uid;
7385: }
7386: }
7387: }
7388: }
7389: if ($first) { $names{'firstname'} = $first; }
7390: if (defined($middle)) { $names{'middlename'} = $middle; }
7391: if ($last) { $names{'lastname'} = $last; }
7392: if (defined($gene)) { $names{'generation'} = $gene; }
7393: if ($email) {
7394: $email=~s/[^\w\@\.\-\,]//gs;
7395: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7396: }
7397: if ($uid) { $names{'id'} = $uid; }
7398: if (defined($inststatus)) {
7399: $names{'inststatus'} = '';
7400: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7401: if (ref($usertypes) eq 'HASH') {
7402: my @okstatuses;
7403: foreach my $item (split(/:/,$inststatus)) {
7404: if (defined($usertypes->{$item})) {
7405: push(@okstatuses,$item);
7406: }
7407: }
7408: if (@okstatuses) {
7409: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7410: }
7411: }
7412: }
7413: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7414: $umode.', '.$first.', '.$middle.', '.
7415: $last.', '.$gene.', '.$email.', '.$inststatus;
7416: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7417: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7418: } else {
7419: $logmsg .= ' during self creation';
7420: }
7421: my $changed;
7422: if ($newuser) {
7423: $changed = 1;
7424: } else {
7425: foreach my $field (@fields) {
7426: if ($names{$field} ne $oldnames{$field}) {
7427: $changed = 1;
7428: last;
7429: }
7430: }
7431: }
7432: unless ($changed) {
7433: $logmsg = 'No changes in user information needed for: '.$logmsg;
7434: &logthis($logmsg);
7435: return 'ok';
7436: }
7437: my $reply = &put('environment', \%names, $udom,$uname);
7438: if ($reply ne 'ok') {
7439: return 'error: '.$reply;
7440: }
7441: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7442: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7443: }
7444: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7445: &devalidate_cache_new('namescache',$uname.':'.$udom);
7446: $logmsg = 'Success modifying user '.$logmsg;
7447: &logthis($logmsg);
7448: return 'ok';
7449: }
7450:
7451: # -------------------------------------------------------------- Modify student
7452:
7453: sub modifystudent {
7454: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7455: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7456: $selfenroll,$context,$inststatus)=@_;
7457: if (!$cid) {
7458: unless ($cid=$env{'request.course.id'}) {
7459: return 'not_in_class';
7460: }
7461: }
7462: # --------------------------------------------------------------- Make the user
7463: my $reply=&modifyuser
7464: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7465: $desiredhome,$email,$inststatus);
7466: unless ($reply eq 'ok') { return $reply; }
7467: # This will cause &modify_student_enrollment to get the uid from the
7468: # students environment
7469: $uid = undef if (!$forceid);
7470: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7471: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7472: return $reply;
7473: }
7474:
7475: sub modify_student_enrollment {
7476: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7477: my ($cdom,$cnum,$chome);
7478: if (!$cid) {
7479: unless ($cid=$env{'request.course.id'}) {
7480: return 'not_in_class';
7481: }
7482: $cdom=$env{'course.'.$cid.'.domain'};
7483: $cnum=$env{'course.'.$cid.'.num'};
7484: } else {
7485: ($cdom,$cnum)=split(/_/,$cid);
7486: }
7487: $chome=$env{'course.'.$cid.'.home'};
7488: if (!$chome) {
7489: $chome=&homeserver($cnum,$cdom);
7490: }
7491: if (!$chome) { return 'unknown_course'; }
7492: # Make sure the user exists
7493: my $uhome=&homeserver($uname,$udom);
7494: if (($uhome eq '') || ($uhome eq 'no_host')) {
7495: return 'error: no such user';
7496: }
7497: # Get student data if we were not given enough information
7498: if (!defined($first) || $first eq '' ||
7499: !defined($last) || $last eq '' ||
7500: !defined($uid) || $uid eq '' ||
7501: !defined($middle) || $middle eq '' ||
7502: !defined($gene) || $gene eq '') {
7503: # They did not supply us with enough data to enroll the student, so
7504: # we need to pick up more information.
7505: my %tmp = &get('environment',
7506: ['firstname','middlename','lastname', 'generation','id']
7507: ,$udom,$uname);
7508:
7509: #foreach my $key (keys(%tmp)) {
7510: # &logthis("key $key = ".$tmp{$key});
7511: #}
7512: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7513: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7514: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7515: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7516: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7517: }
7518: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7519: my $user = "$uname:$udom";
7520: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
7521: my $reply=cput('classlist',
7522: {$user =>
7523: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7524: $cdom,$cnum);
7525: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7526: &devalidate_getsection_cache($udom,$uname,$cid);
7527: } else {
7528: return 'error: '.$reply;
7529: }
7530: # Add student role to user
7531: my $uurl='/'.$cid;
7532: $uurl=~s/\_/\//g;
7533: if ($usec) {
7534: $uurl.='/'.$usec;
7535: }
7536: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7537: $selfenroll,$context);
7538: if ($result ne 'ok') {
7539: if ($old_entry{$user} ne '') {
7540: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7541: } else {
7542: $reply = &del('classlist',[$user],$cdom,$cnum);
7543: }
7544: }
7545: return $result;
7546: }
7547:
7548: sub format_name {
7549: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7550: my $name;
7551: if ($first ne 'lastname') {
7552: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7553: } else {
7554: if ($lastname=~/\S/) {
7555: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7556: $name=~s/\s+,/,/;
7557: } else {
7558: $name.= $firstname.' '.$middlename.' '.$generation;
7559: }
7560: }
7561: $name=~s/^\s+//;
7562: $name=~s/\s+$//;
7563: $name=~s/\s+/ /g;
7564: return $name;
7565: }
7566:
7567: # ------------------------------------------------- Write to course preferences
7568:
7569: sub writecoursepref {
7570: my ($courseid,%prefs)=@_;
7571: $courseid=~s/^\///;
7572: $courseid=~s/\_/\//g;
7573: my ($cdomain,$cnum)=split(/\//,$courseid);
7574: my $chome=homeserver($cnum,$cdomain);
7575: if (($chome eq '') || ($chome eq 'no_host')) {
7576: return 'error: no such course';
7577: }
7578: my $cstring='';
7579: foreach my $pref (keys(%prefs)) {
7580: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7581: }
7582: $cstring=~s/\&$//;
7583: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7584: }
7585:
7586: # ---------------------------------------------------------- Make/modify course
7587:
7588: sub createcourse {
7589: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7590: $course_owner,$crstype,$cnum,$context,$category)=@_;
7591: $url=&declutter($url);
7592: my $cid='';
7593: if ($context eq 'requestcourses') {
7594: my $can_create = 0;
7595: my ($ownername,$ownerdom) = split(':',$course_owner);
7596: if ($udom eq $ownerdom) {
7597: if (&usertools_access($ownername,$ownerdom,$category,undef,
7598: $context)) {
7599: $can_create = 1;
7600: }
7601: } else {
7602: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7603: $category);
7604: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7605: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7606: if (@curr > 0) {
7607: my @options = qw(approval validate autolimit);
7608: my $optregex = join('|',@options);
7609: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7610: $can_create = 1;
7611: }
7612: }
7613: }
7614: }
7615: if ($can_create) {
7616: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7617: unless (&allowed('ccc',$udom)) {
7618: return 'refused';
7619: }
7620: }
7621: } else {
7622: return 'refused';
7623: }
7624: } elsif (!&allowed('ccc',$udom)) {
7625: return 'refused';
7626: }
7627: # --------------------------------------------------------------- Get Unique ID
7628: my $uname;
7629: if ($cnum =~ /^$match_courseid$/) {
7630: my $chome=&homeserver($cnum,$udom,'true');
7631: if (($chome eq '') || ($chome eq 'no_host')) {
7632: $uname = $cnum;
7633: } else {
7634: $uname = &generate_coursenum($udom,$crstype);
7635: }
7636: } else {
7637: $uname = &generate_coursenum($udom,$crstype);
7638: }
7639: return $uname if ($uname =~ /^error/);
7640: # -------------------------------------------------- Check supplied server name
7641: if (!defined($course_server)) {
7642: if (defined(&domain($udom,'primary'))) {
7643: $course_server = &domain($udom,'primary');
7644: } else {
7645: $course_server = $env{'user.home'};
7646: }
7647: }
7648: my %host_servers =
7649: &Apache::lonnet::get_servers($udom,'library');
7650: unless ($host_servers{$course_server}) {
7651: return 'error: invalid home server for course: '.$course_server;
7652: }
7653: # ------------------------------------------------------------- Make the course
7654: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
7655: $course_server);
7656: unless ($reply eq 'ok') { return 'error: '.$reply; }
7657: my $uhome=&homeserver($uname,$udom,'true');
7658: if (($uhome eq '') || ($uhome eq 'no_host')) {
7659: return 'error: no such course';
7660: }
7661: # ----------------------------------------------------------------- Course made
7662: # log existence
7663: my $now = time;
7664: my $newcourse = {
7665: $udom.'_'.$uname => {
7666: description => $description,
7667: inst_code => $inst_code,
7668: owner => $course_owner,
7669: type => $crstype,
7670: creator => $env{'user.name'}.':'.
7671: $env{'user.domain'},
7672: created => $now,
7673: context => $context,
7674: },
7675: };
7676: &courseidput($udom,$newcourse,$uhome,'notime');
7677: # set toplevel url
7678: my $topurl=$url;
7679: unless ($nonstandard) {
7680: # ------------------------------------------ For standard courses, make top url
7681: my $mapurl=&clutter($url);
7682: if ($mapurl eq '/res/') { $mapurl=''; }
7683: $env{'form.initmap'}=(<<ENDINITMAP);
7684: <map>
7685: <resource id="1" type="start"></resource>
7686: <resource id="2" src="$mapurl"></resource>
7687: <resource id="3" type="finish"></resource>
7688: <link index="1" from="1" to="2"></link>
7689: <link index="2" from="2" to="3"></link>
7690: </map>
7691: ENDINITMAP
7692: $topurl=&declutter(
7693: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
7694: );
7695: }
7696: # ----------------------------------------------------------- Write preferences
7697: &writecoursepref($udom.'_'.$uname,
7698: ('description' => $description,
7699: 'url' => $topurl,
7700: 'internal.creator' => $env{'user.name'}.':'.
7701: $env{'user.domain'},
7702: 'internal.created' => $now,
7703: 'internal.creationcontext' => $context)
7704: );
7705: return '/'.$udom.'/'.$uname;
7706: }
7707:
7708: # ------------------------------------------------------------------- Create ID
7709: sub generate_coursenum {
7710: my ($udom,$crstype) = @_;
7711: my $domdesc = &domain($udom);
7712: return 'error: invalid domain' if ($domdesc eq '');
7713: my $first;
7714: if ($crstype eq 'Community') {
7715: $first = '0';
7716: } else {
7717: $first = int(1+rand(9));
7718: }
7719: my $uname=$first.
7720: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7721: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7722: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7723: # ----------------------------------------------- Make sure that does not exist
7724: my $uhome=&homeserver($uname,$udom,'true');
7725: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7726: if ($crstype eq 'Community') {
7727: $first = '0';
7728: } else {
7729: $first = int(1+rand(9));
7730: }
7731: $uname=$first.
7732: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7733: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7734: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7735: $uhome=&homeserver($uname,$udom,'true');
7736: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7737: return 'error: unable to generate unique course-ID';
7738: }
7739: }
7740: return $uname;
7741: }
7742:
7743: sub is_course {
7744: my ($cdom,$cnum) = @_;
7745: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
7746: undef,'.');
7747: if (exists($courses{$cdom.'_'.$cnum})) {
7748: return 1;
7749: }
7750: return 0;
7751: }
7752:
7753: sub store_userdata {
7754: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
7755: my $result;
7756: if ($datakey ne '') {
7757: if (ref($storehash) eq 'HASH') {
7758: if ($udom eq '' || $uname eq '') {
7759: $udom = $env{'user.domain'};
7760: $uname = $env{'user.name'};
7761: }
7762: my $uhome=&homeserver($uname,$udom);
7763: if (($uhome eq '') || ($uhome eq 'no_host')) {
7764: $result = 'error: no_host';
7765: } else {
7766: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7767: $storehash->{'host'} = $perlvar{'lonHostID'};
7768:
7769: my $namevalue='';
7770: foreach my $key (keys(%{$storehash})) {
7771: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7772: }
7773: $namevalue=~s/\&$//;
7774: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7775: $namevalue,$uhome);
7776: }
7777: } else {
7778: $result = 'error: data to store was not a hash reference';
7779: }
7780: } else {
7781: $result= 'error: invalid requestkey';
7782: }
7783: return $result;
7784: }
7785:
7786: # ---------------------------------------------------------- Assign Custom Role
7787:
7788: sub assigncustomrole {
7789: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
7790: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
7791: $end,$start,$deleteflag,$selfenroll,$context);
7792: }
7793:
7794: # ----------------------------------------------------------------- Revoke Role
7795:
7796: sub revokerole {
7797: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
7798: my $now=time;
7799: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
7800: }
7801:
7802: # ---------------------------------------------------------- Revoke Custom Role
7803:
7804: sub revokecustomrole {
7805: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
7806: my $now=time;
7807: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
7808: $deleteflag,$selfenroll,$context);
7809: }
7810:
7811: # ------------------------------------------------------------ Disk usage
7812: sub diskusage {
7813: my ($udom,$uname,$directorypath,$getpropath)=@_;
7814: $directorypath =~ s/\/$//;
7815: my $listing=&reply('du2:'.&escape($directorypath).':'
7816: .&escape($getpropath).':'.&escape($uname).':'
7817: .&escape($udom),homeserver($uname,$udom));
7818: if ($listing eq 'unknown_cmd') {
7819: if ($getpropath) {
7820: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7821: }
7822: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7823: }
7824: return $listing;
7825: }
7826:
7827: sub is_locked {
7828: my ($file_name, $domain, $user, $which) = @_;
7829: my @check;
7830: my $is_locked;
7831: push (@check,$file_name);
7832: my %locked = &get('file_permissions',\@check,
7833: $env{'user.domain'},$env{'user.name'});
7834: my ($tmp)=keys(%locked);
7835: if ($tmp=~/^error:/) { undef(%locked); }
7836:
7837: if (ref($locked{$file_name}) eq 'ARRAY') {
7838: $is_locked = 'false';
7839: foreach my $entry (@{$locked{$file_name}}) {
7840: if (ref($entry) eq 'ARRAY') {
7841: $is_locked = 'true';
7842: if (ref($which) eq 'ARRAY') {
7843: push(@{$which},$entry);
7844: } else {
7845: last;
7846: }
7847: }
7848: }
7849: } else {
7850: $is_locked = 'false';
7851: }
7852: return $is_locked;
7853: }
7854:
7855: sub declutter_portfile {
7856: my ($file) = @_;
7857: $file =~ s{^(/portfolio/|portfolio/)}{/};
7858: return $file;
7859: }
7860:
7861: # ------------------------------------------------------------- Mark as Read Only
7862:
7863: sub mark_as_readonly {
7864: my ($domain,$user,$files,$what) = @_;
7865: my %current_permissions = &dump('file_permissions',$domain,$user);
7866: my ($tmp)=keys(%current_permissions);
7867: if ($tmp=~/^error:/) { undef(%current_permissions); }
7868: foreach my $file (@{$files}) {
7869: $file = &declutter_portfile($file);
7870: push(@{$current_permissions{$file}},$what);
7871: }
7872: &put('file_permissions',\%current_permissions,$domain,$user);
7873: return;
7874: }
7875:
7876: # ------------------------------------------------------------Save Selected Files
7877:
7878: sub save_selected_files {
7879: my ($user, $path, @files) = @_;
7880: my $filename = $user."savedfiles";
7881: my @other_files = &files_not_in_path($user, $path);
7882: open (OUT, '>'.$tmpdir.$filename);
7883: foreach my $file (@files) {
7884: print (OUT $env{'form.currentpath'}.$file."\n");
7885: }
7886: foreach my $file (@other_files) {
7887: print (OUT $file."\n");
7888: }
7889: close (OUT);
7890: return 'ok';
7891: }
7892:
7893: sub clear_selected_files {
7894: my ($user) = @_;
7895: my $filename = $user."savedfiles";
7896: open (OUT, '>'.LONCAPA::tempdir().$filename);
7897: print (OUT undef);
7898: close (OUT);
7899: return ("ok");
7900: }
7901:
7902: sub files_in_path {
7903: my ($user, $path) = @_;
7904: my $filename = $user."savedfiles";
7905: my %return_files;
7906: open (IN, '<'.LONCAPA::tempdir().$filename);
7907: while (my $line_in = <IN>) {
7908: chomp ($line_in);
7909: my @paths_and_file = split (m!/!, $line_in);
7910: my $file_part = pop (@paths_and_file);
7911: my $path_part = join ('/', @paths_and_file);
7912: $path_part.='/';
7913: my $path_and_file = $path_part.$file_part;
7914: if ($path_part eq $path) {
7915: $return_files{$file_part}= 'selected';
7916: }
7917: }
7918: close (IN);
7919: return (\%return_files);
7920: }
7921:
7922: # called in portfolio select mode, to show files selected NOT in current directory
7923: sub files_not_in_path {
7924: my ($user, $path) = @_;
7925: my $filename = $user."savedfiles";
7926: my @return_files;
7927: my $path_part;
7928: open(IN, '<'.LONCAPA::.$filename);
7929: while (my $line = <IN>) {
7930: #ok, I know it's clunky, but I want it to work
7931: my @paths_and_file = split(m|/|, $line);
7932: my $file_part = pop(@paths_and_file);
7933: chomp($file_part);
7934: my $path_part = join('/', @paths_and_file);
7935: $path_part .= '/';
7936: my $path_and_file = $path_part.$file_part;
7937: if ($path_part ne $path) {
7938: push(@return_files, ($path_and_file));
7939: }
7940: }
7941: close(OUT);
7942: return (@return_files);
7943: }
7944:
7945: #----------------------------------------------Get portfolio file permissions
7946:
7947: sub get_portfile_permissions {
7948: my ($domain,$user) = @_;
7949: my %current_permissions = &dump('file_permissions',$domain,$user);
7950: my ($tmp)=keys(%current_permissions);
7951: if ($tmp=~/^error:/) { undef(%current_permissions); }
7952: return \%current_permissions;
7953: }
7954:
7955: #---------------------------------------------Get portfolio file access controls
7956:
7957: sub get_access_controls {
7958: my ($current_permissions,$group,$file) = @_;
7959: my %access;
7960: my $real_file = $file;
7961: $file =~ s/\.meta$//;
7962: if (defined($file)) {
7963: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7964: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
7965: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
7966: }
7967: }
7968: } else {
7969: foreach my $key (keys(%{$current_permissions})) {
7970: if ($key =~ /\0accesscontrol$/) {
7971: if (defined($group)) {
7972: if ($key !~ m-^\Q$group\E/-) {
7973: next;
7974: }
7975: }
7976: my ($fullpath) = split(/\0/,$key);
7977: if (ref($$current_permissions{$key}) eq 'HASH') {
7978: foreach my $control (keys(%{$$current_permissions{$key}})) {
7979: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7980: }
7981: }
7982: }
7983: }
7984: }
7985: return %access;
7986: }
7987:
7988: sub modify_access_controls {
7989: my ($file_name,$changes,$domain,$user)=@_;
7990: my ($outcome,$deloutcome);
7991: my %store_permissions;
7992: my %new_values;
7993: my %new_control;
7994: my %translation;
7995: my @deletions = ();
7996: my $now = time;
7997: if (exists($$changes{'activate'})) {
7998: if (ref($$changes{'activate'}) eq 'HASH') {
7999: my @newitems = sort(keys(%{$$changes{'activate'}}));
8000: my $numnew = scalar(@newitems);
8001: for (my $i=0; $i<$numnew; $i++) {
8002: my $newkey = $newitems[$i];
8003: my $newid = &Apache::loncommon::get_cgi_id();
8004: if ($newkey =~ /^\d+:/) {
8005: $newkey =~ s/^(\d+)/$newid/;
8006: $translation{$1} = $newid;
8007: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8008: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8009: $translation{$1} = $newid;
8010: }
8011: $new_values{$file_name."\0".$newkey} =
8012: $$changes{'activate'}{$newitems[$i]};
8013: $new_control{$newkey} = $now;
8014: }
8015: }
8016: }
8017: my %todelete;
8018: my %changed_items;
8019: foreach my $action ('delete','update') {
8020: if (exists($$changes{$action})) {
8021: if (ref($$changes{$action}) eq 'HASH') {
8022: foreach my $key (keys(%{$$changes{$action}})) {
8023: my ($itemnum) = ($key =~ /^([^:]+):/);
8024: if ($action eq 'delete') {
8025: $todelete{$itemnum} = 1;
8026: } else {
8027: $changed_items{$itemnum} = $key;
8028: }
8029: }
8030: }
8031: }
8032: }
8033: # get lock on access controls for file.
8034: my $lockhash = {
8035: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8036: ':'.$env{'user.domain'},
8037: };
8038: my $tries = 0;
8039: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8040:
8041: while (($gotlock ne 'ok') && $tries <3) {
8042: $tries ++;
8043: sleep 1;
8044: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8045: }
8046: if ($gotlock eq 'ok') {
8047: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8048: my ($tmp)=keys(%curr_permissions);
8049: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8050: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8051: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8052: if (ref($curr_controls) eq 'HASH') {
8053: foreach my $control_item (keys(%{$curr_controls})) {
8054: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8055: if (defined($todelete{$itemnum})) {
8056: push(@deletions,$file_name."\0".$control_item);
8057: } else {
8058: if (defined($changed_items{$itemnum})) {
8059: $new_control{$changed_items{$itemnum}} = $now;
8060: push(@deletions,$file_name."\0".$control_item);
8061: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8062: } else {
8063: $new_control{$control_item} = $$curr_controls{$control_item};
8064: }
8065: }
8066: }
8067: }
8068: }
8069: my ($group);
8070: if (&is_course($domain,$user)) {
8071: ($group,my $file) = split(/\//,$file_name,2);
8072: }
8073: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8074: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8075: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8076: # remove lock
8077: my @del_lock = ($file_name."\0".'locked_access_records');
8078: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
8079: my $sqlresult =
8080: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
8081: $group);
8082: } else {
8083: $outcome = "error: could not obtain lockfile\n";
8084: }
8085: return ($outcome,$deloutcome,\%new_values,\%translation);
8086: }
8087:
8088: sub make_public_indefinitely {
8089: my ($requrl) = @_;
8090: my $now = time;
8091: my $action = 'activate';
8092: my $aclnum = 0;
8093: if (&is_portfolio_url($requrl)) {
8094: my (undef,$udom,$unum,$file_name,$group) =
8095: &parse_portfolio_url($requrl);
8096: my $current_perms = &get_portfile_permissions($udom,$unum);
8097: my %access_controls = &get_access_controls($current_perms,
8098: $group,$file_name);
8099: foreach my $key (keys(%{$access_controls{$file_name}})) {
8100: my ($num,$scope,$end,$start) =
8101: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8102: if ($scope eq 'public') {
8103: if ($start <= $now && $end == 0) {
8104: $action = 'none';
8105: } else {
8106: $action = 'update';
8107: $aclnum = $num;
8108: }
8109: last;
8110: }
8111: }
8112: if ($action eq 'none') {
8113: return 'ok';
8114: } else {
8115: my %changes;
8116: my $newend = 0;
8117: my $newstart = $now;
8118: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8119: $changes{$action}{$newkey} = {
8120: type => 'public',
8121: time => {
8122: start => $newstart,
8123: end => $newend,
8124: },
8125: };
8126: my ($outcome,$deloutcome,$new_values,$translation) =
8127: &modify_access_controls($file_name,\%changes,$udom,$unum);
8128: return $outcome;
8129: }
8130: } else {
8131: return 'invalid';
8132: }
8133: }
8134:
8135: #------------------------------------------------------Get Marked as Read Only
8136:
8137: sub get_marked_as_readonly {
8138: my ($domain,$user,$what,$group) = @_;
8139: my $current_permissions = &get_portfile_permissions($domain,$user);
8140: my @readonly_files;
8141: my $cmp1=$what;
8142: if (ref($what)) { $cmp1=join('',@{$what}) };
8143: while (my ($file_name,$value) = each(%{$current_permissions})) {
8144: if (defined($group)) {
8145: if ($file_name !~ m-^\Q$group\E/-) {
8146: next;
8147: }
8148: }
8149: if (ref($value) eq "ARRAY"){
8150: foreach my $stored_what (@{$value}) {
8151: my $cmp2=$stored_what;
8152: if (ref($stored_what) eq 'ARRAY') {
8153: $cmp2=join('',@{$stored_what});
8154: }
8155: if ($cmp1 eq $cmp2) {
8156: push(@readonly_files, $file_name);
8157: last;
8158: } elsif (!defined($what)) {
8159: push(@readonly_files, $file_name);
8160: last;
8161: }
8162: }
8163: }
8164: }
8165: return @readonly_files;
8166: }
8167: #-----------------------------------------------------------Get Marked as Read Only Hash
8168:
8169: sub get_marked_as_readonly_hash {
8170: my ($current_permissions,$group,$what) = @_;
8171: my %readonly_files;
8172: while (my ($file_name,$value) = each(%{$current_permissions})) {
8173: if (defined($group)) {
8174: if ($file_name !~ m-^\Q$group\E/-) {
8175: next;
8176: }
8177: }
8178: if (ref($value) eq "ARRAY"){
8179: foreach my $stored_what (@{$value}) {
8180: if (ref($stored_what) eq 'ARRAY') {
8181: foreach my $lock_descriptor(@{$stored_what}) {
8182: if ($lock_descriptor eq 'graded') {
8183: $readonly_files{$file_name} = 'graded';
8184: } elsif ($lock_descriptor eq 'handback') {
8185: $readonly_files{$file_name} = 'handback';
8186: } else {
8187: if (!exists($readonly_files{$file_name})) {
8188: $readonly_files{$file_name} = 'locked';
8189: }
8190: }
8191: }
8192: }
8193: }
8194: }
8195: }
8196: return %readonly_files;
8197: }
8198: # ------------------------------------------------------------ Unmark as Read Only
8199:
8200: sub unmark_as_readonly {
8201: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8202: # for portfolio submissions, $what contains [$symb,$crsid]
8203: my ($domain,$user,$what,$file_name,$group) = @_;
8204: $file_name = &declutter_portfile($file_name);
8205: my $symb_crs = $what;
8206: if (ref($what)) { $symb_crs=join('',@$what); }
8207: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
8208: my ($tmp)=keys(%current_permissions);
8209: if ($tmp=~/^error:/) { undef(%current_permissions); }
8210: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
8211: foreach my $file (@readonly_files) {
8212: my $clean_file = &declutter_portfile($file);
8213: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
8214: my $current_locks = $current_permissions{$file};
8215: my @new_locks;
8216: my @del_keys;
8217: if (ref($current_locks) eq "ARRAY"){
8218: foreach my $locker (@{$current_locks}) {
8219: my $compare=$locker;
8220: if (ref($locker) eq 'ARRAY') {
8221: $compare=join('',@{$locker});
8222: if ($compare ne $symb_crs) {
8223: push(@new_locks, $locker);
8224: }
8225: }
8226: }
8227: if (scalar(@new_locks) > 0) {
8228: $current_permissions{$file} = \@new_locks;
8229: } else {
8230: push(@del_keys, $file);
8231: &del('file_permissions',\@del_keys, $domain, $user);
8232: delete($current_permissions{$file});
8233: }
8234: }
8235: }
8236: &put('file_permissions',\%current_permissions,$domain,$user);
8237: return;
8238: }
8239:
8240: # ------------------------------------------------------------ Directory lister
8241:
8242: sub dirlist {
8243: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
8244: $uri=~s/^\///;
8245: $uri=~s/\/$//;
8246: my ($udom, $uname);
8247: if ($getuserdir) {
8248: $udom = $userdomain;
8249: $uname = $username;
8250: } else {
8251: (undef,$udom,$uname)=split(/\//,$uri);
8252: if(defined($userdomain)) {
8253: $udom = $userdomain;
8254: }
8255: if(defined($username)) {
8256: $uname = $username;
8257: }
8258: }
8259: my ($dirRoot,$listing,@listing_results);
8260:
8261: $dirRoot = $perlvar{'lonDocRoot'};
8262: if (defined($getpropath)) {
8263: $dirRoot = &propath($udom,$uname);
8264: $dirRoot =~ s/\/$//;
8265: } elsif (defined($getuserdir)) {
8266: my $subdir=$uname.'__';
8267: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8268: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8269: ."/$udom/$subdir/$uname";
8270: } elsif (defined($alternateRoot)) {
8271: $dirRoot = $alternateRoot;
8272: }
8273:
8274: if($udom) {
8275: if($uname) {
8276: my $uhome = &homeserver($uname,$udom);
8277: if ($uhome eq 'no_host') {
8278: return ([],'no_host');
8279: }
8280: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
8281: .$getuserdir.':'.&escape($dirRoot)
8282: .':'.&escape($uname).':'.&escape($udom),$uhome);
8283: if ($listing eq 'unknown_cmd') {
8284: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
8285: } else {
8286: @listing_results = map { &unescape($_); } split(/:/,$listing);
8287: }
8288: if ($listing eq 'unknown_cmd') {
8289: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
8290: @listing_results = split(/:/,$listing);
8291: } else {
8292: @listing_results = map { &unescape($_); } split(/:/,$listing);
8293: }
8294: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8295: ($listing eq 'rejected') || ($listing eq 'refused') ||
8296: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8297: return ([],$listing);
8298: } else {
8299: return (\@listing_results);
8300: }
8301: } elsif(!$alternateRoot) {
8302: my (%allusers,%listerror);
8303: my %servers = &get_servers($udom,'library');
8304: foreach my $tryserver (keys(%servers)) {
8305: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8306: &escape($udom),$tryserver);
8307: if ($listing eq 'unknown_cmd') {
8308: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8309: $udom, $tryserver);
8310: } else {
8311: @listing_results = map { &unescape($_); } split(/:/,$listing);
8312: }
8313: if ($listing eq 'unknown_cmd') {
8314: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8315: $udom, $tryserver);
8316: @listing_results = split(/:/,$listing);
8317: } else {
8318: @listing_results =
8319: map { &unescape($_); } split(/:/,$listing);
8320: }
8321: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8322: ($listing eq 'rejected') || ($listing eq 'refused') ||
8323: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8324: $listerror{$tryserver} = $listing;
8325: } else {
8326: foreach my $line (@listing_results) {
8327: my ($entry) = split(/&/,$line,2);
8328: $allusers{$entry} = 1;
8329: }
8330: }
8331: }
8332: my @alluserslist=();
8333: foreach my $user (sort(keys(%allusers))) {
8334: push(@alluserslist,$user.'&user');
8335: }
8336: return (\@alluserslist);
8337: } else {
8338: return ([],'missing username');
8339: }
8340: } elsif(!defined($getpropath)) {
8341: my $path = $perlvar{'lonDocRoot'}.'/res/';
8342: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8343: return (\@all_domains);
8344: } else {
8345: return ([],'missing domain');
8346: }
8347: }
8348:
8349: # --------------------------------------------- GetFileTimestamp
8350: # This function utilizes dirlist and returns the date stamp for
8351: # when it was last modified. It will also return an error of -1
8352: # if an error occurs
8353:
8354: sub GetFileTimestamp {
8355: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
8356: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8357: $studentName = &LONCAPA::clean_username($studentName);
8358: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8359: undef,$getuserdir);
8360: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8361: return -1;
8362: }
8363: if (ref($fileref) eq 'ARRAY') {
8364: my @stats = split('&',$fileref->[0]);
8365: # @stats contains first the filename, then the stat output
8366: return $stats[10]; # so this is 10 instead of 9.
8367: } else {
8368: return -1;
8369: }
8370: }
8371:
8372: sub stat_file {
8373: my ($uri) = @_;
8374: $uri = &clutter_with_no_wrapper($uri);
8375:
8376: my ($udom,$uname,$file);
8377: if ($uri =~ m-^/(uploaded|editupload)/-) {
8378: ($udom,$uname,$file) =
8379: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8380: $file = 'userfiles/'.$file;
8381: }
8382: if ($uri =~ m-^/res/-) {
8383: ($udom,$uname) =
8384: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8385: $file = $uri;
8386: }
8387:
8388: if (!$udom || !$uname || !$file) {
8389: # unable to handle the uri
8390: return ();
8391: }
8392: my $getpropath;
8393: if ($file =~ /^userfiles\//) {
8394: $getpropath = 1;
8395: }
8396: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8397: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8398: return ();
8399: } else {
8400: if (ref($listref) eq 'ARRAY') {
8401: my @stats = split('&',$listref->[0]);
8402: shift(@stats); #filename is first
8403: return @stats;
8404: }
8405: }
8406: return ();
8407: }
8408:
8409: # -------------------------------------------------------- Value of a Condition
8410:
8411: # gets the value of a specific preevaluated condition
8412: # stored in the string $env{user.state.<cid>}
8413: # or looks up a condition reference in the bighash and if if hasn't
8414: # already been evaluated recurses into docondval to get the value of
8415: # the condition, then memoizing it to
8416: # $env{user.state.<cid>.<condition>}
8417: sub directcondval {
8418: my $number=shift;
8419: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8420: &Apache::lonuserstate::evalstate();
8421: }
8422: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8423: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8424: } elsif ($number =~ /^_/) {
8425: my $sub_condition;
8426: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8427: &GDBM_READER(),0640)) {
8428: $sub_condition=$bighash{'conditions'.$number};
8429: untie(%bighash);
8430: }
8431: my $value = &docondval($sub_condition);
8432: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8433: return $value;
8434: }
8435: if ($env{'user.state.'.$env{'request.course.id'}}) {
8436: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8437: } else {
8438: return 2;
8439: }
8440: }
8441:
8442: # get the collection of conditions for this resource
8443: sub condval {
8444: my $condidx=shift;
8445: my $allpathcond='';
8446: foreach my $cond (split(/\|/,$condidx)) {
8447: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8448: $allpathcond.=
8449: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8450: }
8451: }
8452: $allpathcond=~s/\|$//;
8453: return &docondval($allpathcond);
8454: }
8455:
8456: #evaluates an expression of conditions
8457: sub docondval {
8458: my ($allpathcond) = @_;
8459: my $result=0;
8460: if ($env{'request.course.id'}
8461: && defined($allpathcond)) {
8462: my $operand='|';
8463: my @stack;
8464: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8465: if ($chunk eq '(') {
8466: push @stack,($operand,$result);
8467: } elsif ($chunk eq ')') {
8468: my $before=pop @stack;
8469: if (pop @stack eq '&') {
8470: $result=$result>$before?$before:$result;
8471: } else {
8472: $result=$result>$before?$result:$before;
8473: }
8474: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8475: $operand=$chunk;
8476: } else {
8477: my $new=directcondval($chunk);
8478: if ($operand eq '&') {
8479: $result=$result>$new?$new:$result;
8480: } else {
8481: $result=$result>$new?$result:$new;
8482: }
8483: }
8484: }
8485: }
8486: return $result;
8487: }
8488:
8489: # ---------------------------------------------------- Devalidate courseresdata
8490:
8491: sub devalidatecourseresdata {
8492: my ($coursenum,$coursedomain)=@_;
8493: my $hashid=$coursenum.':'.$coursedomain;
8494: &devalidate_cache_new('courseres',$hashid);
8495: }
8496:
8497:
8498: # --------------------------------------------------- Course Resourcedata Query
8499: #
8500: # Parameters:
8501: # $coursenum - Number of the course.
8502: # $coursedomain - Domain at which the course was created.
8503: # Returns:
8504: # A hash of the course parameters along (I think) with timestamps
8505: # and version info.
8506:
8507: sub get_courseresdata {
8508: my ($coursenum,$coursedomain)=@_;
8509: my $coursehom=&homeserver($coursenum,$coursedomain);
8510: my $hashid=$coursenum.':'.$coursedomain;
8511: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8512: my %dumpreply;
8513: unless (defined($cached)) {
8514: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8515: $result=\%dumpreply;
8516: my ($tmp) = keys(%dumpreply);
8517: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8518: &do_cache_new('courseres',$hashid,$result,600);
8519: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8520: return $tmp;
8521: } elsif ($tmp =~ /^(error)/) {
8522: $result=undef;
8523: &do_cache_new('courseres',$hashid,$result,600);
8524: }
8525: }
8526: return $result;
8527: }
8528:
8529: sub devalidateuserresdata {
8530: my ($uname,$udom)=@_;
8531: my $hashid="$udom:$uname";
8532: &devalidate_cache_new('userres',$hashid);
8533: }
8534:
8535: sub get_userresdata {
8536: my ($uname,$udom)=@_;
8537: #most student don\'t have any data set, check if there is some data
8538: if (&EXT_cache_status($udom,$uname)) { return undef; }
8539:
8540: my $hashid="$udom:$uname";
8541: my ($result,$cached)=&is_cached_new('userres',$hashid);
8542: if (!defined($cached)) {
8543: my %resourcedata=&dump('resourcedata',$udom,$uname);
8544: $result=\%resourcedata;
8545: &do_cache_new('userres',$hashid,$result,600);
8546: }
8547: my ($tmp)=keys(%$result);
8548: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8549: return $result;
8550: }
8551: #error 2 occurs when the .db doesn't exist
8552: if ($tmp!~/error: 2 /) {
8553: &logthis("<font color=\"blue\">WARNING:".
8554: " Trying to get resource data for ".
8555: $uname." at ".$udom.": ".
8556: $tmp."</font>");
8557: } elsif ($tmp=~/error: 2 /) {
8558: #&EXT_cache_set($udom,$uname);
8559: &do_cache_new('userres',$hashid,undef,600);
8560: undef($tmp); # not really an error so don't send it back
8561: }
8562: return $tmp;
8563: }
8564: #----------------------------------------------- resdata - return resource data
8565: # Purpose:
8566: # Return resource data for either users or for a course.
8567: # Parameters:
8568: # $name - Course/user name.
8569: # $domain - Name of the domain the user/course is registered on.
8570: # $type - Type of thing $name is (must be 'course' or 'user'
8571: # @which - Array of names of resources desired.
8572: # Returns:
8573: # The value of the first reasource in @which that is found in the
8574: # resource hash.
8575: # Exceptional Conditions:
8576: # If the $type passed in is not valid (not the string 'course' or
8577: # 'user', an undefined reference is returned.
8578: # If none of the resources are found, an undef is returned
8579: sub resdata {
8580: my ($name,$domain,$type,@which)=@_;
8581: my $result;
8582: if ($type eq 'course') {
8583: $result=&get_courseresdata($name,$domain);
8584: } elsif ($type eq 'user') {
8585: $result=&get_userresdata($name,$domain);
8586: }
8587: if (!ref($result)) { return $result; }
8588: foreach my $item (@which) {
8589: if (defined($result->{$item->[0]})) {
8590: return [$result->{$item->[0]},$item->[1]];
8591: }
8592: }
8593: return undef;
8594: }
8595:
8596: #
8597: # EXT resource caching routines
8598: #
8599:
8600: sub clear_EXT_cache_status {
8601: &delenv('cache.EXT.');
8602: }
8603:
8604: sub EXT_cache_status {
8605: my ($target_domain,$target_user) = @_;
8606: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8607: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8608: # We know already the user has no data
8609: return 1;
8610: } else {
8611: return 0;
8612: }
8613: }
8614:
8615: sub EXT_cache_set {
8616: my ($target_domain,$target_user) = @_;
8617: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8618: #&appenv({$cachename => time});
8619: }
8620:
8621: # --------------------------------------------------------- Value of a Variable
8622: sub EXT {
8623:
8624: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8625: unless ($varname) { return ''; }
8626: #get real user name/domain, courseid and symb
8627: my $courseid;
8628: my $publicuser;
8629: if ($symbparm) {
8630: $symbparm=&get_symb_from_alias($symbparm);
8631: }
8632: if (!($uname && $udom)) {
8633: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8634: if (!$symbparm) { $symbparm=$cursymb; }
8635: } else {
8636: $courseid=$env{'request.course.id'};
8637: }
8638: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8639: my $rest;
8640: if (defined($therest[0])) {
8641: $rest=join('.',@therest);
8642: } else {
8643: $rest='';
8644: }
8645:
8646: my $qualifierrest=$qualifier;
8647: if ($rest) { $qualifierrest.='.'.$rest; }
8648: my $spacequalifierrest=$space;
8649: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
8650: if ($realm eq 'user') {
8651: # --------------------------------------------------------------- user.resource
8652: if ($space eq 'resource') {
8653: if ( (defined($Apache::lonhomework::parsing_a_problem)
8654: || defined($Apache::lonhomework::parsing_a_task))
8655: &&
8656: ($symbparm eq &symbread()) ) {
8657: # if we are in the middle of processing the resource the
8658: # get the value we are planning on committing
8659: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8660: return $Apache::lonhomework::results{$qualifierrest};
8661: } else {
8662: return $Apache::lonhomework::history{$qualifierrest};
8663: }
8664: } else {
8665: my %restored;
8666: if ($publicuser || $env{'request.state'} eq 'construct') {
8667: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8668: } else {
8669: %restored=&restore($symbparm,$courseid,$udom,$uname);
8670: }
8671: return $restored{$qualifierrest};
8672: }
8673: # ----------------------------------------------------------------- user.access
8674: } elsif ($space eq 'access') {
8675: # FIXME - not supporting calls for a specific user
8676: return &allowed($qualifier,$rest);
8677: # ------------------------------------------ user.preferences, user.environment
8678: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
8679: if (($uname eq $env{'user.name'}) &&
8680: ($udom eq $env{'user.domain'})) {
8681: return $env{join('.',('environment',$qualifierrest))};
8682: } else {
8683: my %returnhash;
8684: if (!$publicuser) {
8685: %returnhash=&userenvironment($udom,$uname,
8686: $qualifierrest);
8687: }
8688: return $returnhash{$qualifierrest};
8689: }
8690: # ----------------------------------------------------------------- user.course
8691: } elsif ($space eq 'course') {
8692: # FIXME - not supporting calls for a specific user
8693: return $env{join('.',('request.course',$qualifier))};
8694: # ------------------------------------------------------------------- user.role
8695: } elsif ($space eq 'role') {
8696: # FIXME - not supporting calls for a specific user
8697: my ($role,$where)=split(/\./,$env{'request.role'});
8698: if ($qualifier eq 'value') {
8699: return $role;
8700: } elsif ($qualifier eq 'extent') {
8701: return $where;
8702: }
8703: # ----------------------------------------------------------------- user.domain
8704: } elsif ($space eq 'domain') {
8705: return $udom;
8706: # ------------------------------------------------------------------- user.name
8707: } elsif ($space eq 'name') {
8708: return $uname;
8709: # ---------------------------------------------------- Any other user namespace
8710: } else {
8711: my %reply;
8712: if (!$publicuser) {
8713: %reply=&get($space,[$qualifierrest],$udom,$uname);
8714: }
8715: return $reply{$qualifierrest};
8716: }
8717: } elsif ($realm eq 'query') {
8718: # ---------------------------------------------- pull stuff out of query string
8719: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8720: [$spacequalifierrest]);
8721: return $env{'form.'.$spacequalifierrest};
8722: } elsif ($realm eq 'request') {
8723: # ------------------------------------------------------------- request.browser
8724: if ($space eq 'browser') {
8725: return $env{'browser.'.$qualifier};
8726: # ------------------------------------------------------------ request.filename
8727: } else {
8728: return $env{'request.'.$spacequalifierrest};
8729: }
8730: } elsif ($realm eq 'course') {
8731: # ---------------------------------------------------------- course.description
8732: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
8733: } elsif ($realm eq 'resource') {
8734:
8735: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
8736: if (!$symbparm) { $symbparm=&symbread(); }
8737: }
8738:
8739: if ($space eq 'title') {
8740: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8741: return &gettitle($symbparm);
8742: }
8743:
8744: if ($space eq 'map') {
8745: my ($map) = &decode_symb($symbparm);
8746: return &symbread($map);
8747: }
8748: if ($space eq 'filename') {
8749: if ($symbparm) {
8750: return &clutter((&decode_symb($symbparm))[2]);
8751: }
8752: return &hreflocation('',$env{'request.filename'});
8753: }
8754:
8755: my ($section, $group, @groups);
8756: my ($courselevelm,$courselevel);
8757: if ($symbparm && defined($courseid) &&
8758: $courseid eq $env{'request.course.id'}) {
8759:
8760: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
8761:
8762: # ----------------------------------------------------- Cascading lookup scheme
8763: my $symbp=$symbparm;
8764: my $mapp=&deversion((&decode_symb($symbp))[0]);
8765:
8766: my $symbparm=$symbp.'.'.$spacequalifierrest;
8767: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8768:
8769: if (($env{'user.name'} eq $uname) &&
8770: ($env{'user.domain'} eq $udom)) {
8771: $section=$env{'request.course.sec'};
8772: @groups = split(/:/,$env{'request.course.groups'});
8773: @groups=&sort_course_groups($courseid,@groups);
8774: } else {
8775: if (! defined($usection)) {
8776: $section=&getsection($udom,$uname,$courseid);
8777: } else {
8778: $section = $usection;
8779: }
8780: @groups = &get_users_groups($udom,$uname,$courseid);
8781: }
8782:
8783: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8784: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8785: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8786:
8787: $courselevel=$courseid.'.'.$spacequalifierrest;
8788: my $courselevelr=$courseid.'.'.$symbparm;
8789: $courselevelm=$courseid.'.'.$mapparm;
8790:
8791: # ----------------------------------------------------------- first, check user
8792:
8793: my $userreply=&resdata($uname,$udom,'user',
8794: ([$courselevelr,'resource'],
8795: [$courselevelm,'map' ],
8796: [$courselevel, 'course' ]));
8797: if (defined($userreply)) { return &get_reply($userreply); }
8798:
8799: # ------------------------------------------------ second, check some of course
8800: my $coursereply;
8801: if (@groups > 0) {
8802: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8803: $mapparm,$spacequalifierrest);
8804: if (defined($coursereply)) { return &get_reply($coursereply); }
8805: }
8806:
8807: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8808: $env{'course.'.$courseid.'.domain'},
8809: 'course',
8810: ([$seclevelr, 'resource'],
8811: [$seclevelm, 'map' ],
8812: [$seclevel, 'course' ],
8813: [$courselevelr,'resource']));
8814: if (defined($coursereply)) { return &get_reply($coursereply); }
8815:
8816: # ------------------------------------------------------ third, check map parms
8817: my %parmhash=();
8818: my $thisparm='';
8819: if (tie(%parmhash,'GDBM_File',
8820: $env{'request.course.fn'}.'_parms.db',
8821: &GDBM_READER(),0640)) {
8822: $thisparm=$parmhash{$symbparm};
8823: untie(%parmhash);
8824: }
8825: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
8826: }
8827: # ------------------------------------------ fourth, look in resource metadata
8828:
8829: $spacequalifierrest=~s/\./\_/;
8830: my $filename;
8831: if (!$symbparm) { $symbparm=&symbread(); }
8832: if ($symbparm) {
8833: $filename=(&decode_symb($symbparm))[2];
8834: } else {
8835: $filename=$env{'request.filename'};
8836: }
8837: my $metadata=&metadata($filename,$spacequalifierrest);
8838: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8839: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
8840: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8841:
8842: # ---------------------------------------------- fourth, look in rest of course
8843: if ($symbparm && defined($courseid) &&
8844: $courseid eq $env{'request.course.id'}) {
8845: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8846: $env{'course.'.$courseid.'.domain'},
8847: 'course',
8848: ([$courselevelm,'map' ],
8849: [$courselevel, 'course']));
8850: if (defined($coursereply)) { return &get_reply($coursereply); }
8851: }
8852: # ------------------------------------------------------------------ Cascade up
8853: unless ($space eq '0') {
8854: my @parts=split(/_/,$space);
8855: my $id=pop(@parts);
8856: my $part=join('_',@parts);
8857: if ($part eq '') { $part='0'; }
8858: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
8859: $symbparm,$udom,$uname,$section,1);
8860: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
8861: }
8862: if ($recurse) { return undef; }
8863: my $pack_def=&packages_tab_default($filename,$varname);
8864: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
8865: # ---------------------------------------------------- Any other user namespace
8866: } elsif ($realm eq 'environment') {
8867: # ----------------------------------------------------------------- environment
8868: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8869: return $env{'environment.'.$spacequalifierrest};
8870: } else {
8871: if ($uname eq 'anonymous' && $udom eq '') {
8872: return '';
8873: }
8874: my %returnhash=&userenvironment($udom,$uname,
8875: $spacequalifierrest);
8876: return $returnhash{$spacequalifierrest};
8877: }
8878: } elsif ($realm eq 'system') {
8879: # ----------------------------------------------------------------- system.time
8880: if ($space eq 'time') {
8881: return time;
8882: }
8883: } elsif ($realm eq 'server') {
8884: # ----------------------------------------------------------------- system.time
8885: if ($space eq 'name') {
8886: return $ENV{'SERVER_NAME'};
8887: }
8888: }
8889: return '';
8890: }
8891:
8892: sub get_reply {
8893: my ($reply_value) = @_;
8894: if (ref($reply_value) eq 'ARRAY') {
8895: if (wantarray) {
8896: return @$reply_value;
8897: }
8898: return $reply_value->[0];
8899: } else {
8900: return $reply_value;
8901: }
8902: }
8903:
8904: sub check_group_parms {
8905: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8906: my @groupitems = ();
8907: my $resultitem;
8908: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
8909: foreach my $group (@{$groups}) {
8910: foreach my $level (@levels) {
8911: my $item = $courseid.'.['.$group.'].'.$level->[0];
8912: push(@groupitems,[$item,$level->[1]]);
8913: }
8914: }
8915: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8916: $env{'course.'.$courseid.'.domain'},
8917: 'course',@groupitems);
8918: return $coursereply;
8919: }
8920:
8921: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
8922: my ($courseid,@groups) = @_;
8923: @groups = sort(@groups);
8924: return @groups;
8925: }
8926:
8927: sub packages_tab_default {
8928: my ($uri,$varname)=@_;
8929: my (undef,$part,$name)=split(/\./,$varname);
8930:
8931: my (@extension,@specifics,$do_default);
8932: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
8933: my ($pack_type,$pack_part)=split(/_/,$package,2);
8934: if ($pack_type eq 'default') {
8935: $do_default=1;
8936: } elsif ($pack_type eq 'extension') {
8937: push(@extension,[$package,$pack_type,$pack_part]);
8938: } elsif ($pack_part eq $part || $pack_type eq 'part') {
8939: # only look at packages defaults for packages that this id is
8940: push(@specifics,[$package,$pack_type,$pack_part]);
8941: }
8942: }
8943: # first look for a package that matches the requested part id
8944: foreach my $package (@specifics) {
8945: my (undef,$pack_type,$pack_part)=@{$package};
8946: next if ($pack_part ne $part);
8947: if (defined($packagetab{"$pack_type&$name&default"})) {
8948: return $packagetab{"$pack_type&$name&default"};
8949: }
8950: }
8951: # look for any possible matching non extension_ package
8952: foreach my $package (@specifics) {
8953: my (undef,$pack_type,$pack_part)=@{$package};
8954: if (defined($packagetab{"$pack_type&$name&default"})) {
8955: return $packagetab{"$pack_type&$name&default"};
8956: }
8957: if ($pack_type eq 'part') { $pack_part='0'; }
8958: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8959: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
8960: }
8961: }
8962: # look for any posible extension_ match
8963: foreach my $package (@extension) {
8964: my ($package,$pack_type)=@{$package};
8965: if (defined($packagetab{"$pack_type&$name&default"})) {
8966: return $packagetab{"$pack_type&$name&default"};
8967: }
8968: if (defined($packagetab{$package."&$name&default"})) {
8969: return $packagetab{$package."&$name&default"};
8970: }
8971: }
8972: # look for a global default setting
8973: if ($do_default && defined($packagetab{"default&$name&default"})) {
8974: return $packagetab{"default&$name&default"};
8975: }
8976: return undef;
8977: }
8978:
8979: sub add_prefix_and_part {
8980: my ($prefix,$part)=@_;
8981: my $keyroot;
8982: if (defined($prefix) && $prefix !~ /^__/) {
8983: # prefix that has a part already
8984: $keyroot=$prefix;
8985: } elsif (defined($prefix)) {
8986: # prefix that is missing a part
8987: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8988: } else {
8989: # no prefix at all
8990: if (defined($part)) { $keyroot='_'.$part; }
8991: }
8992: return $keyroot;
8993: }
8994:
8995: # ---------------------------------------------------------------- Get metadata
8996:
8997: my %metaentry;
8998: my %importedpartids;
8999: sub metadata {
9000: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
9001: $uri=&declutter($uri);
9002: # if it is a non metadata possible uri return quickly
9003: if (($uri eq '') ||
9004: (($uri =~ m|^/*adm/|) &&
9005: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
9006: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
9007: return undef;
9008: }
9009: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
9010: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
9011: return undef;
9012: }
9013: my $filename=$uri;
9014: $uri=~s/\.meta$//;
9015: #
9016: # Is the metadata already cached?
9017: # Look at timestamp of caching
9018: # Everything is cached by the main uri, libraries are never directly cached
9019: #
9020: if (!defined($liburi)) {
9021: my ($result,$cached)=&is_cached_new('meta',$uri);
9022: if (defined($cached)) { return $result->{':'.$what}; }
9023: }
9024: {
9025: # Imported parts would go here
9026: my %importedids=();
9027: my @origfileimportpartids=();
9028: my $importedparts=0;
9029: #
9030: # Is this a recursive call for a library?
9031: #
9032: # if (! exists($metacache{$uri})) {
9033: # $metacache{$uri}={};
9034: # }
9035: my $cachetime = 60*60;
9036: if ($liburi) {
9037: $liburi=&declutter($liburi);
9038: $filename=$liburi;
9039: } else {
9040: &devalidate_cache_new('meta',$uri);
9041: undef(%metaentry);
9042: }
9043: my %metathesekeys=();
9044: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9045: my $metastring;
9046: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
9047: my $which = &hreflocation('','/'.($liburi || $uri));
9048: $metastring =
9049: &Apache::lonnet::ssi_body($which,
9050: ('grade_target' => 'meta'));
9051: $cachetime = 1; # only want this cached in the child not long term
9052: } elsif (($uri !~ m -^(editupload)/-) &&
9053: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9054: my $file=&filelocation('',&clutter($filename));
9055: #push(@{$metaentry{$uri.'.file'}},$file);
9056: $metastring=&getfile($file);
9057: }
9058: my $parser=HTML::LCParser->new(\$metastring);
9059: my $token;
9060: undef %metathesekeys;
9061: while ($token=$parser->get_token) {
9062: if ($token->[0] eq 'S') {
9063: if (defined($token->[2]->{'package'})) {
9064: #
9065: # This is a package - get package info
9066: #
9067: my $package=$token->[2]->{'package'};
9068: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9069: if (defined($token->[2]->{'id'})) {
9070: $keyroot.='_'.$token->[2]->{'id'};
9071: }
9072: if ($metaentry{':packages'}) {
9073: $metaentry{':packages'}.=','.$package.$keyroot;
9074: } else {
9075: $metaentry{':packages'}=$package.$keyroot;
9076: }
9077: foreach my $pack_entry (keys(%packagetab)) {
9078: my $part=$keyroot;
9079: $part=~s/^\_//;
9080: if ($pack_entry=~/^\Q$package\E\&/ ||
9081: $pack_entry=~/^\Q$package\E_0\&/) {
9082: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
9083: # ignore package.tab specified default values
9084: # here &package_tab_default() will fetch those
9085: if ($subp eq 'default') { next; }
9086: my $value=$packagetab{$pack_entry};
9087: my $unikey;
9088: if ($pack =~ /_0$/) {
9089: $unikey='parameter_0_'.$name;
9090: $part=0;
9091: } else {
9092: $unikey='parameter'.$keyroot.'_'.$name;
9093: }
9094: if ($subp eq 'display') {
9095: $value.=' [Part: '.$part.']';
9096: }
9097: $metaentry{':'.$unikey.'.part'}=$part;
9098: $metathesekeys{$unikey}=1;
9099: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9100: $metaentry{':'.$unikey.'.'.$subp}=$value;
9101: }
9102: if (defined($metaentry{':'.$unikey.'.default'})) {
9103: $metaentry{':'.$unikey}=
9104: $metaentry{':'.$unikey.'.default'};
9105: }
9106: }
9107: }
9108: } else {
9109: #
9110: # This is not a package - some other kind of start tag
9111: #
9112: my $entry=$token->[1];
9113: my $unikey='';
9114:
9115: if ($entry eq 'import') {
9116: #
9117: # Importing a library here
9118: #
9119: my $location=$parser->get_text('/import');
9120: my $dir=$filename;
9121: $dir=~s|[^/]*$||;
9122: $location=&filelocation($dir,$location);
9123:
9124: my $importmode=$token->[2]->{'importmode'};
9125: if ($importmode eq 'problem') {
9126: # Import as problem/response
9127: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9128: } elsif ($importmode eq 'part') {
9129: # Import as part(s)
9130: $importedparts=1;
9131: # We need to get the original file and the imported file to get the part order correct
9132: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9133: # Load and inspect original file
9134: if ($#origfileimportpartids<0) {
9135: undef(%importedpartids);
9136: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9137: my $origfile=&getfile($origfilelocation);
9138: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9139: }
9140:
9141: # Load and inspect imported file
9142: my $impfile=&getfile($location);
9143: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9144: if ($#impfilepartids>=0) {
9145: # This problem had parts
9146: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
9147: } else {
9148: # Importing by turning a single problem into a problem part
9149: # It gets the import-tags ID as part-ID
9150: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
9151: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
9152: }
9153: } else {
9154: # Normal import
9155: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9156: if (defined($token->[2]->{'id'})) {
9157: $unikey.='_'.$token->[2]->{'id'};
9158: }
9159: }
9160:
9161: if ($depthcount<20) {
9162: my $metadata =
9163: &metadata($uri,'keys', $location,$unikey,
9164: $depthcount+1);
9165: foreach my $meta (split(',',$metadata)) {
9166: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9167: $metathesekeys{$meta}=1;
9168: }
9169:
9170: }
9171: } else {
9172: #
9173: # Not importing, some other kind of non-package, non-library start tag
9174: #
9175: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9176: if (defined($token->[2]->{'id'})) {
9177: $unikey.='_'.$token->[2]->{'id'};
9178: }
9179: if (defined($token->[2]->{'name'})) {
9180: $unikey.='_'.$token->[2]->{'name'};
9181: }
9182: $metathesekeys{$unikey}=1;
9183: foreach my $param (@{$token->[3]}) {
9184: $metaentry{':'.$unikey.'.'.$param} =
9185: $token->[2]->{$param};
9186: }
9187: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
9188: my $default=$metaentry{':'.$unikey.'.default'};
9189: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9190: # only ws inside the tag, and not in default, so use default
9191: # as value
9192: $metaentry{':'.$unikey}=$default;
9193: } elsif ( $internaltext =~ /\S/ ) {
9194: # something interesting inside the tag
9195: $metaentry{':'.$unikey}=$internaltext;
9196: } else {
9197: # no interesting values, don't set a default
9198: }
9199: # end of not-a-package not-a-library import
9200: }
9201: # end of not-a-package start tag
9202: }
9203: # the next is the end of "start tag"
9204: }
9205: }
9206: my ($extension) = ($uri =~ /\.(\w+)$/);
9207: $extension = lc($extension);
9208: if ($extension eq 'htm') { $extension='html'; }
9209:
9210: foreach my $key (keys(%packagetab)) {
9211: #no specific packages #how's our extension
9212: if ($key!~/^extension_\Q$extension\E&/) { next; }
9213: &metadata_create_package_def($uri,$key,'extension_'.$extension,
9214: \%metathesekeys);
9215: }
9216:
9217: if (!exists($metaentry{':packages'})
9218: || $packagetab{"import_defaults&extension_$extension"}) {
9219: foreach my $key (keys(%packagetab)) {
9220: #no specific packages well let's get default then
9221: if ($key!~/^default&/) { next; }
9222: &metadata_create_package_def($uri,$key,'default',
9223: \%metathesekeys);
9224: }
9225: }
9226: # are there custom rights to evaluate
9227: if ($metaentry{':copyright'} eq 'custom') {
9228:
9229: #
9230: # Importing a rights file here
9231: #
9232: unless ($depthcount) {
9233: my $location=$metaentry{':customdistributionfile'};
9234: my $dir=$filename;
9235: $dir=~s|[^/]*$||;
9236: $location=&filelocation($dir,$location);
9237: my $rights_metadata =
9238: &metadata($uri,'keys',$location,'_rights',
9239: $depthcount+1);
9240: foreach my $rights (split(',',$rights_metadata)) {
9241: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9242: $metathesekeys{$rights}=1;
9243: }
9244: }
9245: }
9246: # uniqifiy package listing
9247: my %seen;
9248: my @uniq_packages =
9249: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9250: $metaentry{':packages'} = join(',',@uniq_packages);
9251:
9252: if ($importedparts) {
9253: # We had imported parts and need to rebuild partorder
9254: $metaentry{':partorder'}='';
9255: $metathesekeys{'partorder'}=1;
9256: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9257: if ($origfileimportpartids[$index] eq 'part') {
9258: # original part, part of the problem
9259: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9260: } else {
9261: # we have imported parts at this position
9262: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9263: }
9264: }
9265: $metaentry{':partorder'}=~s/^\,//;
9266: }
9267:
9268: $metaentry{':keys'} = join(',',keys(%metathesekeys));
9269: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9270: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
9271: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
9272: # this is the end of "was not already recently cached
9273: }
9274: return $metaentry{':'.$what};
9275: }
9276:
9277: sub metadata_create_package_def {
9278: my ($uri,$key,$package,$metathesekeys)=@_;
9279: my ($pack,$name,$subp)=split(/\&/,$key);
9280: if ($subp eq 'default') { next; }
9281:
9282: if (defined($metaentry{':packages'})) {
9283: $metaentry{':packages'}.=','.$package;
9284: } else {
9285: $metaentry{':packages'}=$package;
9286: }
9287: my $value=$packagetab{$key};
9288: my $unikey;
9289: $unikey='parameter_0_'.$name;
9290: $metaentry{':'.$unikey.'.part'}=0;
9291: $$metathesekeys{$unikey}=1;
9292: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9293: $metaentry{':'.$unikey.'.'.$subp}=$value;
9294: }
9295: if (defined($metaentry{':'.$unikey.'.default'})) {
9296: $metaentry{':'.$unikey}=
9297: $metaentry{':'.$unikey.'.default'};
9298: }
9299: }
9300:
9301: sub metadata_generate_part0 {
9302: my ($metadata,$metacache,$uri) = @_;
9303: my %allnames;
9304: foreach my $metakey (keys(%$metadata)) {
9305: if ($metakey=~/^parameter\_(.*)/) {
9306: my $part=$$metacache{':'.$metakey.'.part'};
9307: my $name=$$metacache{':'.$metakey.'.name'};
9308: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
9309: $allnames{$name}=$part;
9310: }
9311: }
9312: }
9313: foreach my $name (keys(%allnames)) {
9314: $$metadata{"parameter_0_$name"}=1;
9315: my $key=":parameter_0_$name";
9316: $$metacache{"$key.part"}='0';
9317: $$metacache{"$key.name"}=$name;
9318: $$metacache{"$key.type"}=$$metacache{':parameter_'.
9319: $allnames{$name}.'_'.$name.
9320: '.type'};
9321: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
9322: '.display'};
9323: my $expr='[Part: '.$allnames{$name}.']';
9324: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
9325: $$metacache{"$key.display"}=$olddis;
9326: }
9327: }
9328:
9329: # ------------------------------------------------------ Devalidate title cache
9330:
9331: sub devalidate_title_cache {
9332: my ($url)=@_;
9333: if (!$env{'request.course.id'}) { return; }
9334: my $symb=&symbread($url);
9335: if (!$symb) { return; }
9336: my $key=$env{'request.course.id'}."\0".$symb;
9337: &devalidate_cache_new('title',$key);
9338: }
9339:
9340: # ------------------------------------------------- Get the title of a course
9341:
9342: sub current_course_title {
9343: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9344: }
9345: # ------------------------------------------------- Get the title of a resource
9346:
9347: sub gettitle {
9348: my $urlsymb=shift;
9349: my $symb=&symbread($urlsymb);
9350: if ($symb) {
9351: my $key=$env{'request.course.id'}."\0".$symb;
9352: my ($result,$cached)=&is_cached_new('title',$key);
9353: if (defined($cached)) {
9354: return $result;
9355: }
9356: my ($map,$resid,$url)=&decode_symb($symb);
9357: my $title='';
9358: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9359: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9360: } else {
9361: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9362: &GDBM_READER(),0640)) {
9363: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9364: $title=$bighash{'title_'.$mapid.'.'.$resid};
9365: untie(%bighash);
9366: }
9367: }
9368: $title=~s/\&colon\;/\:/gs;
9369: if ($title) {
9370: return &do_cache_new('title',$key,$title,600);
9371: }
9372: $urlsymb=$url;
9373: }
9374: my $title=&metadata($urlsymb,'title');
9375: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9376: return $title;
9377: }
9378:
9379: sub get_slot {
9380: my ($which,$cnum,$cdom)=@_;
9381: if (!$cnum || !$cdom) {
9382: (undef,my $courseid)=&whichuser();
9383: $cdom=$env{'course.'.$courseid.'.domain'};
9384: $cnum=$env{'course.'.$courseid.'.num'};
9385: }
9386: my $key=join("\0",'slots',$cdom,$cnum,$which);
9387: my %slotinfo;
9388: if (exists($remembered{$key})) {
9389: $slotinfo{$which} = $remembered{$key};
9390: } else {
9391: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9392: &Apache::lonhomework::showhash(%slotinfo);
9393: my ($tmp)=keys(%slotinfo);
9394: if ($tmp=~/^error:/) { return (); }
9395: $remembered{$key} = $slotinfo{$which};
9396: }
9397: if (ref($slotinfo{$which}) eq 'HASH') {
9398: return %{$slotinfo{$which}};
9399: }
9400: return $slotinfo{$which};
9401: }
9402:
9403: sub get_reservable_slots {
9404: my ($cnum,$cdom,$uname,$udom) = @_;
9405: my $now = time;
9406: my $reservable_info;
9407: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9408: if (exists($remembered{$key})) {
9409: $reservable_info = $remembered{$key};
9410: } else {
9411: my %resv;
9412: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9413: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9414: $reservable_info = \%resv;
9415: $remembered{$key} = $reservable_info;
9416: }
9417: return $reservable_info;
9418: }
9419:
9420: sub get_course_slots {
9421: my ($cnum,$cdom) = @_;
9422: my $hashid=$cnum.':'.$cdom;
9423: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9424: if (defined($cached)) {
9425: if (ref($result) eq 'HASH') {
9426: return %{$result};
9427: }
9428: } else {
9429: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9430: my ($tmp) = keys(%slots);
9431: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9432: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9433: return %slots;
9434: }
9435: }
9436: return;
9437: }
9438:
9439: sub devalidate_slots_cache {
9440: my ($cnum,$cdom)=@_;
9441: my $hashid=$cnum.':'.$cdom;
9442: &devalidate_cache_new('allslots',$hashid);
9443: }
9444:
9445: # ------------------------------------------------- Update symbolic store links
9446:
9447: sub symblist {
9448: my ($mapname,%newhash)=@_;
9449: $mapname=&deversion(&declutter($mapname));
9450: my %hash;
9451: if (($env{'request.course.fn'}) && (%newhash)) {
9452: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9453: &GDBM_WRCREAT(),0640)) {
9454: foreach my $url (keys(%newhash)) {
9455: next if ($url eq 'last_known'
9456: && $env{'form.no_update_last_known'});
9457: $hash{declutter($url)}=&encode_symb($mapname,
9458: $newhash{$url}->[1],
9459: $newhash{$url}->[0]);
9460: }
9461: if (untie(%hash)) {
9462: return 'ok';
9463: }
9464: }
9465: }
9466: return 'error';
9467: }
9468:
9469: # --------------------------------------------------------------- Verify a symb
9470:
9471: sub symbverify {
9472: my ($symb,$thisurl)=@_;
9473: my $thisfn=$thisurl;
9474: $thisfn=&declutter($thisfn);
9475: # direct jump to resource in page or to a sequence - will construct own symbs
9476: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9477: # check URL part
9478: my ($map,$resid,$url)=&decode_symb($symb);
9479:
9480: unless ($url eq $thisfn) { return 0; }
9481:
9482: $symb=&symbclean($symb);
9483: $thisurl=&deversion($thisurl);
9484: $thisfn=&deversion($thisfn);
9485:
9486: my %bighash;
9487: my $okay=0;
9488:
9489: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9490: &GDBM_READER(),0640)) {
9491: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9492: $thisurl =~ s/\?.+$//;
9493: }
9494: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9495: unless ($ids) {
9496: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9497: $ids=$bighash{$idkey};
9498: }
9499: if ($ids) {
9500: # ------------------------------------------------------------------- Has ID(s)
9501: foreach my $id (split(/\,/,$ids)) {
9502: my ($mapid,$resid)=split(/\./,$id);
9503: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9504: $symb =~ s/\?.+$//;
9505: }
9506: if (
9507: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9508: eq $symb) {
9509: if (($env{'request.role.adv'}) ||
9510: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9511: ($thisurl eq '/adm/navmaps')) {
9512: $okay=1;
9513: }
9514: }
9515: }
9516: }
9517: untie(%bighash);
9518: }
9519: return $okay;
9520: }
9521:
9522: # --------------------------------------------------------------- Clean-up symb
9523:
9524: sub symbclean {
9525: my $symb=shift;
9526: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9527: # remove version from map
9528: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9529:
9530: # remove version from URL
9531: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9532:
9533: # remove wrapper
9534:
9535: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9536: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9537: return $symb;
9538: }
9539:
9540: # ---------------------------------------------- Split symb to find map and url
9541:
9542: sub encode_symb {
9543: my ($map,$resid,$url)=@_;
9544: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9545: }
9546:
9547: sub decode_symb {
9548: my $symb=shift;
9549: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9550: my ($map,$resid,$url)=split(/___/,$symb);
9551: return (&fixversion($map),$resid,&fixversion($url));
9552: }
9553:
9554: sub fixversion {
9555: my $fn=shift;
9556: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9557: my %bighash;
9558: my $uri=&clutter($fn);
9559: my $key=$env{'request.course.id'}.'_'.$uri;
9560: # is this cached?
9561: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9562: if (defined($cached)) { return $result; }
9563: # unfortunately not cached, or expired
9564: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9565: &GDBM_READER(),0640)) {
9566: if ($bighash{'version_'.$uri}) {
9567: my $version=$bighash{'version_'.$uri};
9568: unless (($version eq 'mostrecent') ||
9569: ($version==&getversion($uri))) {
9570: $uri=~s/\.(\w+)$/\.$version\.$1/;
9571: }
9572: }
9573: untie %bighash;
9574: }
9575: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9576: }
9577:
9578: sub deversion {
9579: my $url=shift;
9580: $url=~s/\.\d+\.(\w+)$/\.$1/;
9581: return $url;
9582: }
9583:
9584: # ------------------------------------------------------ Return symb list entry
9585:
9586: sub symbread {
9587: my ($thisfn,$donotrecurse)=@_;
9588: my $cache_str='request.symbread.cached.'.$thisfn;
9589: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9590: # no filename provided? try from environment
9591: unless ($thisfn) {
9592: if ($env{'request.symb'}) {
9593: return $env{$cache_str}=&symbclean($env{'request.symb'});
9594: }
9595: $thisfn=$env{'request.filename'};
9596: }
9597: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9598: # is that filename actually a symb? Verify, clean, and return
9599: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9600: if (&symbverify($thisfn,$1)) {
9601: return $env{$cache_str}=&symbclean($thisfn);
9602: }
9603: }
9604: $thisfn=declutter($thisfn);
9605: my %hash;
9606: my %bighash;
9607: my $syval='';
9608: if (($env{'request.course.fn'}) && ($thisfn)) {
9609: my $targetfn = $thisfn;
9610: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9611: $targetfn = 'adm/wrapper/'.$thisfn;
9612: }
9613: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9614: $targetfn=$1;
9615: }
9616: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9617: &GDBM_READER(),0640)) {
9618: $syval=$hash{$targetfn};
9619: untie(%hash);
9620: }
9621: # ---------------------------------------------------------- There was an entry
9622: if ($syval) {
9623: #unless ($syval=~/\_\d+$/) {
9624: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9625: #&appenv({'request.ambiguous' => $thisfn});
9626: #return $env{$cache_str}='';
9627: #}
9628: #$syval.=$1;
9629: #}
9630: } else {
9631: # ------------------------------------------------------- Was not in symb table
9632: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9633: &GDBM_READER(),0640)) {
9634: # ---------------------------------------------- Get ID(s) for current resource
9635: my $ids=$bighash{'ids_'.&clutter($thisfn)};
9636: unless ($ids) {
9637: $ids=$bighash{'ids_/'.$thisfn};
9638: }
9639: unless ($ids) {
9640: # alias?
9641: $ids=$bighash{'mapalias_'.$thisfn};
9642: }
9643: if ($ids) {
9644: # ------------------------------------------------------------------- Has ID(s)
9645: my @possibilities=split(/\,/,$ids);
9646: if ($#possibilities==0) {
9647: # ----------------------------------------------- There is only one possibility
9648: my ($mapid,$resid)=split(/\./,$ids);
9649: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9650: $resid,$thisfn);
9651: } elsif (!$donotrecurse) {
9652: # ------------------------------------------ There is more than one possibility
9653: my $realpossible=0;
9654: foreach my $id (@possibilities) {
9655: my $file=$bighash{'src_'.$id};
9656: if (&allowed('bre',$file)) {
9657: my ($mapid,$resid)=split(/\./,$id);
9658: if ($bighash{'map_type_'.$mapid} ne 'page') {
9659: $realpossible++;
9660: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9661: $resid,$thisfn);
9662: }
9663: }
9664: }
9665: if ($realpossible!=1) { $syval=''; }
9666: } else {
9667: $syval='';
9668: }
9669: }
9670: untie(%bighash)
9671: }
9672: }
9673: if ($syval) {
9674: return $env{$cache_str}=$syval;
9675: }
9676: }
9677: &appenv({'request.ambiguous' => $thisfn});
9678: return $env{$cache_str}='';
9679: }
9680:
9681: # ---------------------------------------------------------- Return random seed
9682:
9683: sub numval {
9684: my $txt=shift;
9685: $txt=~tr/A-J/0-9/;
9686: $txt=~tr/a-j/0-9/;
9687: $txt=~tr/K-T/0-9/;
9688: $txt=~tr/k-t/0-9/;
9689: $txt=~tr/U-Z/0-5/;
9690: $txt=~tr/u-z/0-5/;
9691: $txt=~s/\D//g;
9692: if ($_64bit) { if ($txt > 2**32) { return -1; } }
9693: return int($txt);
9694: }
9695:
9696: sub numval2 {
9697: my $txt=shift;
9698: $txt=~tr/A-J/0-9/;
9699: $txt=~tr/a-j/0-9/;
9700: $txt=~tr/K-T/0-9/;
9701: $txt=~tr/k-t/0-9/;
9702: $txt=~tr/U-Z/0-5/;
9703: $txt=~tr/u-z/0-5/;
9704: $txt=~s/\D//g;
9705: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9706: my $total;
9707: foreach my $val (@txts) { $total+=$val; }
9708: if ($_64bit) { if ($total > 2**32) { return -1; } }
9709: return int($total);
9710: }
9711:
9712: sub numval3 {
9713: use integer;
9714: my $txt=shift;
9715: $txt=~tr/A-J/0-9/;
9716: $txt=~tr/a-j/0-9/;
9717: $txt=~tr/K-T/0-9/;
9718: $txt=~tr/k-t/0-9/;
9719: $txt=~tr/U-Z/0-5/;
9720: $txt=~tr/u-z/0-5/;
9721: $txt=~s/\D//g;
9722: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9723: my $total;
9724: foreach my $val (@txts) { $total+=$val; }
9725: if ($_64bit) { $total=(($total<<32)>>32); }
9726: return $total;
9727: }
9728:
9729: sub digest {
9730: my ($data)=@_;
9731: my $digest=&Digest::MD5::md5($data);
9732: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9733: my ($e,$f);
9734: {
9735: use integer;
9736: $e=($a+$b);
9737: $f=($c+$d);
9738: if ($_64bit) {
9739: $e=(($e<<32)>>32);
9740: $f=(($f<<32)>>32);
9741: }
9742: }
9743: if (wantarray) {
9744: return ($e,$f);
9745: } else {
9746: my $g;
9747: {
9748: use integer;
9749: $g=($e+$f);
9750: if ($_64bit) {
9751: $g=(($g<<32)>>32);
9752: }
9753: }
9754: return $g;
9755: }
9756: }
9757:
9758: sub latest_rnd_algorithm_id {
9759: return '64bit5';
9760: }
9761:
9762: sub get_rand_alg {
9763: my ($courseid)=@_;
9764: if (!$courseid) { $courseid=(&whichuser())[1]; }
9765: if ($courseid) {
9766: return $env{"course.$courseid.rndseed"};
9767: }
9768: return &latest_rnd_algorithm_id();
9769: }
9770:
9771: sub validCODE {
9772: my ($CODE)=@_;
9773: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9774: return 0;
9775: }
9776:
9777: sub getCODE {
9778: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
9779: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9780: defined($Apache::lonhomework::parsing_a_task) ) &&
9781: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
9782: return $Apache::lonhomework::history{'resource.CODE'};
9783: }
9784: return undef;
9785: }
9786: #
9787: # Determines the random seed for a specific context:
9788: #
9789: # parameters:
9790: # symb - in course context the symb for the seed.
9791: # course_id - The course id of the form domain_coursenum.
9792: # domain - Domain for the user.
9793: # course - Course for the user.
9794: # cenv - environment of the course.
9795: #
9796: # NOTE:
9797: # All parameters are picked out of the environment if missing
9798: # or not defined.
9799: # If a symb cannot be determined the current time is used instead.
9800: #
9801: # For a given well defined symb, courside, domain, username,
9802: # and course environment, the seed is reproducible.
9803: #
9804: sub rndseed {
9805: my ($symb,$courseid,$domain,$username, $cenv)=@_;
9806: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
9807: if (!defined($symb)) {
9808: unless ($symb=$wsymb) { return time; }
9809: }
9810: if (!defined $courseid) {
9811: $courseid=$wcourseid;
9812: }
9813: if (!defined $domain) { $domain=$wdomain; }
9814: if (!defined $username) { $username=$wusername }
9815:
9816: my $which;
9817: if (defined($cenv->{'rndseed'})) {
9818: $which = $cenv->{'rndseed'};
9819: } else {
9820: $which =&get_rand_alg($courseid);
9821: }
9822: if (defined(&getCODE())) {
9823:
9824: if ($which eq '64bit5') {
9825: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9826: } elsif ($which eq '64bit4') {
9827: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9828: } else {
9829: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9830: }
9831: } elsif ($which eq '64bit5') {
9832: return &rndseed_64bit5($symb,$courseid,$domain,$username);
9833: } elsif ($which eq '64bit4') {
9834: return &rndseed_64bit4($symb,$courseid,$domain,$username);
9835: } elsif ($which eq '64bit3') {
9836: return &rndseed_64bit3($symb,$courseid,$domain,$username);
9837: } elsif ($which eq '64bit2') {
9838: return &rndseed_64bit2($symb,$courseid,$domain,$username);
9839: } elsif ($which eq '64bit') {
9840: return &rndseed_64bit($symb,$courseid,$domain,$username);
9841: }
9842: return &rndseed_32bit($symb,$courseid,$domain,$username);
9843: }
9844:
9845: sub rndseed_32bit {
9846: my ($symb,$courseid,$domain,$username)=@_;
9847: {
9848: use integer;
9849: my $symbchck=unpack("%32C*",$symb) << 27;
9850: my $symbseed=numval($symb) << 22;
9851: my $namechck=unpack("%32C*",$username) << 17;
9852: my $nameseed=numval($username) << 12;
9853: my $domainseed=unpack("%32C*",$domain) << 7;
9854: my $courseseed=unpack("%32C*",$courseid);
9855: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
9856: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9857: #&logthis("rndseed :$num:$symb");
9858: if ($_64bit) { $num=(($num<<32)>>32); }
9859: return $num;
9860: }
9861: }
9862:
9863: sub rndseed_64bit {
9864: my ($symb,$courseid,$domain,$username)=@_;
9865: {
9866: use integer;
9867: my $symbchck=unpack("%32S*",$symb) << 21;
9868: my $symbseed=numval($symb) << 10;
9869: my $namechck=unpack("%32S*",$username);
9870:
9871: my $nameseed=numval($username) << 21;
9872: my $domainseed=unpack("%32S*",$domain) << 10;
9873: my $courseseed=unpack("%32S*",$courseid);
9874:
9875: my $num1=$symbchck+$symbseed+$namechck;
9876: my $num2=$nameseed+$domainseed+$courseseed;
9877: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9878: #&logthis("rndseed :$num:$symb");
9879: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9880: return "$num1,$num2";
9881: }
9882: }
9883:
9884: sub rndseed_64bit2 {
9885: my ($symb,$courseid,$domain,$username)=@_;
9886: {
9887: use integer;
9888: # strings need to be an even # of cahracters long, it it is odd the
9889: # last characters gets thrown away
9890: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9891: my $symbseed=numval($symb) << 10;
9892: my $namechck=unpack("%32S*",$username.' ');
9893:
9894: my $nameseed=numval($username) << 21;
9895: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9896: my $courseseed=unpack("%32S*",$courseid.' ');
9897:
9898: my $num1=$symbchck+$symbseed+$namechck;
9899: my $num2=$nameseed+$domainseed+$courseseed;
9900: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9901: #&logthis("rndseed :$num:$symb");
9902: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9903: return "$num1,$num2";
9904: }
9905: }
9906:
9907: sub rndseed_64bit3 {
9908: my ($symb,$courseid,$domain,$username)=@_;
9909: {
9910: use integer;
9911: # strings need to be an even # of cahracters long, it it is odd the
9912: # last characters gets thrown away
9913: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9914: my $symbseed=numval2($symb) << 10;
9915: my $namechck=unpack("%32S*",$username.' ');
9916:
9917: my $nameseed=numval2($username) << 21;
9918: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9919: my $courseseed=unpack("%32S*",$courseid.' ');
9920:
9921: my $num1=$symbchck+$symbseed+$namechck;
9922: my $num2=$nameseed+$domainseed+$courseseed;
9923: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9924: #&logthis("rndseed :$num1:$num2:$_64bit");
9925: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9926:
9927: return "$num1:$num2";
9928: }
9929: }
9930:
9931: sub rndseed_64bit4 {
9932: my ($symb,$courseid,$domain,$username)=@_;
9933: {
9934: use integer;
9935: # strings need to be an even # of cahracters long, it it is odd the
9936: # last characters gets thrown away
9937: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9938: my $symbseed=numval3($symb) << 10;
9939: my $namechck=unpack("%32S*",$username.' ');
9940:
9941: my $nameseed=numval3($username) << 21;
9942: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9943: my $courseseed=unpack("%32S*",$courseid.' ');
9944:
9945: my $num1=$symbchck+$symbseed+$namechck;
9946: my $num2=$nameseed+$domainseed+$courseseed;
9947: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9948: #&logthis("rndseed :$num1:$num2:$_64bit");
9949: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9950:
9951: return "$num1:$num2";
9952: }
9953: }
9954:
9955: sub rndseed_64bit5 {
9956: my ($symb,$courseid,$domain,$username)=@_;
9957: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9958: return "$num1:$num2";
9959: }
9960:
9961: sub rndseed_CODE_64bit {
9962: my ($symb,$courseid,$domain,$username)=@_;
9963: {
9964: use integer;
9965: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9966: my $symbseed=numval2($symb);
9967: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9968: my $CODEseed=numval(&getCODE());
9969: my $courseseed=unpack("%32S*",$courseid.' ');
9970: my $num1=$symbseed+$CODEchck;
9971: my $num2=$CODEseed+$courseseed+$symbchck;
9972: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9973: #&logthis("rndseed :$num1:$num2:$symb");
9974: if ($_64bit) { $num1=(($num1<<32)>>32); }
9975: if ($_64bit) { $num2=(($num2<<32)>>32); }
9976: return "$num1:$num2";
9977: }
9978: }
9979:
9980: sub rndseed_CODE_64bit4 {
9981: my ($symb,$courseid,$domain,$username)=@_;
9982: {
9983: use integer;
9984: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9985: my $symbseed=numval3($symb);
9986: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9987: my $CODEseed=numval3(&getCODE());
9988: my $courseseed=unpack("%32S*",$courseid.' ');
9989: my $num1=$symbseed+$CODEchck;
9990: my $num2=$CODEseed+$courseseed+$symbchck;
9991: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9992: #&logthis("rndseed :$num1:$num2:$symb");
9993: if ($_64bit) { $num1=(($num1<<32)>>32); }
9994: if ($_64bit) { $num2=(($num2<<32)>>32); }
9995: return "$num1:$num2";
9996: }
9997: }
9998:
9999: sub rndseed_CODE_64bit5 {
10000: my ($symb,$courseid,$domain,$username)=@_;
10001: my $code = &getCODE();
10002: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10003: return "$num1:$num2";
10004: }
10005:
10006: sub setup_random_from_rndseed {
10007: my ($rndseed)=@_;
10008: if ($rndseed =~/([,:])/) {
10009: my ($num1,$num2)=split(/[,:]/,$rndseed);
10010: &Math::Random::random_set_seed(abs($num1),abs($num2));
10011: } else {
10012: &Math::Random::random_set_seed_from_phrase($rndseed);
10013: }
10014: }
10015:
10016: sub latest_receipt_algorithm_id {
10017: return 'receipt3';
10018: }
10019:
10020: sub recunique {
10021: my $fucourseid=shift;
10022: my $unique;
10023: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10024: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10025: $unique=$env{"course.$fucourseid.internal.encseed"};
10026: } else {
10027: $unique=$perlvar{'lonReceipt'};
10028: }
10029: return unpack("%32C*",$unique);
10030: }
10031:
10032: sub recprefix {
10033: my $fucourseid=shift;
10034: my $prefix;
10035: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10036: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10037: $prefix=$env{"course.$fucourseid.internal.encpref"};
10038: } else {
10039: $prefix=$perlvar{'lonHostID'};
10040: }
10041: return unpack("%32C*",$prefix);
10042: }
10043:
10044: sub ireceipt {
10045: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10046:
10047: my $return =&recprefix($fucourseid).'-';
10048:
10049: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10050: $env{'request.state'} eq 'construct') {
10051: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10052: return $return;
10053: }
10054:
10055: my $cuname=unpack("%32C*",$funame);
10056: my $cudom=unpack("%32C*",$fudom);
10057: my $cucourseid=unpack("%32C*",$fucourseid);
10058: my $cusymb=unpack("%32C*",$fusymb);
10059: my $cunique=&recunique($fucourseid);
10060: my $cpart=unpack("%32S*",$part);
10061: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10062:
10063: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
10064:
10065: $return.= ($cunique%$cuname+
10066: $cunique%$cudom+
10067: $cusymb%$cuname+
10068: $cusymb%$cudom+
10069: $cucourseid%$cuname+
10070: $cucourseid%$cudom+
10071: $cpart%$cuname+
10072: $cpart%$cudom);
10073: } else {
10074: $return.= ($cunique%$cuname+
10075: $cunique%$cudom+
10076: $cusymb%$cuname+
10077: $cusymb%$cudom+
10078: $cucourseid%$cuname+
10079: $cucourseid%$cudom);
10080: }
10081: return $return;
10082: }
10083:
10084: sub receipt {
10085: my ($part)=@_;
10086: my ($symb,$courseid,$domain,$name) = &whichuser();
10087: return &ireceipt($name,$domain,$courseid,$symb,$part);
10088: }
10089:
10090: sub whichuser {
10091: my ($passedsymb)=@_;
10092: my ($symb,$courseid,$domain,$name,$publicuser);
10093: if (defined($env{'form.grade_symb'})) {
10094: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10095: my $allowed=&allowed('vgr',$tmp_courseid);
10096: if (!$allowed &&
10097: exists($env{'request.course.sec'}) &&
10098: $env{'request.course.sec'} !~ /^\s*$/) {
10099: $allowed=&allowed('vgr',$tmp_courseid.
10100: '/'.$env{'request.course.sec'});
10101: }
10102: if ($allowed) {
10103: ($symb)=&get_env_multiple('form.grade_symb');
10104: $courseid=$tmp_courseid;
10105: ($domain)=&get_env_multiple('form.grade_domain');
10106: ($name)=&get_env_multiple('form.grade_username');
10107: return ($symb,$courseid,$domain,$name,$publicuser);
10108: }
10109: }
10110: if (!$passedsymb) {
10111: $symb=&symbread();
10112: } else {
10113: $symb=$passedsymb;
10114: }
10115: $courseid=$env{'request.course.id'};
10116: $domain=$env{'user.domain'};
10117: $name=$env{'user.name'};
10118: if ($name eq 'public' && $domain eq 'public') {
10119: if (!defined($env{'form.username'})) {
10120: $env{'form.username'}.=time.rand(10000000);
10121: }
10122: $name.=$env{'form.username'};
10123: }
10124: return ($symb,$courseid,$domain,$name,$publicuser);
10125:
10126: }
10127:
10128: # ------------------------------------------------------------ Serves up a file
10129: # returns either the contents of the file or
10130: # -1 if the file doesn't exist
10131: #
10132: # if the target is a file that was uploaded via DOCS,
10133: # a check will be made to see if a current copy exists on the local server,
10134: # if it does this will be served, otherwise a copy will be retrieved from
10135: # the home server for the course and stored in /home/httpd/html/userfiles on
10136: # the local server.
10137:
10138: sub getfile {
10139: my ($file) = @_;
10140: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10141: &repcopy($file);
10142: return &readfile($file);
10143: }
10144:
10145: sub repcopy_userfile {
10146: my ($file)=@_;
10147: my $londocroot = $perlvar{'lonDocRoot'};
10148: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10149: if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10150: my ($cdom,$cnum,$filename) =
10151: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10152: my $uri="/uploaded/$cdom/$cnum/$filename";
10153: if (-e "$file") {
10154: # we already have a local copy, check it out
10155: my @fileinfo = stat($file);
10156: my $rtncode;
10157: my $info;
10158: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10159: if ($lwpresp ne 'ok') {
10160: # there is no such file anymore, even though we had a local copy
10161: if ($rtncode eq '404') {
10162: unlink($file);
10163: }
10164: return -1;
10165: }
10166: if ($info < $fileinfo[9]) {
10167: # nice, the file we have is up-to-date, just say okay
10168: return 'ok';
10169: } else {
10170: # the file is outdated, get rid of it
10171: unlink($file);
10172: }
10173: }
10174: # one way or the other, at this point, we don't have the file
10175: # construct the correct path for the file
10176: my @parts = ($cdom,$cnum);
10177: if ($filename =~ m|^(.+)/[^/]+$|) {
10178: push @parts, split(/\//,$1);
10179: }
10180: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10181: foreach my $part (@parts) {
10182: $path .= '/'.$part;
10183: if (!-e $path) {
10184: mkdir($path,0770);
10185: }
10186: }
10187: # now the path exists for sure
10188: # get a user agent
10189: my $ua=new LWP::UserAgent;
10190: my $transferfile=$file.'.in.transfer';
10191: # FIXME: this should flock
10192: if (-e $transferfile) { return 'ok'; }
10193: my $request;
10194: $uri=~s/^\///;
10195: my $homeserver = &homeserver($cnum,$cdom);
10196: my $protocol = $protocol{$homeserver};
10197: $protocol = 'http' if ($protocol ne 'https');
10198: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10199: my $response=$ua->request($request,$transferfile);
10200: # did it work?
10201: if ($response->is_error()) {
10202: unlink($transferfile);
10203: &logthis("Userfile repcopy failed for $uri");
10204: return -1;
10205: }
10206: # worked, rename the transfer file
10207: rename($transferfile,$file);
10208: return 'ok';
10209: }
10210:
10211: sub tokenwrapper {
10212: my $uri=shift;
10213: $uri=~s|^https?\://([^/]+)||;
10214: $uri=~s|^/||;
10215: $env{'user.environment'}=~/\/([^\/]+)\.id/;
10216: my $token=$1;
10217: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10218: if ($udom && $uname && $file) {
10219: $file=~s|(\?\.*)*$||;
10220: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10221: my $homeserver = &homeserver($uname,$udom);
10222: my $protocol = $protocol{$homeserver};
10223: $protocol = 'http' if ($protocol ne 'https');
10224: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10225: (($uri=~/\?/)?'&':'?').'token='.$token.
10226: '&tokenissued='.$perlvar{'lonHostID'};
10227: } else {
10228: return '/adm/notfound.html';
10229: }
10230: }
10231:
10232: # call with reqtype HEAD: get last modification time
10233: # call with reqtype GET: get the file contents
10234: # Do not call this with reqtype GET for large files! It loads everything into memory
10235: #
10236: sub getuploaded {
10237: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10238: $uri=~s/^\///;
10239: my $homeserver = &homeserver($cnum,$cdom);
10240: my $protocol = $protocol{$homeserver};
10241: $protocol = 'http' if ($protocol ne 'https');
10242: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10243: my $ua=new LWP::UserAgent;
10244: my $request=new HTTP::Request($reqtype,$uri);
10245: my $response=$ua->request($request);
10246: $$rtncode = $response->code;
10247: if (! $response->is_success()) {
10248: return 'failed';
10249: }
10250: if ($reqtype eq 'HEAD') {
10251: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10252: } elsif ($reqtype eq 'GET') {
10253: $$info = $response->content;
10254: }
10255: return 'ok';
10256: }
10257:
10258: sub readfile {
10259: my $file = shift;
10260: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10261: my $fh;
10262: open($fh,"<$file");
10263: my $a='';
10264: while (my $line = <$fh>) { $a .= $line; }
10265: return $a;
10266: }
10267:
10268: sub filelocation {
10269: my ($dir,$file) = @_;
10270: my $location;
10271: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10272:
10273: if ($file =~ m-^/adm/-) {
10274: $file=~s-^/adm/wrapper/-/-;
10275: $file=~s-^/adm/coursedocs/showdoc/-/-;
10276: }
10277:
10278: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10279: $location = $file;
10280: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10281: my ($udom,$uname,$filename)=
10282: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10283: my $home=&homeserver($uname,$udom);
10284: my $is_me=0;
10285: my @ids=¤t_machine_ids();
10286: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10287: if ($is_me) {
10288: $location=propath($udom,$uname).'/userfiles/'.$filename;
10289: } else {
10290: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10291: $udom.'/'.$uname.'/'.$filename;
10292: }
10293: } elsif ($file =~ m-^/adm/-) {
10294: $location = $perlvar{'lonDocRoot'}.'/'.$file;
10295: } else {
10296: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10297: $file=~s:^/(res|priv)/:/:;
10298: my $space=$1;
10299: if ( !( $file =~ m:^/:) ) {
10300: $location = $dir. '/'.$file;
10301: } else {
10302: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10303: }
10304: }
10305: $location=~s://+:/:g; # remove duplicate /
10306: while ($location=~m{/\.\./}) {
10307: if ($location =~ m{/[^/]+/\.\./}) {
10308: $location=~ s{/[^/]+/\.\./}{/}g;
10309: } else {
10310: $location=~ s{/\.\./}{/}g;
10311: }
10312: } #remove dir/..
10313: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10314: return $location;
10315: }
10316:
10317: sub hreflocation {
10318: my ($dir,$file)=@_;
10319: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10320: $file=filelocation($dir,$file);
10321: } elsif ($file=~m-^/adm/-) {
10322: $file=~s-^/adm/wrapper/-/-;
10323: $file=~s-^/adm/coursedocs/showdoc/-/-;
10324: }
10325: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10326: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10327: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10328: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10329: {/uploaded/$1/$2/}x;
10330: }
10331: if ($file=~ m{^/userfiles/}) {
10332: $file =~ s{^/userfiles/}{/uploaded/};
10333: }
10334: return $file;
10335: }
10336:
10337:
10338:
10339:
10340:
10341: sub current_machine_domains {
10342: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10343: }
10344:
10345: sub machine_domains {
10346: my ($hostname) = @_;
10347: my @domains;
10348: my %hostname = &all_hostnames();
10349: while( my($id, $name) = each(%hostname)) {
10350: # &logthis("-$id-$name-$hostname-");
10351: if ($hostname eq $name) {
10352: push(@domains,&host_domain($id));
10353: }
10354: }
10355: return @domains;
10356: }
10357:
10358: sub current_machine_ids {
10359: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10360: }
10361:
10362: sub machine_ids {
10363: my ($hostname) = @_;
10364: $hostname ||= &hostname($perlvar{'lonHostID'});
10365: my @ids;
10366: my %name_to_host = &all_names();
10367: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10368: return @{ $name_to_host{$hostname} };
10369: }
10370: return;
10371: }
10372:
10373: sub additional_machine_domains {
10374: my @domains;
10375: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10376: while( my $line = <$fh>) {
10377: $line =~ s/\s//g;
10378: push(@domains,$line);
10379: }
10380: return @domains;
10381: }
10382:
10383: sub default_login_domain {
10384: my $domain = $perlvar{'lonDefDomain'};
10385: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10386: foreach my $posdom (¤t_machine_domains(),
10387: &additional_machine_domains()) {
10388: if (lc($posdom) eq lc($testdomain)) {
10389: $domain=$posdom;
10390: last;
10391: }
10392: }
10393: return $domain;
10394: }
10395:
10396: # ------------------------------------------------------------- Declutters URLs
10397:
10398: sub declutter {
10399: my $thisfn=shift;
10400: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10401: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10402: $thisfn=~s/^\///;
10403: $thisfn=~s|^adm/wrapper/||;
10404: $thisfn=~s|^adm/coursedocs/showdoc/||;
10405: $thisfn=~s/^res\///;
10406: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10407: $thisfn=~s/\?.+$//;
10408: }
10409: return $thisfn;
10410: }
10411:
10412: # ------------------------------------------------------------- Clutter up URLs
10413:
10414: sub clutter {
10415: my $thisfn='/'.&declutter(shift);
10416: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10417: || $thisfn =~ m{^/adm/(includes|pages)} ) {
10418: $thisfn='/res'.$thisfn;
10419: }
10420: if ($thisfn !~m|^/adm|) {
10421: if ($thisfn =~ m|^/ext/|) {
10422: $thisfn='/adm/wrapper'.$thisfn;
10423: } else {
10424: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10425: my $embstyle=&Apache::loncommon::fileembstyle($ext);
10426: if ($embstyle eq 'ssi'
10427: || ($embstyle eq 'hdn')
10428: || ($embstyle eq 'rat')
10429: || ($embstyle eq 'prv')
10430: || ($embstyle eq 'ign')) {
10431: #do nothing with these
10432: } elsif (($embstyle eq 'img')
10433: || ($embstyle eq 'emb')
10434: || ($embstyle eq 'wrp')) {
10435: $thisfn='/adm/wrapper'.$thisfn;
10436: } elsif ($embstyle eq 'unk'
10437: && $thisfn!~/\.(sequence|page)$/) {
10438: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
10439: } else {
10440: # &logthis("Got a blank emb style");
10441: }
10442: }
10443: }
10444: return $thisfn;
10445: }
10446:
10447: sub clutter_with_no_wrapper {
10448: my $uri = &clutter(shift);
10449: if ($uri =~ m-^/adm/-) {
10450: $uri =~ s-^/adm/wrapper/-/-;
10451: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10452: }
10453: return $uri;
10454: }
10455:
10456: sub freeze_escape {
10457: my ($value)=@_;
10458: if (ref($value)) {
10459: $value=&nfreeze($value);
10460: return '__FROZEN__'.&escape($value);
10461: }
10462: return &escape($value);
10463: }
10464:
10465:
10466: sub thaw_unescape {
10467: my ($value)=@_;
10468: if ($value =~ /^__FROZEN__/) {
10469: substr($value,0,10,undef);
10470: $value=&unescape($value);
10471: return &thaw($value);
10472: }
10473: return &unescape($value);
10474: }
10475:
10476: sub correct_line_ends {
10477: my ($result)=@_;
10478: $$result =~s/\r\n/\n/mg;
10479: $$result =~s/\r/\n/mg;
10480: }
10481: # ================================================================ Main Program
10482:
10483: sub goodbye {
10484: &logthis("Starting Shut down");
10485: #not converted to using infrastruture and probably shouldn't be
10486: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10487: #converted
10488: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10489: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10490: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10491: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10492: #1.1 only
10493: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10494: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10495: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10496: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10497: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10498: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10499: &logthis(sprintf("%-20s is %s",'hits',$hits));
10500: &flushcourselogs();
10501: &logthis("Shutting down");
10502: }
10503:
10504: sub get_dns {
10505: my ($url,$func,$ignore_cache) = @_;
10506: if (!$ignore_cache) {
10507: my ($content,$cached)=
10508: &Apache::lonnet::is_cached_new('dns',$url);
10509: if ($cached) {
10510: &$func($content);
10511: return;
10512: }
10513: }
10514:
10515: my %alldns;
10516: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10517: foreach my $dns (<$config>) {
10518: next if ($dns !~ /^\^(\S*)/x);
10519: my $line = $1;
10520: my ($host,$protocol) = split(/:/,$line);
10521: if ($protocol ne 'https') {
10522: $protocol = 'http';
10523: }
10524: $alldns{$host} = $protocol;
10525: }
10526: while (%alldns) {
10527: my ($dns) = keys(%alldns);
10528: my $ua=new LWP::UserAgent;
10529: $ua->timeout(30);
10530: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10531: my $response=$ua->request($request);
10532: delete($alldns{$dns});
10533: next if ($response->is_error());
10534: my @content = split("\n",$response->content);
10535: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10536: &$func(\@content);
10537: return;
10538: }
10539: close($config);
10540: my $which = (split('/',$url))[3];
10541: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10542: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10543: my @content = <$config>;
10544: &$func(\@content);
10545: return;
10546: }
10547: # ------------------------------------------------------------ Read domain file
10548: {
10549: my $loaded;
10550: my %domain;
10551:
10552: sub parse_domain_tab {
10553: my ($lines) = @_;
10554: foreach my $line (@$lines) {
10555: next if ($line =~ /^(\#|\s*$ )/x);
10556:
10557: chomp($line);
10558: my ($name,@elements) = split(/:/,$line,9);
10559: my %this_domain;
10560: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10561: 'lang_def', 'city', 'longi', 'lati',
10562: 'primary') {
10563: $this_domain{$field} = shift(@elements);
10564: }
10565: $domain{$name} = \%this_domain;
10566: }
10567: }
10568:
10569: sub reset_domain_info {
10570: undef($loaded);
10571: undef(%domain);
10572: }
10573:
10574: sub load_domain_tab {
10575: my ($ignore_cache) = @_;
10576: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10577: my $fh;
10578: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10579: my @lines = <$fh>;
10580: &parse_domain_tab(\@lines);
10581: }
10582: close($fh);
10583: $loaded = 1;
10584: }
10585:
10586: sub domain {
10587: &load_domain_tab() if (!$loaded);
10588:
10589: my ($name,$what) = @_;
10590: return if ( !exists($domain{$name}) );
10591:
10592: if (!$what) {
10593: return $domain{$name}{'description'};
10594: }
10595: return $domain{$name}{$what};
10596: }
10597:
10598: sub domain_info {
10599: &load_domain_tab() if (!$loaded);
10600: return %domain;
10601: }
10602:
10603: }
10604:
10605:
10606: # ------------------------------------------------------------- Read hosts file
10607: {
10608: my %hostname;
10609: my %hostdom;
10610: my %libserv;
10611: my $loaded;
10612: my %name_to_host;
10613: my %internetdom;
10614: my %LC_dns_serv;
10615:
10616: sub parse_hosts_tab {
10617: my ($file) = @_;
10618: foreach my $configline (@$file) {
10619: next if ($configline =~ /^(\#|\s*$ )/x);
10620: chomp($configline);
10621: if ($configline =~ /^\^/) {
10622: if ($configline =~ /^\^([\w.\-]+)/) {
10623: $LC_dns_serv{$1} = 1;
10624: }
10625: next;
10626: }
10627: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10628: $name=~s/\s//g;
10629: if ($id && $domain && $role && $name) {
10630: $hostname{$id}=$name;
10631: push(@{$name_to_host{$name}}, $id);
10632: $hostdom{$id}=$domain;
10633: if ($role eq 'library') { $libserv{$id}=$name; }
10634: if (defined($protocol)) {
10635: if ($protocol eq 'https') {
10636: $protocol{$id} = $protocol;
10637: } else {
10638: $protocol{$id} = 'http';
10639: }
10640: } else {
10641: $protocol{$id} = 'http';
10642: }
10643: if (defined($intdom)) {
10644: $internetdom{$id} = $intdom;
10645: }
10646: }
10647: }
10648: }
10649:
10650: sub reset_hosts_info {
10651: &purge_remembered();
10652: &reset_domain_info();
10653: &reset_hosts_ip_info();
10654: undef(%name_to_host);
10655: undef(%hostname);
10656: undef(%hostdom);
10657: undef(%libserv);
10658: undef($loaded);
10659: }
10660:
10661: sub load_hosts_tab {
10662: my ($ignore_cache) = @_;
10663: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10664: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10665: my @config = <$config>;
10666: &parse_hosts_tab(\@config);
10667: close($config);
10668: $loaded=1;
10669: }
10670:
10671: sub hostname {
10672: &load_hosts_tab() if (!$loaded);
10673:
10674: my ($lonid) = @_;
10675: return $hostname{$lonid};
10676: }
10677:
10678: sub all_hostnames {
10679: &load_hosts_tab() if (!$loaded);
10680:
10681: return %hostname;
10682: }
10683:
10684: sub all_names {
10685: &load_hosts_tab() if (!$loaded);
10686:
10687: return %name_to_host;
10688: }
10689:
10690: sub all_host_domain {
10691: &load_hosts_tab() if (!$loaded);
10692: return %hostdom;
10693: }
10694:
10695: sub is_library {
10696: &load_hosts_tab() if (!$loaded);
10697:
10698: return exists($libserv{$_[0]});
10699: }
10700:
10701: sub all_library {
10702: &load_hosts_tab() if (!$loaded);
10703:
10704: return %libserv;
10705: }
10706:
10707: sub unique_library {
10708: #2x reverse removes all hostnames that appear more than once
10709: my %unique = reverse &all_library();
10710: return reverse %unique;
10711: }
10712:
10713: sub get_servers {
10714: &load_hosts_tab() if (!$loaded);
10715:
10716: my ($domain,$type) = @_;
10717: my %possible_hosts = ($type eq 'library') ? %libserv
10718: : %hostname;
10719: my %result;
10720: if (ref($domain) eq 'ARRAY') {
10721: while ( my ($host,$hostname) = each(%possible_hosts)) {
10722: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10723: $result{$host} = $hostname;
10724: }
10725: }
10726: } else {
10727: while ( my ($host,$hostname) = each(%possible_hosts)) {
10728: if ($hostdom{$host} eq $domain) {
10729: $result{$host} = $hostname;
10730: }
10731: }
10732: }
10733: return %result;
10734: }
10735:
10736: sub get_unique_servers {
10737: my %unique = reverse &get_servers(@_);
10738: return reverse %unique;
10739: }
10740:
10741: sub host_domain {
10742: &load_hosts_tab() if (!$loaded);
10743:
10744: my ($lonid) = @_;
10745: return $hostdom{$lonid};
10746: }
10747:
10748: sub all_domains {
10749: &load_hosts_tab() if (!$loaded);
10750:
10751: my %seen;
10752: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10753: return @uniq;
10754: }
10755:
10756: sub internet_dom {
10757: &load_hosts_tab() if (!$loaded);
10758:
10759: my ($lonid) = @_;
10760: return $internetdom{$lonid};
10761: }
10762:
10763: sub is_LC_dns {
10764: &load_hosts_tab() if (!$loaded);
10765:
10766: my ($hostname) = @_;
10767: return exists($LC_dns_serv{$hostname});
10768: }
10769:
10770: }
10771:
10772: {
10773: my %iphost;
10774: my %name_to_ip;
10775: my %lonid_to_ip;
10776:
10777: sub get_hosts_from_ip {
10778: my ($ip) = @_;
10779: my %iphosts = &get_iphost();
10780: if (ref($iphosts{$ip})) {
10781: return @{$iphosts{$ip}};
10782: }
10783: return;
10784: }
10785:
10786: sub reset_hosts_ip_info {
10787: undef(%iphost);
10788: undef(%name_to_ip);
10789: undef(%lonid_to_ip);
10790: }
10791:
10792: sub get_host_ip {
10793: my ($lonid) = @_;
10794: if (exists($lonid_to_ip{$lonid})) {
10795: return $lonid_to_ip{$lonid};
10796: }
10797: my $name=&hostname($lonid);
10798: my $ip = gethostbyname($name);
10799: return if (!$ip || length($ip) ne 4);
10800: $ip=inet_ntoa($ip);
10801: $name_to_ip{$name} = $ip;
10802: $lonid_to_ip{$lonid} = $ip;
10803: return $ip;
10804: }
10805:
10806: sub get_iphost {
10807: my ($ignore_cache) = @_;
10808:
10809: if (!$ignore_cache) {
10810: if (%iphost) {
10811: return %iphost;
10812: }
10813: my ($ip_info,$cached)=
10814: &Apache::lonnet::is_cached_new('iphost','iphost');
10815: if ($cached) {
10816: %iphost = %{$ip_info->[0]};
10817: %name_to_ip = %{$ip_info->[1]};
10818: %lonid_to_ip = %{$ip_info->[2]};
10819: return %iphost;
10820: }
10821: }
10822:
10823: # get yesterday's info for fallback
10824: my %old_name_to_ip;
10825: my ($ip_info,$cached)=
10826: &Apache::lonnet::is_cached_new('iphost','iphost');
10827: if ($cached) {
10828: %old_name_to_ip = %{$ip_info->[1]};
10829: }
10830:
10831: my %name_to_host = &all_names();
10832: foreach my $name (keys(%name_to_host)) {
10833: my $ip;
10834: if (!exists($name_to_ip{$name})) {
10835: $ip = gethostbyname($name);
10836: if (!$ip || length($ip) ne 4) {
10837: if (defined($old_name_to_ip{$name})) {
10838: $ip = $old_name_to_ip{$name};
10839: &logthis("Can't find $name defaulting to old $ip");
10840: } else {
10841: &logthis("Name $name no IP found");
10842: next;
10843: }
10844: } else {
10845: $ip=inet_ntoa($ip);
10846: }
10847: $name_to_ip{$name} = $ip;
10848: } else {
10849: $ip = $name_to_ip{$name};
10850: }
10851: foreach my $id (@{ $name_to_host{$name} }) {
10852: $lonid_to_ip{$id} = $ip;
10853: }
10854: push(@{$iphost{$ip}},@{$name_to_host{$name}});
10855: }
10856: &Apache::lonnet::do_cache_new('iphost','iphost',
10857: [\%iphost,\%name_to_ip,\%lonid_to_ip],
10858: 48*60*60);
10859:
10860: return %iphost;
10861: }
10862:
10863: #
10864: # Given a DNS returns the loncapa host name for that DNS
10865: #
10866: sub host_from_dns {
10867: my ($dns) = @_;
10868: my @hosts;
10869: my $ip;
10870:
10871: if (exists($name_to_ip{$dns})) {
10872: $ip = $name_to_ip{$dns};
10873: }
10874: if (!$ip) {
10875: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10876: if (length($ip) == 4) {
10877: $ip = &IO::Socket::inet_ntoa($ip);
10878: }
10879: }
10880: if ($ip) {
10881: @hosts = get_hosts_from_ip($ip);
10882: return $hosts[0];
10883: }
10884: return undef;
10885: }
10886:
10887: sub get_internet_names {
10888: my ($lonid) = @_;
10889: return if ($lonid eq '');
10890: my ($idnref,$cached)=
10891: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10892: if ($cached) {
10893: return $idnref;
10894: }
10895: my $ip = &get_host_ip($lonid);
10896: my @hosts = &get_hosts_from_ip($ip);
10897: my %iphost = &get_iphost();
10898: my (@idns,%seen);
10899: foreach my $id (@hosts) {
10900: my $dom = &host_domain($id);
10901: my $prim_id = &domain($dom,'primary');
10902: my $prim_ip = &get_host_ip($prim_id);
10903: next if ($seen{$prim_ip});
10904: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10905: foreach my $id (@{$iphost{$prim_ip}}) {
10906: my $intdom = &internet_dom($id);
10907: unless (grep(/^\Q$intdom\E$/,@idns)) {
10908: push(@idns,$intdom);
10909: }
10910: }
10911: }
10912: $seen{$prim_ip} = 1;
10913: }
10914: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10915: }
10916:
10917: }
10918:
10919: sub all_loncaparevs {
10920: 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);
10921: }
10922:
10923: BEGIN {
10924:
10925: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10926: unless ($readit) {
10927: {
10928: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10929: %perlvar = (%perlvar,%{$configvars});
10930: }
10931:
10932:
10933: # ------------------------------------------------------ Read spare server file
10934: {
10935: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10936:
10937: while (my $configline=<$config>) {
10938: chomp($configline);
10939: if ($configline) {
10940: my ($host,$type) = split(':',$configline,2);
10941: if (!defined($type) || $type eq '') { $type = 'default' };
10942: push(@{ $spareid{$type} }, $host);
10943: }
10944: }
10945: close($config);
10946: }
10947: # ------------------------------------------------------------ Read permissions
10948: {
10949: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10950:
10951: while (my $configline=<$config>) {
10952: chomp($configline);
10953: if ($configline) {
10954: my ($role,$perm)=split(/ /,$configline);
10955: if ($perm ne '') { $pr{$role}=$perm; }
10956: }
10957: }
10958: close($config);
10959: }
10960:
10961: # -------------------------------------------- Read plain texts for permissions
10962: {
10963: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10964:
10965: while (my $configline=<$config>) {
10966: chomp($configline);
10967: if ($configline) {
10968: my ($short,@plain)=split(/:/,$configline);
10969: %{$prp{$short}} = ();
10970: if (@plain > 0) {
10971: $prp{$short}{'std'} = $plain[0];
10972: for (my $i=1; $i<@plain; $i++) {
10973: $prp{$short}{'alt'.$i} = $plain[$i];
10974: }
10975: }
10976: }
10977: }
10978: close($config);
10979: }
10980:
10981: # ---------------------------------------------------------- Read package table
10982: {
10983: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10984:
10985: while (my $configline=<$config>) {
10986: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10987: chomp($configline);
10988: my ($short,$plain)=split(/:/,$configline);
10989: my ($pack,$name)=split(/\&/,$short);
10990: if ($plain ne '') {
10991: $packagetab{$pack.'&'.$name.'&name'}=$name;
10992: $packagetab{$short}=$plain;
10993: }
10994: }
10995: close($config);
10996: }
10997:
10998: # ---------------------------------------------------------- Read loncaparev table
10999: {
11000: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11001: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11002: while (my $configline=<$config>) {
11003: chomp($configline);
11004: my ($hostid,$loncaparev)=split(/:/,$configline);
11005: $loncaparevs{$hostid}=$loncaparev;
11006: }
11007: close($config);
11008: }
11009: }
11010: }
11011:
11012: # ---------------------------------------------------------- Read serverhostID table
11013: {
11014: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11015: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11016: while (my $configline=<$config>) {
11017: chomp($configline);
11018: my ($name,$id)=split(/:/,$configline);
11019: $serverhomeIDs{$name}=$id;
11020: }
11021: close($config);
11022: }
11023: }
11024: }
11025:
11026: {
11027: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11028: if (-e $file) {
11029: my $parser = HTML::LCParser->new($file);
11030: while (my $token = $parser->get_token()) {
11031: if ($token->[0] eq 'S') {
11032: my $item = $token->[1];
11033: my $name = $token->[2]{'name'};
11034: my $value = $token->[2]{'value'};
11035: if ($item ne '' && $name ne '' && $value ne '') {
11036: my $release = $parser->get_text();
11037: $release =~ s/(^\s*|\s*$ )//gx;
11038: $needsrelease{$item.':'.$name.':'.$value} = $release;
11039: }
11040: }
11041: }
11042: }
11043: }
11044:
11045: # ---------------------------------------------------------- Read managers table
11046: {
11047: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11048: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11049: while (my $configline=<$config>) {
11050: chomp($configline);
11051: next if ($configline =~ /^\#/);
11052: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11053: $managerstab{$configline} = 1;
11054: }
11055: }
11056: close($config);
11057: }
11058: }
11059: }
11060:
11061: # ------------- set up temporary directory
11062: {
11063: $tmpdir = LONCAPA::tempdir();
11064:
11065: }
11066:
11067: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11068: 'compress_threshold'=> 20_000,
11069: });
11070:
11071: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11072: $dumpcount=0;
11073: $locknum=0;
11074:
11075: &logtouch();
11076: &logthis('<font color="yellow">INFO: Read configuration</font>');
11077: $readit=1;
11078: {
11079: use integer;
11080: my $test=(2**32)+1;
11081: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11082: &logthis(" Detected 64bit platform ($_64bit)");
11083: }
11084: }
11085: }
11086:
11087: 1;
11088: __END__
11089:
11090: =pod
11091:
11092: =head1 NAME
11093:
11094: Apache::lonnet - Subroutines to ask questions about things in the network.
11095:
11096: =head1 SYNOPSIS
11097:
11098: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11099:
11100: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11101:
11102: Common parameters:
11103:
11104: =over 4
11105:
11106: =item *
11107:
11108: $uname : an internal username (if $cname expecting a course Id specifically)
11109:
11110: =item *
11111:
11112: $udom : a domain (if $cdom expecting a course's domain specifically)
11113:
11114: =item *
11115:
11116: $symb : a resource instance identifier
11117:
11118: =item *
11119:
11120: $namespace : the name of a .db file that contains the data needed or
11121: being set.
11122:
11123: =back
11124:
11125: =head1 OVERVIEW
11126:
11127: lonnet provides subroutines which interact with the
11128: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11129: about classes, users, and resources.
11130:
11131: For many of these objects you can also use this to store data about
11132: them or modify them in various ways.
11133:
11134: =head2 Symbs
11135:
11136: To identify a specific instance of a resource, LON-CAPA uses symbols
11137: or "symbs"X<symb>. These identifiers are built from the URL of the
11138: map, the resource number of the resource in the map, and the URL of
11139: the resource itself. The latter is somewhat redundant, but might help
11140: if maps change.
11141:
11142: An example is
11143:
11144: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11145:
11146: The respective map entry is
11147:
11148: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11149: title="Problem 2">
11150: </resource>
11151:
11152: Symbs are used by the random number generator, as well as to store and
11153: restore data specific to a certain instance of for example a problem.
11154:
11155: =head2 Storing And Retrieving Data
11156:
11157: X<store()>X<cstore()>X<restore()>Three of the most important functions
11158: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11159: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11160: is is the non-critical message twin of cstore. These functions are for
11161: handlers to store a perl hash to a user's permanent data space in an
11162: easy manner, and to retrieve it again on another call. It is expected
11163: that a handler would use this once at the beginning to retrieve data,
11164: and then again once at the end to send only the new data back.
11165:
11166: The data is stored in the user's data directory on the user's
11167: homeserver under the ID of the course.
11168:
11169: The hash that is returned by restore will have all of the previous
11170: value for all of the elements of the hash.
11171:
11172: Example:
11173:
11174: #creating a hash
11175: my %hash;
11176: $hash{'foo'}='bar';
11177:
11178: #storing it
11179: &Apache::lonnet::cstore(\%hash);
11180:
11181: #changing a value
11182: $hash{'foo'}='notbar';
11183:
11184: #adding a new value
11185: $hash{'bar'}='foo';
11186: &Apache::lonnet::cstore(\%hash);
11187:
11188: #retrieving the hash
11189: my %history=&Apache::lonnet::restore();
11190:
11191: #print the hash
11192: foreach my $key (sort(keys(%history))) {
11193: print("\%history{$key} = $history{$key}");
11194: }
11195:
11196: Will print out:
11197:
11198: %history{1:foo} = bar
11199: %history{1:keys} = foo:timestamp
11200: %history{1:timestamp} = 990455579
11201: %history{2:bar} = foo
11202: %history{2:foo} = notbar
11203: %history{2:keys} = foo:bar:timestamp
11204: %history{2:timestamp} = 990455580
11205: %history{bar} = foo
11206: %history{foo} = notbar
11207: %history{timestamp} = 990455580
11208: %history{version} = 2
11209:
11210: Note that the special hash entries C<keys>, C<version> and
11211: C<timestamp> were added to the hash. C<version> will be equal to the
11212: total number of versions of the data that have been stored. The
11213: C<timestamp> attribute will be the UNIX time the hash was
11214: stored. C<keys> is available in every historical section to list which
11215: keys were added or changed at a specific historical revision of a
11216: hash.
11217:
11218: B<Warning>: do not store the hash that restore returns directly. This
11219: will cause a mess since it will restore the historical keys as if the
11220: were new keys. I.E. 1:foo will become 1:1:foo etc.
11221:
11222: Calling convention:
11223:
11224: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11225: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11226:
11227: For more detailed information, see lonnet specific documentation.
11228:
11229: =head1 RETURN MESSAGES
11230:
11231: =over 4
11232:
11233: =item * B<con_lost>: unable to contact remote host
11234:
11235: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11236: when the connection is brought back up
11237:
11238: =item * B<con_failed>: unable to contact remote host and unable to save message
11239: for later delivery
11240:
11241: =item * B<error:>: an error a occurred, a description of the error follows the :
11242:
11243: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11244: that was requested
11245:
11246: =back
11247:
11248: =head1 PUBLIC SUBROUTINES
11249:
11250: =head2 Session Environment Functions
11251:
11252: =over 4
11253:
11254: =item *
11255: X<appenv()>
11256: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11257: the user envirnoment file, and will be restored for each access this
11258: user makes during this session, also modifies the %env for the current
11259: process. Optional rolesarrayref - if defined contains a reference to an array
11260: of roles which are exempt from the restriction on modifying user.role entries
11261: in the user's environment.db and in %env.
11262:
11263: =item *
11264: X<delenv()>
11265: B<delenv($delthis,$regexp)>: removes all items from the session
11266: environment file that begin with $delthis. If the
11267: optional second arg - $regexp - is true, $delthis is treated as a
11268: regular expression, otherwise \Q$delthis\E is used.
11269: The values are also deleted from the current processes %env.
11270:
11271: =item * get_env_multiple($name)
11272:
11273: gets $name from the %env hash, it seemlessly handles the cases where multiple
11274: values may be defined and end up as an array ref.
11275:
11276: returns an array of values
11277:
11278: =back
11279:
11280: =head2 User Information
11281:
11282: =over 4
11283:
11284: =item *
11285: X<queryauthenticate()>
11286: B<queryauthenticate($uname,$udom)>: try to determine user's current
11287: authentication scheme
11288:
11289: =item *
11290: X<authenticate()>
11291: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11292: authenticate user from domain's lib servers (first use the current
11293: one). C<$upass> should be the users password.
11294: $checkdefauth is optional (value is 1 if a check should be made to
11295: authenticate user using default authentication method, and allow
11296: account creation if username does not have account in the domain).
11297: $clientcancheckhost is optional (value is 1 if checking whether the
11298: server can host will occur on the client side in lonauth.pm).
11299:
11300: =item *
11301: X<homeserver()>
11302: B<homeserver($uname,$udom)>: find the server which has
11303: the user's directory and files (there must be only one), this caches
11304: the answer, and also caches if there is a borken connection.
11305:
11306: =item *
11307: X<idget()>
11308: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11309: (IDs are a unique resource in a domain, there must be only 1 ID per
11310: username, and only 1 username per ID in a specific domain) (returns
11311: hash: id=>name,id=>name)
11312:
11313: =item *
11314: X<idrget()>
11315: B<idrget($udom,@unames)>: find the IDs behind a list of
11316: usernames (returns hash: name=>id,name=>id)
11317:
11318: =item *
11319: X<idput()>
11320: B<idput($udom,%ids)>: store away a list of names and associated IDs
11321:
11322: =item *
11323: X<rolesinit()>
11324: B<rolesinit($udom,$username,$authhost)>: get user privileges
11325:
11326: =item *
11327: X<getsection()>
11328: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11329: course $cname, return section name/number or '' for "not in course"
11330: and '-1' for "no section"
11331:
11332: =item *
11333: X<userenvironment()>
11334: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11335: passed in @what from the requested user's environment, returns a hash
11336:
11337: =item *
11338: X<userlog_query()>
11339: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11340: activity.log file. %filters defines filters applied when parsing the
11341: log file. These can be start or end timestamps, or the type of action
11342: - log to look for Login or Logout events, check for Checkin or
11343: Checkout, role for role selection. The response is in the form
11344: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11345: escaped strings of the action recorded in the activity.log file.
11346:
11347: =back
11348:
11349: =head2 User Roles
11350:
11351: =over 4
11352:
11353: =item *
11354:
11355: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11356: F: full access
11357: U,I,K: authentication modes (cxx only)
11358: '': forbidden
11359: 1: user needs to choose course
11360: 2: browse allowed
11361: A: passphrase authentication needed
11362:
11363: =item *
11364:
11365: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11366: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11367: and course level
11368:
11369: =item *
11370:
11371: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11372: (rolesplain.tab); plain text explanation of a user role term.
11373: $type is Course (default) or Community.
11374: If $forcedefault evaluates to true, text returned will be default
11375: text for $type. Otherwise, if this is a course, the text returned
11376: will be a custom name for the role (if defined in the course's
11377: environment). If no custom name is defined the default is returned.
11378:
11379: =item *
11380:
11381: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11382: All arguments are optional. Returns a hash of a roles, either for
11383: co-author/assistant author roles for a user's Construction Space
11384: (default), or if $context is 'userroles', roles for the user himself,
11385: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11386: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11387: For each key, value is set to colon-separated start and end times for
11388: the role. If no username and domain are specified, will default to
11389: current user/domain. Types, roles, and roledoms are references to arrays
11390: of role statuses (active, future or previous), roles
11391: (e.g., cc,in, st etc.) and domains of the roles which can be used
11392: to restrict the list of roles reported. If no array ref is
11393: provided for types, will default to return only active roles.
11394:
11395: =back
11396:
11397: =head2 User Modification
11398:
11399: =over 4
11400:
11401: =item *
11402:
11403: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11404: user for the level given by URL. Optional start and end dates (leave empty
11405: string or zero for "no date")
11406:
11407: =item *
11408:
11409: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11410: change a users, password, possible return values are: ok,
11411: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11412: refused
11413:
11414: =item *
11415:
11416: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11417:
11418: =item *
11419:
11420: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11421: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11422:
11423: will update user information (firstname,middlename,lastname,generation,
11424: permanentemail), and if forceid is true, student/employee ID also.
11425: A user's institutional affiliation(s) can also be updated.
11426: User information fields will not be overwritten with empty entries
11427: unless the field is included in the $candelete array reference.
11428: This array is included when a single user is modified via "Manage Users",
11429: or when Autoupdate.pl is run by cron in a domain.
11430:
11431: =item *
11432:
11433: modifystudent
11434:
11435: modify a student's enrollment and identification information.
11436: The course id is resolved based on the current users environment.
11437: This means the envoking user must be a course coordinator or otherwise
11438: associated with a course.
11439:
11440: This call is essentially a wrapper for lonnet::modifyuser and
11441: lonnet::modify_student_enrollment
11442:
11443: Inputs:
11444:
11445: =over 4
11446:
11447: =item B<$udom> Student's loncapa domain
11448:
11449: =item B<$uname> Student's loncapa login name
11450:
11451: =item B<$uid> Student/Employee ID
11452:
11453: =item B<$umode> Student's authentication mode
11454:
11455: =item B<$upass> Student's password
11456:
11457: =item B<$first> Student's first name
11458:
11459: =item B<$middle> Student's middle name
11460:
11461: =item B<$last> Student's last name
11462:
11463: =item B<$gene> Student's generation
11464:
11465: =item B<$usec> Student's section in course
11466:
11467: =item B<$end> Unix time of the roles expiration
11468:
11469: =item B<$start> Unix time of the roles start date
11470:
11471: =item B<$forceid> If defined, allow $uid to be changed
11472:
11473: =item B<$desiredhome> server to use as home server for student
11474:
11475: =item B<$email> Student's permanent e-mail address
11476:
11477: =item B<$type> Type of enrollment (auto or manual)
11478:
11479: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11480:
11481: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11482:
11483: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11484:
11485: =item B<$context> role change context (shown in User Management Logs display in a course)
11486:
11487: =item B<$inststatus> institutional status of user - : separated string of escaped status types
11488:
11489: =back
11490:
11491: =item *
11492:
11493: modify_student_enrollment
11494:
11495: Change a students enrollment status in a class. The environment variable
11496: 'role.request.course' must be defined for this function to proceed.
11497:
11498: Inputs:
11499:
11500: =over 4
11501:
11502: =item $udom, students domain
11503:
11504: =item $uname, students name
11505:
11506: =item $uid, students user id
11507:
11508: =item $first, students first name
11509:
11510: =item $middle
11511:
11512: =item $last
11513:
11514: =item $gene
11515:
11516: =item $usec
11517:
11518: =item $end
11519:
11520: =item $start
11521:
11522: =item $type
11523:
11524: =item $locktype
11525:
11526: =item $cid
11527:
11528: =item $selfenroll
11529:
11530: =item $context
11531:
11532: =back
11533:
11534:
11535: =item *
11536:
11537: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11538: custom role; give a custom role to a user for the level given by URL. Specify
11539: name and domain of role author, and role name
11540:
11541: =item *
11542:
11543: revokerole($udom,$uname,$url,$role) : revoke a role for url
11544:
11545: =item *
11546:
11547: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11548:
11549: =back
11550:
11551: =head2 Course Infomation
11552:
11553: =over 4
11554:
11555: =item *
11556:
11557: coursedescription($courseid,$options) : returns a hash of information about the
11558: specified course id, including all environment settings for the
11559: course, the description of the course will be in the hash under the
11560: key 'description'
11561:
11562: $options is an optional parameter that if supplied is a hash reference that controls
11563: what how this function works. It has the following key/values:
11564:
11565: =over 4
11566:
11567: =item freshen_cache
11568:
11569: If defined, and the environment cache for the course is valid, it is
11570: returned in the returned hash.
11571:
11572: =item one_time
11573:
11574: If defined, the last cache time is set to _now_
11575:
11576: =item user
11577:
11578: If defined, the supplied username is used instead of the current user.
11579:
11580:
11581: =back
11582:
11583: =item *
11584:
11585: resdata($name,$domain,$type,@which) : request for current parameter
11586: setting for a specific $type, where $type is either 'course' or 'user',
11587: @what should be a list of parameters to ask about. This routine caches
11588: answers for 5 minutes.
11589:
11590: =item *
11591:
11592: get_courseresdata($courseid, $domain) : dump the entire course resource
11593: data base, returning a hash that is keyed by the resource name and has
11594: values that are the resource value. I believe that the timestamps and
11595: versions are also returned.
11596:
11597:
11598: =back
11599:
11600: =head2 Course Modification
11601:
11602: =over 4
11603:
11604: =item *
11605:
11606: writecoursepref($courseid,%prefs) : write preferences (environment
11607: database) for a course
11608:
11609: =item *
11610:
11611: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11612:
11613: =item *
11614:
11615: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11616:
11617: =back
11618:
11619: =head2 Resource Subroutines
11620:
11621: =over 4
11622:
11623: =item *
11624:
11625: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11626:
11627: =item *
11628:
11629: repcopy($filename) : subscribes to the requested file, and attempts to
11630: replicate from the owning library server, Might return
11631: 'unavailable', 'not_found', 'forbidden', 'ok', or
11632: 'bad_request', also attempts to grab the metadata for the
11633: resource. Expects the local filesystem pathname
11634: (/home/httpd/html/res/....)
11635:
11636: =back
11637:
11638: =head2 Resource Information
11639:
11640: =over 4
11641:
11642: =item *
11643:
11644: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11645: a vairety of different possible values, $varname should be a request
11646: string, and the other parameters can be used to specify who and what
11647: one is asking about.
11648:
11649: Possible values for $varname are environment.lastname (or other item
11650: from the envirnment hash), user.name (or someother aspect about the
11651: user), resource.0.maxtries (or some other part and parameter of a
11652: resource)
11653:
11654: =item *
11655:
11656: directcondval($number) : get current value of a condition; reads from a state
11657: string
11658:
11659: =item *
11660:
11661: condval($condidx) : value of condition index based on state
11662:
11663: =item *
11664:
11665: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11666: resource's metadata, $what should be either a specific key, or either
11667: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11668: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11669:
11670: this function automatically caches all requests
11671:
11672: =item *
11673:
11674: metadata_query($query,$custom,$customshow) : make a metadata query against the
11675: network of library servers; returns file handle of where SQL and regex results
11676: will be stored for query
11677:
11678: =item *
11679:
11680: symbread($filename) : return symbolic list entry (filename argument optional);
11681: returns the data handle
11682:
11683: =item *
11684:
11685: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11686: a possible symb for the URL in $thisfn, and if is an encryypted
11687: resource that the user accessed using /enc/ returns a 1 on success, 0
11688: on failure, user must be in a course, as it assumes the existance of
11689: the course initial hash, and uses $env('request.course.id'}
11690:
11691:
11692: =item *
11693:
11694: symbclean($symb) : removes versions numbers from a symb, returns the
11695: cleaned symb
11696:
11697: =item *
11698:
11699: is_on_map($uri) : checks if the $uri is somewhere on the current
11700: course map, user must be in a course for it to work.
11701:
11702: =item *
11703:
11704: numval($salt) : return random seed value (addend for rndseed)
11705:
11706: =item *
11707:
11708: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11709: a random seed, all arguments are optional, if they aren't sent it uses the
11710: environment to derive them. Note: if symb isn't sent and it can't get one
11711: from &symbread it will use the current time as its return value
11712:
11713: =item *
11714:
11715: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11716: unfakeable, receipt
11717:
11718: =item *
11719:
11720: receipt() : API to ireceipt working off of env values; given out to users
11721:
11722: =item *
11723:
11724: countacc($url) : count the number of accesses to a given URL
11725:
11726: =item *
11727:
11728: 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
11729:
11730: =item *
11731:
11732: 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)
11733:
11734: =item *
11735:
11736: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11737:
11738: =item *
11739:
11740: devalidate($symb) : devalidate temporary spreadsheet calculations,
11741: forcing spreadsheet to reevaluate the resource scores next time.
11742:
11743: =back
11744:
11745: =head2 Storing/Retreiving Data
11746:
11747: =over 4
11748:
11749: =item *
11750:
11751: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11752: for this url; hashref needs to be given and should be a \%hashname; the
11753: remaining args aren't required and if they aren't passed or are '' they will
11754: be derived from the env
11755:
11756: =item *
11757:
11758: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11759: uses critical subroutine
11760:
11761: =item *
11762:
11763: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11764: all args are optional
11765:
11766: =item *
11767:
11768: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11769: dumps the complete (or key matching regexp) namespace into a hash
11770: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11771: normally &store()ed into
11772:
11773: $range should be either an integer '100' (give me the first 100
11774: matching records)
11775: or be two integers sperated by a - with no spaces
11776: '30-50' (give me the 30th through the 50th matching
11777: records)
11778:
11779:
11780: =item *
11781:
11782: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11783: replaces a &store() version of data with a replacement set of data
11784: for a particular resource in a namespace passed in the $storehash hash
11785: reference
11786:
11787: =item *
11788:
11789: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11790: works very similar to store/cstore, but all data is stored in a
11791: temporary location and can be reset using tmpreset, $storehash should
11792: be a hash reference, returns nothing on success
11793:
11794: =item *
11795:
11796: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11797: similar to restore, but all data is stored in a temporary location and
11798: can be reset using tmpreset. Returns a hash of values on success,
11799: error string otherwise.
11800:
11801: =item *
11802:
11803: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11804: deltes all keys for $symb form the temporary storage hash.
11805:
11806: =item *
11807:
11808: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11809: reference filled in from namesp ($udom and $uname are optional)
11810:
11811: =item *
11812:
11813: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11814: namesp ($udom and $uname are optional)
11815:
11816: =item *
11817:
11818: dump($namespace,$udom,$uname,$regexp,$range) :
11819: dumps the complete (or key matching regexp) namespace into a hash
11820: ($udom, $uname, $regexp, $range are optional)
11821:
11822: $range should be either an integer '100' (give me the first 100
11823: matching records)
11824: or be two integers sperated by a - with no spaces
11825: '30-50' (give me the 30th through the 50th matching
11826: records)
11827: =item *
11828:
11829: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11830: $store can be a scalar, an array reference, or if the amount to be
11831: incremented is > 1, a hash reference.
11832:
11833: ($udom and $uname are optional)
11834:
11835: =item *
11836:
11837: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11838: ($udom and $uname are optional)
11839:
11840: =item *
11841:
11842: cput($namespace,$storehash,$udom,$uname) : critical put
11843: ($udom and $uname are optional)
11844:
11845: =item *
11846:
11847: newput($namespace,$storehash,$udom,$uname) :
11848:
11849: Attempts to store the items in the $storehash, but only if they don't
11850: currently exist, if this succeeds you can be certain that you have
11851: successfully created a new key value pair in the $namespace db.
11852:
11853:
11854: Args:
11855: $namespace: name of database to store values to
11856: $storehash: hashref to store to the db
11857: $udom: (optional) domain of user containing the db
11858: $uname: (optional) name of user caontaining the db
11859:
11860: Returns:
11861: 'ok' -> succeeded in storing all keys of $storehash
11862: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11863: least <key> already existed in the db (other
11864: requested keys may also already exist)
11865: 'error: <msg>' -> unable to tie the DB or other error occurred
11866: 'con_lost' -> unable to contact request server
11867: 'refused' -> action was not allowed by remote machine
11868:
11869:
11870: =item *
11871:
11872: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11873: reference filled in from namesp (encrypts the return communication)
11874: ($udom and $uname are optional)
11875:
11876: =item *
11877:
11878: log($udom,$name,$home,$message) : write to permanent log for user; use
11879: critical subroutine
11880:
11881: =item *
11882:
11883: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11884: array reference filled in from namespace found in domain level on either
11885: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11886:
11887: =item *
11888:
11889: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11890: domain level either on specified domain server ($uhome) or primary domain
11891: server ($udom and $uhome are optional)
11892:
11893: =item *
11894:
11895: get_domain_defaults($target_domain) : returns hash with defaults for
11896: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11897: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11898: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11899: Values are retrieved from cache (if current), or from domain's configuration.db
11900: (if available), or lastly from values in lonTabs/dns_domain,tab,
11901: or lonTabs/domain.tab.
11902:
11903: %domdefaults = &get_auth_defaults($target_domain);
11904:
11905: =back
11906:
11907: =head2 Network Status Functions
11908:
11909: =over 4
11910:
11911: =item *
11912:
11913: dirlist() : return directory list based on URI (first arg).
11914:
11915: Inputs: 1 required, 5 optional.
11916:
11917: =over
11918:
11919: =item
11920: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11921:
11922: =item
11923: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
11924:
11925: =item
11926: $username - username of user/course to be listed. Extracted from $uri if absent.
11927:
11928: =item
11929: $getpropath - boolean: 1 if prepend path using &propath().
11930:
11931: =item
11932: $getuserdir - boolean: 1 if prepend path for "userfiles".
11933:
11934: =item
11935: $alternateRoot - path to prepend in place of path from $uri.
11936:
11937: =back
11938:
11939: Returns: Array of up to two items.
11940:
11941: =over
11942:
11943: a reference to an array of files/subdirectories
11944:
11945: =over
11946:
11947: Each element in the array of files/subdirectories is a & separated list of
11948: item name and the result of running stat on the item. If dirlist was requested
11949: for a file instead of a directory, the item name will be ''. For a directory
11950: listing, if the item is a metadata file, the element will end &N&M
11951: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11952: default copyright set (1).
11953:
11954: =back
11955:
11956: a scalar containing error condition (if encountered).
11957:
11958: =over
11959:
11960: =item
11961: no_host (no homeserver identified for $username:$domain).
11962:
11963: =item
11964: no_such_host (server contacted for listing not identified as valid host).
11965:
11966: =item
11967: con_lost (connection to remote server failed).
11968:
11969: =item
11970: refused (invalid $username:$domain received on lond side).
11971:
11972: =item
11973: no_such_dir (directory at specified path on lond side does not exist).
11974:
11975: =item
11976: empty (directory at specified path on lond side is empty).
11977:
11978: =over
11979:
11980: This is currently not encountered because the &ls3, &ls2,
11981: &ls (_handler) routines on the lond side do not filter out
11982: . and .. from a directory listing.
11983:
11984: =back
11985:
11986: =back
11987:
11988: =back
11989:
11990: =item *
11991:
11992: spareserver() : find server with least workload from spare.tab
11993:
11994:
11995: =item *
11996:
11997: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11998: if there is no corresponding loncapa host.
11999:
12000: =back
12001:
12002:
12003: =head2 Apache Request
12004:
12005: =over 4
12006:
12007: =item *
12008:
12009: ssi($url,%hash) : server side include, does a complete request cycle on url to
12010: localhost, posts hash
12011:
12012: =back
12013:
12014: =head2 Data to String to Data
12015:
12016: =over 4
12017:
12018: =item *
12019:
12020: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12021: and '&' separators, supports elements that are arrayrefs and hashrefs
12022:
12023: =item *
12024:
12025: hashref2str($hashref) : convert a hashref into a string complete with
12026: escaping and '=' and '&' separators, supports elements that are
12027: arrayrefs and hashrefs
12028:
12029: =item *
12030:
12031: arrayref2str($arrayref) : convert an arrayref into a string complete
12032: with escaping and '&' separators, supports elements that are arrayrefs
12033: and hashrefs
12034:
12035: =item *
12036:
12037: str2hash($string) : convert string to hash using unescaping and
12038: splitting on '=' and '&', supports elements that are arrayrefs and
12039: hashrefs
12040:
12041: =item *
12042:
12043: str2array($string) : convert string to hash using unescaping and
12044: splitting on '&', supports elements that are arrayrefs and hashrefs
12045:
12046: =back
12047:
12048: =head2 Logging Routines
12049:
12050:
12051: These routines allow one to make log messages in the lonnet.log and
12052: lonnet.perm logfiles.
12053:
12054: =over 4
12055:
12056: =item *
12057:
12058: logtouch() : make sure the logfile, lonnet.log, exists
12059:
12060: =item *
12061:
12062: logthis() : append message to the normal lonnet.log file, it gets
12063: preiodically rolled over and deleted.
12064:
12065: =item *
12066:
12067: logperm() : append a permanent message to lonnet.perm.log, this log
12068: file never gets deleted by any automated portion of the system, only
12069: messages of critical importance should go in here.
12070:
12071:
12072: =back
12073:
12074: =head2 General File Helper Routines
12075:
12076: =over 4
12077:
12078: =item *
12079:
12080: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12081: (a) files in /uploaded
12082: (i) If a local copy of the file exists -
12083: compares modification date of local copy with last-modified date for
12084: definitive version stored on home server for course. If local copy is
12085: stale, requests a new version from the home server and stores it.
12086: If the original has been removed from the home server, then local copy
12087: is unlinked.
12088: (ii) If local copy does not exist -
12089: requests the file from the home server and stores it.
12090:
12091: If $caller is 'uploadrep':
12092: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12093: for request for files originally uploaded via DOCS.
12094: - returns 'ok' if fresh local copy now available, -1 otherwise.
12095:
12096: Otherwise:
12097: This indicates a call from the content generation phase of the request.
12098: - returns the entire contents of the file or -1.
12099:
12100: (b) files in /res
12101: - returns the entire contents of a file or -1;
12102: it properly subscribes to and replicates the file if neccessary.
12103:
12104:
12105: =item *
12106:
12107: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12108: reference
12109:
12110: returns either a stat() list of data about the file or an empty list
12111: if the file doesn't exist or couldn't find out about it (connection
12112: problems or user unknown)
12113:
12114: =item *
12115:
12116: filelocation($dir,$file) : returns file system location of a file
12117: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12118: directory that relative $file lookups are to looked in ($dir of /a/dir
12119: and a file of ../bob will become /a/bob)
12120:
12121: =item *
12122:
12123: hreflocation($dir,$file) : returns file system location or a URL; same as
12124: filelocation except for hrefs
12125:
12126: =item *
12127:
12128: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12129:
12130: =back
12131:
12132: =head2 Usererfile file routines (/uploaded*)
12133:
12134: =over 4
12135:
12136: =item *
12137:
12138: userfileupload(): main rotine for putting a file in a user or course's
12139: filespace, arguments are,
12140:
12141: formname - required - this is the name of the element in $env where the
12142: filename, and the contents of the file to create/modifed exist
12143: the filename is in $env{'form.'.$formname.'.filename'} and the
12144: contents of the file is located in $env{'form.'.$formname}
12145: context - if coursedoc, store the file in the course of the active role
12146: of the current user;
12147: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12148: if 'canceloverwrite': delete file in tmp/overwrites directory
12149: subdir - required - subdirectory to put the file in under ../userfiles/
12150: if undefined, it will be placed in "unknown"
12151:
12152: (This routine calls clean_filename() to remove any dangerous
12153: characters from the filename, and then calls finuserfileupload() to
12154: complete the transaction)
12155:
12156: returns either the url of the uploaded file (/uploaded/....) if successful
12157: and /adm/notfound.html if unsuccessful
12158:
12159: =item *
12160:
12161: clean_filename(): routine for cleaing a filename up for storage in
12162: userfile space, argument is:
12163:
12164: filename - proposed filename
12165:
12166: returns: the new clean filename
12167:
12168: =item *
12169:
12170: finishuserfileupload(): routine that creates and sends the file to
12171: userspace, probably shouldn't be called directly
12172:
12173: docuname: username or courseid of destination for the file
12174: docudom: domain of user/course of destination for the file
12175: formname: same as for userfileupload()
12176: fname: filename (including subdirectories) for the file
12177: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12178: allfiles: reference to hash used to store objects found by parser
12179: codebase: reference to hash used for codebases of java objects found by parser
12180: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12181: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12182: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12183: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12184: context: if 'overwrite', will move the uploaded file from its temporary location to
12185: userfiles to facilitate overwriting a previously uploaded file with same name.
12186: mimetype: reference to scalar to accommodate mime type determined
12187: from File::MMagic if $parser = parse.
12188:
12189: returns either the url of the uploaded file (/uploaded/....) if successful
12190: and /adm/notfound.html if unsuccessful (or an error message if context
12191: was 'overwrite').
12192:
12193:
12194: =item *
12195:
12196: renameuserfile(): renames an existing userfile to a new name
12197:
12198: Args:
12199: docuname: username or courseid of destination for the file
12200: docudom: domain of user/course of destination for the file
12201: old: current file name (including any subdirs under userfiles)
12202: new: desired file name (including any subdirs under userfiles)
12203:
12204: =item *
12205:
12206: mkdiruserfile(): creates a directory is a userfiles dir
12207:
12208: Args:
12209: docuname: username or courseid of destination for the file
12210: docudom: domain of user/course of destination for the file
12211: dir: dir to create (including any subdirs under userfiles)
12212:
12213: =item *
12214:
12215: removeuserfile(): removes a file that exists in userfiles
12216:
12217: Args:
12218: docuname: username or courseid of destination for the file
12219: docudom: domain of user/course of destination for the file
12220: fname: filname to delete (including any subdirs under userfiles)
12221:
12222: =item *
12223:
12224: removeuploadedurl(): convience function for removeuserfile()
12225:
12226: Args:
12227: url: a full /uploaded/... url to delete
12228:
12229: =item *
12230:
12231: get_portfile_permissions():
12232: Args:
12233: domain: domain of user or course contain the portfolio files
12234: user: name of user or num of course contain the portfolio files
12235: Returns:
12236: hashref of a dump of the proper file_permissions.db
12237:
12238:
12239: =item *
12240:
12241: get_access_controls():
12242:
12243: Args:
12244: current_permissions: the hash ref returned from get_portfile_permissions()
12245: group: (optional) the group you want the files associated with
12246: file: (optional) the file you want access info on
12247:
12248: Returns:
12249: a hash (keys are file names) of hashes containing
12250: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12251: values are XML containing access control settings (see below)
12252:
12253: Internal notes:
12254:
12255: access controls are stored in file_permissions.db as key=value pairs.
12256: key -> path to file/file_name\0uniqueID:scope_end_start
12257: where scope -> public,guest,course,group,domains or users.
12258: end -> UNIX time for end of access (0 -> no end date)
12259: start -> UNIX time for start of access
12260:
12261: value -> XML description of access control
12262: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12263: <start></start>
12264: <end></end>
12265:
12266: <password></password> for scope type = guest
12267:
12268: <domain></domain> for scope type = course or group
12269: <number></number>
12270: <roles id="">
12271: <role></role>
12272: <access></access>
12273: <section></section>
12274: <group></group>
12275: </roles>
12276:
12277: <dom></dom> for scope type = domains
12278:
12279: <users> for scope type = users
12280: <user>
12281: <uname></uname>
12282: <udom></udom>
12283: </user>
12284: </users>
12285: </scope>
12286:
12287: Access data is also aggregated for each file in an additional key=value pair:
12288: key -> path to file/file_name\0accesscontrol
12289: value -> reference to hash
12290: hash contains key = value pairs
12291: where key = uniqueID:scope_end_start
12292: value = UNIX time record was last updated
12293:
12294: Used to improve speed of look-ups of access controls for each file.
12295:
12296: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12297:
12298: modify_access_controls():
12299:
12300: Modifies access controls for a portfolio file
12301: Args
12302: 1. file name
12303: 2. reference to hash of required changes,
12304: 3. domain
12305: 4. username
12306: where domain,username are the domain of the portfolio owner
12307: (either a user or a course)
12308:
12309: Returns:
12310: 1. result of additions or updates ('ok' or 'error', with error message).
12311: 2. result of deletions ('ok' or 'error', with error message).
12312: 3. reference to hash of any new or updated access controls.
12313: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12314: key = integer (inbound ID)
12315: value = uniqueID
12316:
12317: =back
12318:
12319: =head2 HTTP Helper Routines
12320:
12321: =over 4
12322:
12323: =item *
12324:
12325: escape() : unpack non-word characters into CGI-compatible hex codes
12326:
12327: =item *
12328:
12329: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12330:
12331: =back
12332:
12333: =head1 PRIVATE SUBROUTINES
12334:
12335: =head2 Underlying communication routines (Shouldn't call)
12336:
12337: =over 4
12338:
12339: =item *
12340:
12341: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12342:
12343: =item *
12344:
12345: reply() : uses subreply to send a message to remote machine, logs all failures
12346:
12347: =item *
12348:
12349: critical() : passes a critical message to another server; if cannot
12350: get through then place message in connection buffer directory and
12351: returns con_delayed, if incapable of saving message, returns
12352: con_failed
12353:
12354: =item *
12355:
12356: reconlonc() : tries to reconnect lonc client processes.
12357:
12358: =back
12359:
12360: =head2 Resource Access Logging
12361:
12362: =over 4
12363:
12364: =item *
12365:
12366: flushcourselogs() : flush (save) buffer logs and access logs
12367:
12368: =item *
12369:
12370: courselog($what) : save message for course in hash
12371:
12372: =item *
12373:
12374: courseacclog($what) : save message for course using &courselog(). Perform
12375: special processing for specific resource types (problems, exams, quizzes, etc).
12376:
12377: =item *
12378:
12379: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12380: as a PerlChildExitHandler
12381:
12382: =back
12383:
12384: =head2 Other
12385:
12386: =over 4
12387:
12388: =item *
12389:
12390: symblist($mapname,%newhash) : update symbolic storage links
12391:
12392: =back
12393:
12394: =cut
12395:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>