1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1152 2012/02/01 00:18:29 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,$isredirect);
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: $isredirect = 1;
945: }
946: } else {
947: ($login_host, $lowest_load) =
948: &compare_server_load($lonhost, $login_host, $lowest_load);
949: if ($login_host eq $lonhost) {
950: $portal_path = '';
951: $isredirect = '';
952: }
953: }
954: } else {
955: ($login_host, $lowest_load) =
956: &compare_server_load($lonhost, $login_host, $lowest_load);
957: }
958: }
959: if ($login_host ne '') {
960: $hostname = &hostname($login_host);
961: }
962: return ($login_host,$hostname,$portal_path,$isredirect);
963: }
964:
965: # --------------------------------------------- Try to change a user's password
966:
967: sub changepass {
968: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
969: $currentpass = &escape($currentpass);
970: $newpass = &escape($newpass);
971: my $lonhost = $perlvar{'lonHostID'};
972: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
973: $server);
974: if (! $answer) {
975: &logthis("No reply on password change request to $server ".
976: "by $uname in domain $udom.");
977: } elsif ($answer =~ "^ok") {
978: &logthis("$uname in $udom successfully changed their password ".
979: "on $server.");
980: } elsif ($answer =~ "^pwchange_failure") {
981: &logthis("$uname in $udom was unable to change their password ".
982: "on $server. The action was blocked by either lcpasswd ".
983: "or pwchange");
984: } elsif ($answer =~ "^non_authorized") {
985: &logthis("$uname in $udom did not get their password correct when ".
986: "attempting to change it on $server.");
987: } elsif ($answer =~ "^auth_mode_error") {
988: &logthis("$uname in $udom attempted to change their password despite ".
989: "not being locally or internally authenticated on $server.");
990: } elsif ($answer =~ "^unknown_user") {
991: &logthis("$uname in $udom attempted to change their password ".
992: "on $server but were unable to because $server is not ".
993: "their home server.");
994: } elsif ($answer =~ "^refused") {
995: &logthis("$server refused to change $uname in $udom password because ".
996: "it was sent an unencrypted request to change the password.");
997: } elsif ($answer =~ "invalid_client") {
998: &logthis("$server refused to change $uname in $udom password because ".
999: "it was a reset by e-mail originating from an invalid server.");
1000: }
1001: return $answer;
1002: }
1003:
1004: # ----------------------- Try to determine user's current authentication scheme
1005:
1006: sub queryauthenticate {
1007: my ($uname,$udom)=@_;
1008: my $uhome=&homeserver($uname,$udom);
1009: if (!$uhome) {
1010: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1011: return 'no_host';
1012: }
1013: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1014: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1015: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1016: }
1017: return $answer;
1018: }
1019:
1020: # --------- Try to authenticate user from domain's lib servers (first this one)
1021:
1022: sub authenticate {
1023: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1024: $upass=&escape($upass);
1025: $uname= &LONCAPA::clean_username($uname);
1026: my $uhome=&homeserver($uname,$udom,1);
1027: my $newhome;
1028: if ((!$uhome) || ($uhome eq 'no_host')) {
1029: # Maybe the machine was offline and only re-appeared again recently?
1030: &reconlonc();
1031: # One more
1032: $uhome=&homeserver($uname,$udom,1);
1033: if (($uhome eq 'no_host') && $checkdefauth) {
1034: if (defined(&domain($udom,'primary'))) {
1035: $newhome=&domain($udom,'primary');
1036: }
1037: if ($newhome ne '') {
1038: $uhome = $newhome;
1039: }
1040: }
1041: if ((!$uhome) || ($uhome eq 'no_host')) {
1042: &logthis("User $uname at $udom is unknown in authenticate");
1043: return 'no_host';
1044: }
1045: }
1046: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1047: if ($answer eq 'authorized') {
1048: if ($newhome) {
1049: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1050: return 'no_account_on_host';
1051: } else {
1052: &logthis("User $uname at $udom authorized by $uhome");
1053: return $uhome;
1054: }
1055: }
1056: if ($answer eq 'non_authorized') {
1057: &logthis("User $uname at $udom rejected by $uhome");
1058: return 'no_host';
1059: }
1060: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1061: return 'no_host';
1062: }
1063:
1064: sub can_host_session {
1065: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1066: my $canhost = 1;
1067: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1068: if (ref($remotesessions) eq 'HASH') {
1069: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1070: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1071: $canhost = 0;
1072: } else {
1073: $canhost = 1;
1074: }
1075: }
1076: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1077: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1078: $canhost = 1;
1079: } else {
1080: $canhost = 0;
1081: }
1082: }
1083: if ($canhost) {
1084: if ($remotesessions->{'version'} ne '') {
1085: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1086: if ($reqmajor ne '' && $reqminor ne '') {
1087: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1088: my $major = $1;
1089: my $minor = $2;
1090: if (($major < $reqmajor ) ||
1091: (($major == $reqmajor) && ($minor < $reqminor))) {
1092: $canhost = 0;
1093: }
1094: } else {
1095: $canhost = 0;
1096: }
1097: }
1098: }
1099: }
1100: }
1101: if ($canhost) {
1102: if (ref($hostedsessions) eq 'HASH') {
1103: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1104: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1105: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1106: if (($uint_dom ne '') &&
1107: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1108: $canhost = 0;
1109: } else {
1110: $canhost = 1;
1111: }
1112: }
1113: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1114: if (($uint_dom ne '') &&
1115: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1116: $canhost = 1;
1117: } else {
1118: $canhost = 0;
1119: }
1120: }
1121: }
1122: }
1123: return $canhost;
1124: }
1125:
1126: sub spare_can_host {
1127: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1128: my $canhost=1;
1129: my @intdoms;
1130: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1131: if (ref($internet_names) eq 'ARRAY') {
1132: @intdoms = @{$internet_names};
1133: }
1134: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1135: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1136: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1137: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1138: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1139: $canhost = &can_host_session($udom,$try_server,$remoterev,
1140: $remotesessions,
1141: $defdomdefaults{'hostedsessions'});
1142: }
1143: return $canhost;
1144: }
1145:
1146: sub this_host_spares {
1147: my ($dom) = @_;
1148: my ($dom_in_use,$lonhost_in_use,$result);
1149: my @hosts = ¤t_machine_ids();
1150: foreach my $lonhost (@hosts) {
1151: if (&host_domain($lonhost) eq $dom) {
1152: $dom_in_use = $dom;
1153: $lonhost_in_use = $lonhost;
1154: last;
1155: }
1156: }
1157: if ($dom_in_use ne '') {
1158: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1159: }
1160: if (ref($result) ne 'HASH') {
1161: $lonhost_in_use = $perlvar{'lonHostID'};
1162: $dom_in_use = &host_domain($lonhost_in_use);
1163: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1164: if (ref($result) ne 'HASH') {
1165: $result = \%spareid;
1166: }
1167: }
1168: return $result;
1169: }
1170:
1171: sub spares_for_offload {
1172: my ($dom_in_use,$lonhost_in_use) = @_;
1173: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1174: if (defined($cached)) {
1175: return $result;
1176: } else {
1177: my $cachetime = 60*60*24;
1178: my %domconfig =
1179: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1180: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1181: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1182: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1183: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1184: }
1185: }
1186: }
1187: }
1188: return;
1189: }
1190:
1191: sub get_lonbalancer_config {
1192: my ($servers) = @_;
1193: my ($currbalancer,$currtargets);
1194: if (ref($servers) eq 'HASH') {
1195: foreach my $server (keys(%{$servers})) {
1196: my %what = (
1197: spareid => 1,
1198: perlvar => 1,
1199: );
1200: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1201: if ($result eq 'ok') {
1202: if (ref($returnhash) eq 'HASH') {
1203: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1204: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1205: $currbalancer = $server;
1206: $currtargets = {};
1207: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1208: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1209: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1210: }
1211: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1212: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1213: }
1214: }
1215: last;
1216: }
1217: }
1218: }
1219: }
1220: }
1221: }
1222: return ($currbalancer,$currtargets);
1223: }
1224:
1225: sub check_loadbalancing {
1226: my ($uname,$udom) = @_;
1227: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1228: $offloadto,$otherserver);
1229: my $lonhost = $perlvar{'lonHostID'};
1230: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1231: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1232: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1233: my $serverhomedom = &host_domain($lonhost);
1234:
1235: my $cachetime = 60*60*24;
1236:
1237: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1238: $dom_in_use = $udom;
1239: $homeintdom = 1;
1240: } else {
1241: $dom_in_use = $serverhomedom;
1242: }
1243: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1244: unless (defined($cached)) {
1245: my %domconfig =
1246: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1247: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1248: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1249: }
1250: }
1251: if (ref($result) eq 'HASH') {
1252: my $currbalancer = $result->{'lonhost'};
1253: my $currtargets = $result->{'targets'};
1254: my $currrules = $result->{'rules'};
1255: if ($currbalancer ne '') {
1256: my @hosts = ¤t_machine_ids();
1257: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1258: $is_balancer = 1;
1259: }
1260: }
1261: if ($is_balancer) {
1262: if (ref($currrules) eq 'HASH') {
1263: if ($homeintdom) {
1264: if ($uname ne '') {
1265: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1266: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1267: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1268: $rule_in_effect = $currrules->{'_LC_author'};
1269: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1270: $rule_in_effect = $currrules->{'_LC_adv'}
1271: }
1272: }
1273: if ($rule_in_effect eq '') {
1274: my %userenv = &userenvironment($udom,$uname,'inststatus');
1275: if ($userenv{'inststatus'} ne '') {
1276: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1277: my ($othertitle,$usertypes,$types) =
1278: &Apache::loncommon::sorted_inst_types($udom);
1279: if (ref($types) eq 'ARRAY') {
1280: foreach my $type (@{$types}) {
1281: if (grep(/^\Q$type\E$/,@statuses)) {
1282: if (exists($currrules->{$type})) {
1283: $rule_in_effect = $currrules->{$type};
1284: }
1285: }
1286: }
1287: }
1288: } else {
1289: if (exists($currrules->{'default'})) {
1290: $rule_in_effect = $currrules->{'default'};
1291: }
1292: }
1293: }
1294: } else {
1295: if (exists($currrules->{'default'})) {
1296: $rule_in_effect = $currrules->{'default'};
1297: }
1298: }
1299: } else {
1300: if ($currrules->{'_LC_external'} ne '') {
1301: $rule_in_effect = $currrules->{'_LC_external'};
1302: }
1303: }
1304: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1305: $uname,$udom);
1306: }
1307: }
1308: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1309: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1310: unless (defined($cached)) {
1311: my %domconfig =
1312: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1313: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1314: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1315: }
1316: }
1317: if (ref($result) eq 'HASH') {
1318: my $currbalancer = $result->{'lonhost'};
1319: my $currtargets = $result->{'targets'};
1320: my $currrules = $result->{'rules'};
1321:
1322: if ($currbalancer eq $lonhost) {
1323: $is_balancer = 1;
1324: if (ref($currrules) eq 'HASH') {
1325: if ($currrules->{'_LC_internetdom'} ne '') {
1326: $rule_in_effect = $currrules->{'_LC_internetdom'};
1327: }
1328: }
1329: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1330: $uname,$udom);
1331: }
1332: } else {
1333: if ($perlvar{'lonBalancer'} eq 'yes') {
1334: $is_balancer = 1;
1335: $offloadto = &this_host_spares($dom_in_use);
1336: }
1337: }
1338: } else {
1339: if ($perlvar{'lonBalancer'} eq 'yes') {
1340: $is_balancer = 1;
1341: $offloadto = &this_host_spares($dom_in_use);
1342: }
1343: }
1344: my $lowest_load = 30000;
1345: if (ref($offloadto) eq 'HASH') {
1346: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1347: foreach my $try_server (@{$offloadto->{'primary'}}) {
1348: ($otherserver,$lowest_load) =
1349: &compare_server_load($try_server,$otherserver,$lowest_load);
1350: }
1351: }
1352: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1353:
1354: if (!$found_server) {
1355: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1356: foreach my $try_server (@{$offloadto->{'default'}}) {
1357: ($otherserver,$lowest_load) =
1358: &compare_server_load($try_server,$otherserver,$lowest_load);
1359: }
1360: }
1361: }
1362: } elsif (ref($offloadto) eq 'ARRAY') {
1363: if (@{$offloadto} == 1) {
1364: $otherserver = $offloadto->[0];
1365: } elsif (@{$offloadto} > 1) {
1366: foreach my $try_server (@{$offloadto}) {
1367: ($otherserver,$lowest_load) =
1368: &compare_server_load($try_server,$otherserver,$lowest_load);
1369: }
1370: }
1371: }
1372: return ($is_balancer,$otherserver);
1373: }
1374:
1375: sub get_loadbalancer_targets {
1376: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1377: my $offloadto;
1378: if ($rule_in_effect eq '') {
1379: $offloadto = $currtargets;
1380: } else {
1381: if ($rule_in_effect eq 'homeserver') {
1382: my $homeserver = &homeserver($uname,$udom);
1383: if ($homeserver ne 'no_host') {
1384: $offloadto = [$homeserver];
1385: }
1386: } elsif ($rule_in_effect eq 'externalbalancer') {
1387: my %domconfig =
1388: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1389: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1390: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1391: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1392: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1393: }
1394: }
1395: } else {
1396: my %servers = &dom_servers($udom);
1397: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1398: if (&hostname($remotebalancer) ne '') {
1399: $offloadto = [$remotebalancer];
1400: }
1401: }
1402: } elsif (&hostname($rule_in_effect) ne '') {
1403: $offloadto = [$rule_in_effect];
1404: }
1405: }
1406: return $offloadto;
1407: }
1408:
1409: sub internet_dom_servers {
1410: my ($dom) = @_;
1411: my (%uniqservers,%servers);
1412: my $primaryserver = &hostname(&domain($dom,'primary'));
1413: my @machinedoms = &machine_domains($primaryserver);
1414: foreach my $mdom (@machinedoms) {
1415: my %currservers = %servers;
1416: my %server = &get_servers($mdom);
1417: %servers = (%currservers,%server);
1418: }
1419: my %by_hostname;
1420: foreach my $id (keys(%servers)) {
1421: push(@{$by_hostname{$servers{$id}}},$id);
1422: }
1423: foreach my $hostname (sort(keys(%by_hostname))) {
1424: if (@{$by_hostname{$hostname}} > 1) {
1425: my $match = 0;
1426: foreach my $id (@{$by_hostname{$hostname}}) {
1427: if (&host_domain($id) eq $dom) {
1428: $uniqservers{$id} = $hostname;
1429: $match = 1;
1430: }
1431: }
1432: unless ($match) {
1433: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1434: }
1435: } else {
1436: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1437: }
1438: }
1439: return %uniqservers;
1440: }
1441:
1442: # ---------------------- Find the homebase for a user from domain's lib servers
1443:
1444: my %homecache;
1445: sub homeserver {
1446: my ($uname,$udom,$ignoreBadCache)=@_;
1447: my $index="$uname:$udom";
1448:
1449: if (exists($homecache{$index})) { return $homecache{$index}; }
1450:
1451: my %servers = &get_servers($udom,'library');
1452: foreach my $tryserver (keys(%servers)) {
1453: next if ($ignoreBadCache ne 'true' &&
1454: exists($badServerCache{$tryserver}));
1455:
1456: my $answer=reply("home:$udom:$uname",$tryserver);
1457: if ($answer eq 'found') {
1458: delete($badServerCache{$tryserver});
1459: return $homecache{$index}=$tryserver;
1460: } elsif ($answer eq 'no_host') {
1461: $badServerCache{$tryserver}=1;
1462: }
1463: }
1464: return 'no_host';
1465: }
1466:
1467: # ------------------------------------- Find the usernames behind a list of IDs
1468:
1469: sub idget {
1470: my ($udom,@ids)=@_;
1471: my %returnhash=();
1472:
1473: my %servers = &get_servers($udom,'library');
1474: foreach my $tryserver (keys(%servers)) {
1475: my $idlist=join('&',@ids);
1476: $idlist=~tr/A-Z/a-z/;
1477: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1478: my @answer=();
1479: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1480: @answer=split(/\&/,$reply);
1481: } ;
1482: my $i;
1483: for ($i=0;$i<=$#ids;$i++) {
1484: if ($answer[$i]) {
1485: $returnhash{$ids[$i]}=$answer[$i];
1486: }
1487: }
1488: }
1489: return %returnhash;
1490: }
1491:
1492: # ------------------------------------- Find the IDs behind a list of usernames
1493:
1494: sub idrget {
1495: my ($udom,@unames)=@_;
1496: my %returnhash=();
1497: foreach my $uname (@unames) {
1498: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1499: }
1500: return %returnhash;
1501: }
1502:
1503: # ------------------------------- Store away a list of names and associated IDs
1504:
1505: sub idput {
1506: my ($udom,%ids)=@_;
1507: my %servers=();
1508: foreach my $uname (keys(%ids)) {
1509: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1510: my $uhom=&homeserver($uname,$udom);
1511: if ($uhom ne 'no_host') {
1512: my $id=&escape($ids{$uname});
1513: $id=~tr/A-Z/a-z/;
1514: my $esc_unam=&escape($uname);
1515: if ($servers{$uhom}) {
1516: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1517: } else {
1518: $servers{$uhom}=$id.'='.$esc_unam;
1519: }
1520: }
1521: }
1522: foreach my $server (keys(%servers)) {
1523: &critical('idput:'.$udom.':'.$servers{$server},$server);
1524: }
1525: }
1526:
1527: # ------------------------------dump from db file owned by domainconfig user
1528: sub dump_dom {
1529: my ($namespace,$udom,$regexp,$range)=@_;
1530: if (!$udom) {
1531: $udom=$env{'user.domain'};
1532: }
1533: my %returnhash;
1534: if ($udom) {
1535: my $uname = &get_domainconfiguser($udom);
1536: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1537: }
1538: return %returnhash;
1539: }
1540:
1541: # ------------------------------------------ get items from domain db files
1542:
1543: sub get_dom {
1544: my ($namespace,$storearr,$udom,$uhome)=@_;
1545: my $items='';
1546: foreach my $item (@$storearr) {
1547: $items.=&escape($item).'&';
1548: }
1549: $items=~s/\&$//;
1550: if (!$udom) {
1551: $udom=$env{'user.domain'};
1552: if (defined(&domain($udom,'primary'))) {
1553: $uhome=&domain($udom,'primary');
1554: } else {
1555: undef($uhome);
1556: }
1557: } else {
1558: if (!$uhome) {
1559: if (defined(&domain($udom,'primary'))) {
1560: $uhome=&domain($udom,'primary');
1561: }
1562: }
1563: }
1564: if ($udom && $uhome && ($uhome ne 'no_host')) {
1565: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1566: my %returnhash;
1567: if ($rep eq '' || $rep =~ /^error: 2 /) {
1568: return %returnhash;
1569: }
1570: my @pairs=split(/\&/,$rep);
1571: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1572: return @pairs;
1573: }
1574: my $i=0;
1575: foreach my $item (@$storearr) {
1576: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1577: $i++;
1578: }
1579: return %returnhash;
1580: } else {
1581: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1582: }
1583: }
1584:
1585: # -------------------------------------------- put items in domain db files
1586:
1587: sub put_dom {
1588: my ($namespace,$storehash,$udom,$uhome)=@_;
1589: if (!$udom) {
1590: $udom=$env{'user.domain'};
1591: if (defined(&domain($udom,'primary'))) {
1592: $uhome=&domain($udom,'primary');
1593: } else {
1594: undef($uhome);
1595: }
1596: } else {
1597: if (!$uhome) {
1598: if (defined(&domain($udom,'primary'))) {
1599: $uhome=&domain($udom,'primary');
1600: }
1601: }
1602: }
1603: if ($udom && $uhome && ($uhome ne 'no_host')) {
1604: my $items='';
1605: foreach my $item (keys(%$storehash)) {
1606: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1607: }
1608: $items=~s/\&$//;
1609: return &reply("putdom:$udom:$namespace:$items",$uhome);
1610: } else {
1611: &logthis("put_dom failed - no homeserver and/or domain");
1612: }
1613: }
1614:
1615: # --------------------- newput for items in db file owned by domainconfig user
1616: sub newput_dom {
1617: my ($namespace,$storehash,$udom) = @_;
1618: my $result;
1619: if (!$udom) {
1620: $udom=$env{'user.domain'};
1621: }
1622: if ($udom) {
1623: my $uname = &get_domainconfiguser($udom);
1624: $result = &newput($namespace,$storehash,$udom,$uname);
1625: }
1626: return $result;
1627: }
1628:
1629: # --------------------- delete for items in db file owned by domainconfig user
1630: sub del_dom {
1631: my ($namespace,$storearr,$udom)=@_;
1632: if (ref($storearr) eq 'ARRAY') {
1633: if (!$udom) {
1634: $udom=$env{'user.domain'};
1635: }
1636: if ($udom) {
1637: my $uname = &get_domainconfiguser($udom);
1638: return &del($namespace,$storearr,$udom,$uname);
1639: }
1640: }
1641: }
1642:
1643: # ----------------------------------construct domainconfig user for a domain
1644: sub get_domainconfiguser {
1645: my ($udom) = @_;
1646: return $udom.'-domainconfig';
1647: }
1648:
1649: sub retrieve_inst_usertypes {
1650: my ($udom) = @_;
1651: my (%returnhash,@order);
1652: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1653: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1654: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1655: %returnhash = %{$domdefs{'inststatustypes'}};
1656: @order = @{$domdefs{'inststatusorder'}};
1657: } else {
1658: if (defined(&domain($udom,'primary'))) {
1659: my $uhome=&domain($udom,'primary');
1660: my $rep=&reply("inst_usertypes:$udom",$uhome);
1661: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1662: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1663: return (\%returnhash,\@order);
1664: }
1665: my ($hashitems,$orderitems) = split(/:/,$rep);
1666: my @pairs=split(/\&/,$hashitems);
1667: foreach my $item (@pairs) {
1668: my ($key,$value)=split(/=/,$item,2);
1669: $key = &unescape($key);
1670: next if ($key =~ /^error: 2 /);
1671: $returnhash{$key}=&thaw_unescape($value);
1672: }
1673: my @esc_order = split(/\&/,$orderitems);
1674: foreach my $item (@esc_order) {
1675: push(@order,&unescape($item));
1676: }
1677: } else {
1678: &logthis("get_dom failed - no primary domain server for $udom");
1679: }
1680: }
1681: return (\%returnhash,\@order);
1682: }
1683:
1684: sub is_domainimage {
1685: my ($url) = @_;
1686: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1687: if (&domain($1) ne '') {
1688: return '1';
1689: }
1690: }
1691: return;
1692: }
1693:
1694: sub inst_directory_query {
1695: my ($srch) = @_;
1696: my $udom = $srch->{'srchdomain'};
1697: my %results;
1698: my $homeserver = &domain($udom,'primary');
1699: my $outcome;
1700: if ($homeserver ne '') {
1701: my $queryid=&reply("querysend:instdirsearch:".
1702: &escape($srch->{'srchby'}).':'.
1703: &escape($srch->{'srchterm'}).':'.
1704: &escape($srch->{'srchtype'}),$homeserver);
1705: my $host=&hostname($homeserver);
1706: if ($queryid !~/^\Q$host\E\_/) {
1707: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1708: return;
1709: }
1710: my $response = &get_query_reply($queryid);
1711: my $maxtries = 5;
1712: my $tries = 1;
1713: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1714: $response = &get_query_reply($queryid);
1715: $tries ++;
1716: }
1717:
1718: if (!&error($response) && $response ne 'refused') {
1719: if ($response eq 'unavailable') {
1720: $outcome = $response;
1721: } else {
1722: $outcome = 'ok';
1723: my @matches = split(/\n/,$response);
1724: foreach my $match (@matches) {
1725: my ($key,$value) = split(/=/,$match);
1726: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1727: }
1728: }
1729: }
1730: }
1731: return ($outcome,%results);
1732: }
1733:
1734: sub usersearch {
1735: my ($srch) = @_;
1736: my $dom = $srch->{'srchdomain'};
1737: my %results;
1738: my %libserv = &all_library();
1739: my $query = 'usersearch';
1740: foreach my $tryserver (keys(%libserv)) {
1741: if (&host_domain($tryserver) eq $dom) {
1742: my $host=&hostname($tryserver);
1743: my $queryid=
1744: &reply("querysend:".&escape($query).':'.
1745: &escape($srch->{'srchby'}).':'.
1746: &escape($srch->{'srchtype'}).':'.
1747: &escape($srch->{'srchterm'}),$tryserver);
1748: if ($queryid !~/^\Q$host\E\_/) {
1749: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1750: next;
1751: }
1752: my $reply = &get_query_reply($queryid);
1753: my $maxtries = 1;
1754: my $tries = 1;
1755: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1756: $reply = &get_query_reply($queryid);
1757: $tries ++;
1758: }
1759: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1760: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1761: } else {
1762: my @matches;
1763: if ($reply =~ /\n/) {
1764: @matches = split(/\n/,$reply);
1765: } else {
1766: @matches = split(/\&/,$reply);
1767: }
1768: foreach my $match (@matches) {
1769: my ($uname,$udom,%userhash);
1770: foreach my $entry (split(/:/,$match)) {
1771: my ($key,$value) =
1772: map {&unescape($_);} split(/=/,$entry);
1773: $userhash{$key} = $value;
1774: if ($key eq 'username') {
1775: $uname = $value;
1776: } elsif ($key eq 'domain') {
1777: $udom = $value;
1778: }
1779: }
1780: $results{$uname.':'.$udom} = \%userhash;
1781: }
1782: }
1783: }
1784: }
1785: return %results;
1786: }
1787:
1788: sub get_instuser {
1789: my ($udom,$uname,$id) = @_;
1790: my $homeserver = &domain($udom,'primary');
1791: my ($outcome,%results);
1792: if ($homeserver ne '') {
1793: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1794: &escape($id).':'.&escape($udom),$homeserver);
1795: my $host=&hostname($homeserver);
1796: if ($queryid !~/^\Q$host\E\_/) {
1797: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1798: return;
1799: }
1800: my $response = &get_query_reply($queryid);
1801: my $maxtries = 5;
1802: my $tries = 1;
1803: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1804: $response = &get_query_reply($queryid);
1805: $tries ++;
1806: }
1807: if (!&error($response) && $response ne 'refused') {
1808: if ($response eq 'unavailable') {
1809: $outcome = $response;
1810: } else {
1811: $outcome = 'ok';
1812: my @matches = split(/\n/,$response);
1813: foreach my $match (@matches) {
1814: my ($key,$value) = split(/=/,$match);
1815: $results{&unescape($key)} = &thaw_unescape($value);
1816: }
1817: }
1818: }
1819: }
1820: my %userinfo;
1821: if (ref($results{$uname}) eq 'HASH') {
1822: %userinfo = %{$results{$uname}};
1823: }
1824: return ($outcome,%userinfo);
1825: }
1826:
1827: sub inst_rulecheck {
1828: my ($udom,$uname,$id,$item,$rules) = @_;
1829: my %returnhash;
1830: if ($udom ne '') {
1831: if (ref($rules) eq 'ARRAY') {
1832: @{$rules} = map {&escape($_);} (@{$rules});
1833: my $rulestr = join(':',@{$rules});
1834: my $homeserver=&domain($udom,'primary');
1835: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1836: my $response;
1837: if ($item eq 'username') {
1838: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1839: ':'.&escape($uname).':'.$rulestr,
1840: $homeserver));
1841: } elsif ($item eq 'id') {
1842: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1843: ':'.&escape($id).':'.$rulestr,
1844: $homeserver));
1845: } elsif ($item eq 'selfcreate') {
1846: $response=&unescape(&reply('instselfcreatecheck:'.
1847: &escape($udom).':'.&escape($uname).
1848: ':'.$rulestr,$homeserver));
1849: }
1850: if ($response ne 'refused') {
1851: my @pairs=split(/\&/,$response);
1852: foreach my $item (@pairs) {
1853: my ($key,$value)=split(/=/,$item,2);
1854: $key = &unescape($key);
1855: next if ($key =~ /^error: 2 /);
1856: $returnhash{$key}=&thaw_unescape($value);
1857: }
1858: }
1859: }
1860: }
1861: }
1862: return %returnhash;
1863: }
1864:
1865: sub inst_userrules {
1866: my ($udom,$check) = @_;
1867: my (%ruleshash,@ruleorder);
1868: if ($udom ne '') {
1869: my $homeserver=&domain($udom,'primary');
1870: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1871: my $response;
1872: if ($check eq 'id') {
1873: $response=&reply('instidrules:'.&escape($udom),
1874: $homeserver);
1875: } elsif ($check eq 'email') {
1876: $response=&reply('instemailrules:'.&escape($udom),
1877: $homeserver);
1878: } else {
1879: $response=&reply('instuserrules:'.&escape($udom),
1880: $homeserver);
1881: }
1882: if (($response ne 'refused') && ($response ne 'error') &&
1883: ($response ne 'unknown_cmd') &&
1884: ($response ne 'no_such_host')) {
1885: my ($hashitems,$orderitems) = split(/:/,$response);
1886: my @pairs=split(/\&/,$hashitems);
1887: foreach my $item (@pairs) {
1888: my ($key,$value)=split(/=/,$item,2);
1889: $key = &unescape($key);
1890: next if ($key =~ /^error: 2 /);
1891: $ruleshash{$key}=&thaw_unescape($value);
1892: }
1893: my @esc_order = split(/\&/,$orderitems);
1894: foreach my $item (@esc_order) {
1895: push(@ruleorder,&unescape($item));
1896: }
1897: }
1898: }
1899: }
1900: return (\%ruleshash,\@ruleorder);
1901: }
1902:
1903: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1904:
1905: sub get_domain_defaults {
1906: my ($domain) = @_;
1907: my $cachetime = 60*60*24;
1908: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1909: if (defined($cached)) {
1910: if (ref($result) eq 'HASH') {
1911: return %{$result};
1912: }
1913: }
1914: my %domdefaults;
1915: my %domconfig =
1916: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1917: 'requestcourses','inststatus',
1918: 'coursedefaults','usersessions'],$domain);
1919: if (ref($domconfig{'defaults'}) eq 'HASH') {
1920: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1921: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1922: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1923: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1924: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1925: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1926: } else {
1927: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1928: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1929: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1930: }
1931: if (ref($domconfig{'quotas'}) eq 'HASH') {
1932: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1933: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1934: } else {
1935: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1936: }
1937: my @usertools = ('aboutme','blog','portfolio');
1938: foreach my $item (@usertools) {
1939: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1940: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1941: }
1942: }
1943: }
1944: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1945: foreach my $item ('official','unofficial','community') {
1946: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1947: }
1948: }
1949: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1950: foreach my $item ('inststatustypes','inststatusorder') {
1951: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1952: }
1953: }
1954: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1955: foreach my $item ('canuse_pdfforms') {
1956: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1957: }
1958: }
1959: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1960: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1961: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1962: }
1963: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1964: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1965: }
1966: }
1967: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1968: $cachetime);
1969: return %domdefaults;
1970: }
1971:
1972: # --------------------------------------------------- Assign a key to a student
1973:
1974: sub assign_access_key {
1975: #
1976: # a valid key looks like uname:udom#comments
1977: # comments are being appended
1978: #
1979: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1980: $kdom=
1981: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1982: $knum=
1983: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1984: $cdom=
1985: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1986: $cnum=
1987: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1988: $udom=$env{'user.name'} unless (defined($udom));
1989: $uname=$env{'user.domain'} unless (defined($uname));
1990: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1991: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1992: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1993: # assigned to this person
1994: # - this should not happen,
1995: # unless something went wrong
1996: # the first time around
1997: # ready to assign
1998: $logentry=$1.'; '.$logentry;
1999: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2000: $kdom,$knum) eq 'ok') {
2001: # key now belongs to user
2002: my $envkey='key.'.$cdom.'_'.$cnum;
2003: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2004: &appenv({'environment.'.$envkey => $ckey});
2005: return 'ok';
2006: } else {
2007: return
2008: 'error: Count not permanently assign key, will need to be re-entered later.';
2009: }
2010: } else {
2011: return 'error: Could not assign key, try again later.';
2012: }
2013: } elsif (!$existing{$ckey}) {
2014: # the key does not exist
2015: return 'error: The key does not exist';
2016: } else {
2017: # the key is somebody else's
2018: return 'error: The key is already in use';
2019: }
2020: }
2021:
2022: # ------------------------------------------ put an additional comment on a key
2023:
2024: sub comment_access_key {
2025: #
2026: # a valid key looks like uname:udom#comments
2027: # comments are being appended
2028: #
2029: my ($ckey,$cdom,$cnum,$logentry)=@_;
2030: $cdom=
2031: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2032: $cnum=
2033: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2034: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2035: if ($existing{$ckey}) {
2036: $existing{$ckey}.='; '.$logentry;
2037: # ready to assign
2038: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2039: $cdom,$cnum) eq 'ok') {
2040: return 'ok';
2041: } else {
2042: return 'error: Count not store comment.';
2043: }
2044: } else {
2045: # the key does not exist
2046: return 'error: The key does not exist';
2047: }
2048: }
2049:
2050: # ------------------------------------------------------ Generate a set of keys
2051:
2052: sub generate_access_keys {
2053: my ($number,$cdom,$cnum,$logentry)=@_;
2054: $cdom=
2055: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2056: $cnum=
2057: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2058: unless (&allowed('mky',$cdom)) { return 0; }
2059: unless (($cdom) && ($cnum)) { return 0; }
2060: if ($number>10000) { return 0; }
2061: sleep(2); # make sure don't get same seed twice
2062: srand(time()^($$+($$<<15))); # from "Programming Perl"
2063: my $total=0;
2064: for (my $i=1;$i<=$number;$i++) {
2065: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2066: sprintf("%lx",int(100000*rand)).'-'.
2067: sprintf("%lx",int(100000*rand));
2068: $newkey=~s/1/g/g; # folks mix up 1 and l
2069: $newkey=~s/0/h/g; # and also 0 and O
2070: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2071: if ($existing{$newkey}) {
2072: $i--;
2073: } else {
2074: if (&put('accesskeys',
2075: { $newkey => '# generated '.localtime().
2076: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2077: '; '.$logentry },
2078: $cdom,$cnum) eq 'ok') {
2079: $total++;
2080: }
2081: }
2082: }
2083: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2084: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2085: return $total;
2086: }
2087:
2088: # ------------------------------------------------------- Validate an accesskey
2089:
2090: sub validate_access_key {
2091: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2092: $cdom=
2093: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2094: $cnum=
2095: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2096: $udom=$env{'user.domain'} unless (defined($udom));
2097: $uname=$env{'user.name'} unless (defined($uname));
2098: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2099: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2100: }
2101:
2102: # ------------------------------------- Find the section of student in a course
2103: sub devalidate_getsection_cache {
2104: my ($udom,$unam,$courseid)=@_;
2105: my $hashid="$udom:$unam:$courseid";
2106: &devalidate_cache_new('getsection',$hashid);
2107: }
2108:
2109: sub courseid_to_courseurl {
2110: my ($courseid) = @_;
2111: #already url style courseid
2112: return $courseid if ($courseid =~ m{^/});
2113:
2114: if (exists($env{'course.'.$courseid.'.num'})) {
2115: my $cnum = $env{'course.'.$courseid.'.num'};
2116: my $cdom = $env{'course.'.$courseid.'.domain'};
2117: return "/$cdom/$cnum";
2118: }
2119:
2120: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2121: if (exists($courseinfo{'num'})) {
2122: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2123: }
2124:
2125: return undef;
2126: }
2127:
2128: sub getsection {
2129: my ($udom,$unam,$courseid)=@_;
2130: my $cachetime=1800;
2131:
2132: my $hashid="$udom:$unam:$courseid";
2133: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2134: if (defined($cached)) { return $result; }
2135:
2136: my %Pending;
2137: my %Expired;
2138: #
2139: # Each role can either have not started yet (pending), be active,
2140: # or have expired.
2141: #
2142: # If there is an active role, we are done.
2143: #
2144: # If there is more than one role which has not started yet,
2145: # choose the one which will start sooner
2146: # If there is one role which has not started yet, return it.
2147: #
2148: # If there is more than one expired role, choose the one which ended last.
2149: # If there is a role which has expired, return it.
2150: #
2151: $courseid = &courseid_to_courseurl($courseid);
2152: my $extra = &freeze_escape({'skipcheck' => 1});
2153: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
2154: foreach my $key (keys(%roleshash)) {
2155: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2156: my $section=$1;
2157: if ($key eq $courseid.'_st') { $section=''; }
2158: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2159: my $now=time;
2160: if (defined($end) && $end && ($now > $end)) {
2161: $Expired{$end}=$section;
2162: next;
2163: }
2164: if (defined($start) && $start && ($now < $start)) {
2165: $Pending{$start}=$section;
2166: next;
2167: }
2168: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2169: }
2170: #
2171: # Presumedly there will be few matching roles from the above
2172: # loop and the sorting time will be negligible.
2173: if (scalar(keys(%Pending))) {
2174: my ($time) = sort {$a <=> $b} keys(%Pending);
2175: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2176: }
2177: if (scalar(keys(%Expired))) {
2178: my @sorted = sort {$a <=> $b} keys(%Expired);
2179: my $time = pop(@sorted);
2180: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2181: }
2182: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2183: }
2184:
2185: sub save_cache {
2186: &purge_remembered();
2187: #&Apache::loncommon::validate_page();
2188: undef(%env);
2189: undef($env_loaded);
2190: }
2191:
2192: my $to_remember=-1;
2193: my %remembered;
2194: my %accessed;
2195: my $kicks=0;
2196: my $hits=0;
2197: sub make_key {
2198: my ($name,$id) = @_;
2199: if (length($id) > 65
2200: && length(&escape($id)) > 200) {
2201: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2202: }
2203: return &escape($name.':'.$id);
2204: }
2205:
2206: sub devalidate_cache_new {
2207: my ($name,$id,$debug) = @_;
2208: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2209: $id=&make_key($name,$id);
2210: $memcache->delete($id);
2211: delete($remembered{$id});
2212: delete($accessed{$id});
2213: }
2214:
2215: sub is_cached_new {
2216: my ($name,$id,$debug) = @_;
2217: $id=&make_key($name,$id);
2218: if (exists($remembered{$id})) {
2219: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2220: $accessed{$id}=[&gettimeofday()];
2221: $hits++;
2222: return ($remembered{$id},1);
2223: }
2224: my $value = $memcache->get($id);
2225: if (!(defined($value))) {
2226: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2227: return (undef,undef);
2228: }
2229: if ($value eq '__undef__') {
2230: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2231: $value=undef;
2232: }
2233: &make_room($id,$value,$debug);
2234: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2235: return ($value,1);
2236: }
2237:
2238: sub do_cache_new {
2239: my ($name,$id,$value,$time,$debug) = @_;
2240: $id=&make_key($name,$id);
2241: my $setvalue=$value;
2242: if (!defined($setvalue)) {
2243: $setvalue='__undef__';
2244: }
2245: if (!defined($time) ) {
2246: $time=600;
2247: }
2248: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2249: my $result = $memcache->set($id,$setvalue,$time);
2250: if (! $result) {
2251: &logthis("caching of id -> $id failed");
2252: $memcache->disconnect_all();
2253: }
2254: # need to make a copy of $value
2255: &make_room($id,$value,$debug);
2256: return $value;
2257: }
2258:
2259: sub make_room {
2260: my ($id,$value,$debug)=@_;
2261:
2262: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2263: : $value;
2264: if ($to_remember<0) { return; }
2265: $accessed{$id}=[&gettimeofday()];
2266: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2267: my $to_kick;
2268: my $max_time=0;
2269: foreach my $other (keys(%accessed)) {
2270: if (&tv_interval($accessed{$other}) > $max_time) {
2271: $to_kick=$other;
2272: $max_time=&tv_interval($accessed{$other});
2273: }
2274: }
2275: delete($remembered{$to_kick});
2276: delete($accessed{$to_kick});
2277: $kicks++;
2278: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2279: return;
2280: }
2281:
2282: sub purge_remembered {
2283: #&logthis("Tossing ".scalar(keys(%remembered)));
2284: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2285: undef(%remembered);
2286: undef(%accessed);
2287: }
2288: # ------------------------------------- Read an entry from a user's environment
2289:
2290: sub userenvironment {
2291: my ($udom,$unam,@what)=@_;
2292: my $items;
2293: foreach my $item (@what) {
2294: $items.=&escape($item).'&';
2295: }
2296: $items=~s/\&$//;
2297: my %returnhash=();
2298: my $uhome = &homeserver($unam,$udom);
2299: unless ($uhome eq 'no_host') {
2300: my @answer=split(/\&/,
2301: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2302: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2303: return %returnhash;
2304: }
2305: my $i;
2306: for ($i=0;$i<=$#what;$i++) {
2307: $returnhash{$what[$i]}=&unescape($answer[$i]);
2308: }
2309: }
2310: return %returnhash;
2311: }
2312:
2313: # ---------------------------------------------------------- Get a studentphoto
2314: sub studentphoto {
2315: my ($udom,$unam,$ext) = @_;
2316: my $home=&Apache::lonnet::homeserver($unam,$udom);
2317: if (defined($env{'request.course.id'})) {
2318: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2319: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2320: return(&retrievestudentphoto($udom,$unam,$ext));
2321: } else {
2322: my ($result,$perm_reqd)=
2323: &Apache::lonnet::auto_photo_permission($unam,$udom);
2324: if ($result eq 'ok') {
2325: if (!($perm_reqd eq 'yes')) {
2326: return(&retrievestudentphoto($udom,$unam,$ext));
2327: }
2328: }
2329: }
2330: }
2331: } else {
2332: my ($result,$perm_reqd) =
2333: &Apache::lonnet::auto_photo_permission($unam,$udom);
2334: if ($result eq 'ok') {
2335: if (!($perm_reqd eq 'yes')) {
2336: return(&retrievestudentphoto($udom,$unam,$ext));
2337: }
2338: }
2339: }
2340: return '/adm/lonKaputt/lonlogo_broken.gif';
2341: }
2342:
2343: sub retrievestudentphoto {
2344: my ($udom,$unam,$ext,$type) = @_;
2345: my $home=&Apache::lonnet::homeserver($unam,$udom);
2346: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2347: if ($ret eq 'ok') {
2348: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2349: if ($type eq 'thumbnail') {
2350: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2351: }
2352: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2353: return $tokenurl;
2354: } else {
2355: if ($type eq 'thumbnail') {
2356: return '/adm/lonKaputt/genericstudent_tn.gif';
2357: } else {
2358: return '/adm/lonKaputt/lonlogo_broken.gif';
2359: }
2360: }
2361: }
2362:
2363: # -------------------------------------------------------------------- New chat
2364:
2365: sub chatsend {
2366: my ($newentry,$anon,$group)=@_;
2367: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2368: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2369: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2370: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2371: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2372: &escape($newentry)).':'.$group,$chome);
2373: }
2374:
2375: # ------------------------------------------ Find current version of a resource
2376:
2377: sub getversion {
2378: my $fname=&clutter(shift);
2379: unless ($fname=~/^\/res\//) { return -1; }
2380: return ¤tversion(&filelocation('',$fname));
2381: }
2382:
2383: sub currentversion {
2384: my $fname=shift;
2385: my $author=$fname;
2386: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2387: my ($udom,$uname)=split(/\//,$author);
2388: my $home=&homeserver($uname,$udom);
2389: if ($home eq 'no_host') {
2390: return -1;
2391: }
2392: my $answer=&reply("currentversion:$fname",$home);
2393: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2394: return -1;
2395: }
2396: return $answer;
2397: }
2398:
2399: #
2400: # Return special version number of resource if set by override, empty otherwise
2401: #
2402: sub usedversion {
2403: my $fname=shift;
2404: unless ($fname) { $fname=$env{'request.uri'}; }
2405: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2406: if ($urlversion) { return $urlversion; }
2407: return '';
2408: }
2409:
2410: # ----------------------------- Subscribe to a resource, return URL if possible
2411:
2412: sub subscribe {
2413: my $fname=shift;
2414: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2415: $fname=~s/[\n\r]//g;
2416: my $author=$fname;
2417: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2418: my ($udom,$uname)=split(/\//,$author);
2419: my $home=homeserver($uname,$udom);
2420: if ($home eq 'no_host') {
2421: return 'not_found';
2422: }
2423: my $answer=reply("sub:$fname",$home);
2424: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2425: $answer.=' by '.$home;
2426: }
2427: return $answer;
2428: }
2429:
2430: # -------------------------------------------------------------- Replicate file
2431:
2432: sub repcopy {
2433: my $filename=shift;
2434: $filename=~s/\/+/\//g;
2435: my $londocroot = $perlvar{'lonDocRoot'};
2436: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2437: if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
2438: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2439: $filename=~m{^/*(uploaded|editupload)/}) {
2440: return &repcopy_userfile($filename);
2441: }
2442: $filename=~s/[\n\r]//g;
2443: my $transname="$filename.in.transfer";
2444: # FIXME: this should flock
2445: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2446: my $remoteurl=subscribe($filename);
2447: if ($remoteurl =~ /^con_lost by/) {
2448: &logthis("Subscribe returned $remoteurl: $filename");
2449: return 'unavailable';
2450: } elsif ($remoteurl eq 'not_found') {
2451: #&logthis("Subscribe returned not_found: $filename");
2452: return 'not_found';
2453: } elsif ($remoteurl =~ /^rejected by/) {
2454: &logthis("Subscribe returned $remoteurl: $filename");
2455: return 'forbidden';
2456: } elsif ($remoteurl eq 'directory') {
2457: return 'ok';
2458: } else {
2459: my $author=$filename;
2460: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2461: my ($udom,$uname)=split(/\//,$author);
2462: my $home=homeserver($uname,$udom);
2463: unless ($home eq $perlvar{'lonHostID'}) {
2464: my @parts=split(/\//,$filename);
2465: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2466: if ($path ne "$londocroot/res") {
2467: &logthis("Malconfiguration for replication: $filename");
2468: return 'bad_request';
2469: }
2470: my $count;
2471: for ($count=5;$count<$#parts;$count++) {
2472: $path.="/$parts[$count]";
2473: if ((-e $path)!=1) {
2474: mkdir($path,0777);
2475: }
2476: }
2477: my $ua=new LWP::UserAgent;
2478: my $request=new HTTP::Request('GET',"$remoteurl");
2479: my $response=$ua->request($request,$transname);
2480: if ($response->is_error()) {
2481: unlink($transname);
2482: my $message=$response->status_line;
2483: &logthis("<font color=\"blue\">WARNING:"
2484: ." LWP get: $message: $filename</font>");
2485: return 'unavailable';
2486: } else {
2487: if ($remoteurl!~/\.meta$/) {
2488: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2489: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2490: if ($mresponse->is_error()) {
2491: unlink($filename.'.meta');
2492: &logthis(
2493: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2494: }
2495: }
2496: rename($transname,$filename);
2497: return 'ok';
2498: }
2499: }
2500: }
2501: }
2502:
2503: # ------------------------------------------------ Get server side include body
2504: sub ssi_body {
2505: my ($filelink,%form)=@_;
2506: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2507: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2508: }
2509: my $output='';
2510: my $response;
2511: if ($filelink=~/^https?\:/) {
2512: ($output,$response)=&externalssi($filelink);
2513: } else {
2514: $filelink .= $filelink=~/\?/ ? '&' : '?';
2515: $filelink .= 'inhibitmenu=yes';
2516: ($output,$response)=&ssi($filelink,%form);
2517: }
2518: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2519: $output=~s/^.*?\<body[^\>]*\>//si;
2520: $output=~s/\<\/body\s*\>.*?$//si;
2521: if (wantarray) {
2522: return ($output, $response);
2523: } else {
2524: return $output;
2525: }
2526: }
2527:
2528: # --------------------------------------------------------- Server Side Include
2529:
2530: sub absolute_url {
2531: my ($host_name) = @_;
2532: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2533: if ($host_name eq '') {
2534: $host_name = $ENV{'SERVER_NAME'};
2535: }
2536: return $protocol.$host_name;
2537: }
2538:
2539: #
2540: # Server side include.
2541: # Parameters:
2542: # fn Possibly encrypted resource name/id.
2543: # form Hash that describes how the rendering should be done
2544: # and other things.
2545: # Returns:
2546: # Scalar context: The content of the response.
2547: # Array context: 2 element list of the content and the full response object.
2548: #
2549: sub ssi {
2550:
2551: my ($fn,%form)=@_;
2552: my $ua=new LWP::UserAgent;
2553: my $request;
2554:
2555: $form{'no_update_last_known'}=1;
2556: &Apache::lonenc::check_encrypt(\$fn);
2557: if (%form) {
2558: $request=new HTTP::Request('POST',&absolute_url().$fn);
2559: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2560: } else {
2561: $request=new HTTP::Request('GET',&absolute_url().$fn);
2562: }
2563:
2564: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2565: my $response=$ua->request($request);
2566:
2567: if (wantarray) {
2568: return ($response->content, $response);
2569: } else {
2570: return $response->content;
2571: }
2572: }
2573:
2574: sub externalssi {
2575: my ($url)=@_;
2576: my $ua=new LWP::UserAgent;
2577: my $request=new HTTP::Request('GET',$url);
2578: my $response=$ua->request($request);
2579: if (wantarray) {
2580: return ($response->content, $response);
2581: } else {
2582: return $response->content;
2583: }
2584: }
2585:
2586: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2587:
2588: sub allowuploaded {
2589: my ($srcurl,$url)=@_;
2590: $url=&clutter(&declutter($url));
2591: my $dir=$url;
2592: $dir=~s/\/[^\/]+$//;
2593: my %httpref=();
2594: my $httpurl=&hreflocation('',$url);
2595: $httpref{'httpref.'.$httpurl}=$srcurl;
2596: &Apache::lonnet::appenv(\%httpref);
2597: }
2598:
2599: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2600: # input: action, courseID, current domain, intended
2601: # path to file, source of file, instruction to parse file for objects,
2602: # ref to hash for embedded objects,
2603: # ref to hash for codebase of java objects.
2604: # reference to scalar to accommodate mime type determined
2605: # from File::MMagic if $parser = parse.
2606: #
2607: # output: url to file (if action was uploaddoc),
2608: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2609: #
2610: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2611: # course.
2612: #
2613: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2614: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2615: # course's home server.
2616: #
2617: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2618: # be copied from $source (current location) to
2619: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2620: # and will then be copied to
2621: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2622: # course's home server.
2623: #
2624: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2625: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2626: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2627: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2628: # in course's home server.
2629: #
2630:
2631: sub process_coursefile {
2632: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2633: $mimetype)=@_;
2634: my $fetchresult;
2635: my $home=&homeserver($docuname,$docudom);
2636: if ($action eq 'propagate') {
2637: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2638: $home);
2639: } else {
2640: my $fpath = '';
2641: my $fname = $file;
2642: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2643: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2644: my $filepath = &build_filepath($fpath);
2645: if ($action eq 'copy') {
2646: if ($source eq '') {
2647: $fetchresult = 'no source file';
2648: return $fetchresult;
2649: } else {
2650: my $destination = $filepath.'/'.$fname;
2651: rename($source,$destination);
2652: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2653: $home);
2654: }
2655: } elsif ($action eq 'uploaddoc') {
2656: open(my $fh,'>'.$filepath.'/'.$fname);
2657: print $fh $env{'form.'.$source};
2658: close($fh);
2659: if ($parser eq 'parse') {
2660: my $mm = new File::MMagic;
2661: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2662: if ($type eq 'text/html') {
2663: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2664: unless ($parse_result eq 'ok') {
2665: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2666: }
2667: }
2668: if (ref($mimetype)) {
2669: $$mimetype = $type;
2670: }
2671: }
2672: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2673: $home);
2674: if ($fetchresult eq 'ok') {
2675: return '/uploaded/'.$fpath.'/'.$fname;
2676: } else {
2677: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2678: ' to host '.$home.': '.$fetchresult);
2679: return '/adm/notfound.html';
2680: }
2681: }
2682: }
2683: unless ( $fetchresult eq 'ok') {
2684: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2685: ' to host '.$home.': '.$fetchresult);
2686: }
2687: return $fetchresult;
2688: }
2689:
2690: sub build_filepath {
2691: my ($fpath) = @_;
2692: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2693: unless ($fpath eq '') {
2694: my @parts=split('/',$fpath);
2695: foreach my $part (@parts) {
2696: $filepath.= '/'.$part;
2697: if ((-e $filepath)!=1) {
2698: mkdir($filepath,0777);
2699: }
2700: }
2701: }
2702: return $filepath;
2703: }
2704:
2705: sub store_edited_file {
2706: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2707: my $file = $primary_url;
2708: $file =~ s#^/uploaded/$docudom/$docuname/##;
2709: my $fpath = '';
2710: my $fname = $file;
2711: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2712: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2713: my $filepath = &build_filepath($fpath);
2714: open(my $fh,'>'.$filepath.'/'.$fname);
2715: print $fh $content;
2716: close($fh);
2717: my $home=&homeserver($docuname,$docudom);
2718: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2719: $home);
2720: if ($$fetchresult eq 'ok') {
2721: return '/uploaded/'.$fpath.'/'.$fname;
2722: } else {
2723: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2724: ' to host '.$home.': '.$$fetchresult);
2725: return '/adm/notfound.html';
2726: }
2727: }
2728:
2729: sub clean_filename {
2730: my ($fname,$args)=@_;
2731: # Replace Windows backslashes by forward slashes
2732: $fname=~s/\\/\//g;
2733: if (!$args->{'keep_path'}) {
2734: # Get rid of everything but the actual filename
2735: $fname=~s/^.*\/([^\/]+)$/$1/;
2736: }
2737: # Replace spaces by underscores
2738: $fname=~s/\s+/\_/g;
2739: # Replace all other weird characters by nothing
2740: $fname=~s{[^/\w\.\-]}{}g;
2741: # Replace all .\d. sequences with _\d. so they no longer look like version
2742: # numbers
2743: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2744: return $fname;
2745: }
2746: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2747: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2748: # image with the same aspect ratio as the original, but with dimensions which do
2749: # not exceed $resizewidth and $resizeheight.
2750:
2751: sub resizeImage {
2752: my ($img_path,$resizewidth,$resizeheight) = @_;
2753: my $ima = Image::Magick->new;
2754: my $resized;
2755: if (-e $img_path) {
2756: $ima->Read($img_path);
2757: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2758: my $width = $ima->Get('width');
2759: my $height = $ima->Get('height');
2760: if ($width > $resizewidth) {
2761: my $factor = $width/$resizewidth;
2762: my $newheight = $height/$factor;
2763: $ima->Scale(width=>$resizewidth,height=>$newheight);
2764: $resized = 1;
2765: }
2766: }
2767: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2768: my $width = $ima->Get('width');
2769: my $height = $ima->Get('height');
2770: if ($height > $resizeheight) {
2771: my $factor = $height/$resizeheight;
2772: my $newwidth = $width/$factor;
2773: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2774: $resized = 1;
2775: }
2776: }
2777: if ($resized) {
2778: $ima->Write($img_path);
2779: }
2780: }
2781: return;
2782: }
2783:
2784: # --------------- Take an uploaded file and put it into the userfiles directory
2785: # input: $formname - the contents of the file are in $env{"form.$formname"}
2786: # the desired filename is in $env{"form.$formname.filename"}
2787: # $context - possible values: coursedoc, existingfile, overwrite,
2788: # canceloverwrite, or ''.
2789: # if 'coursedoc': upload to the current course
2790: # if 'existingfile': write file to tmp/overwrites directory
2791: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2792: # $context is passed as argument to &finishuserfileupload
2793: # $subdir - directory in userfile to store the file into
2794: # $parser - instruction to parse file for objects ($parser = parse)
2795: # $allfiles - reference to hash for embedded objects
2796: # $codebase - reference to hash for codebase of java objects
2797: # $desuname - username for permanent storage of uploaded file
2798: # $dsetudom - domain for permanaent storage of uploaded file
2799: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2800: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2801: # $resizewidth - width (pixels) to which to resize uploaded image
2802: # $resizeheight - height (pixels) to which to resize uploaded image
2803: # $mimetype - reference to scalar to accommodate mime type determined
2804: # from File::MMagic.
2805: #
2806: # output: url of file in userspace, or error: <message>
2807: # or /adm/notfound.html if failure to upload occurse
2808:
2809: sub userfileupload {
2810: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2811: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2812: if (!defined($subdir)) { $subdir='unknown'; }
2813: my $fname=$env{'form.'.$formname.'.filename'};
2814: $fname=&clean_filename($fname);
2815: # See if there is anything left
2816: unless ($fname) { return 'error: no uploaded file'; }
2817: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2818: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2819: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2820: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2821: my $now = time;
2822: my $filepath;
2823: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2824: $filepath = 'tmp/helprequests/'.$now;
2825: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2826: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2827: '_'.$env{'user.domain'}.'/pending';
2828: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2829: my ($docuname,$docudom);
2830: if ($destudom) {
2831: $docudom = $destudom;
2832: } else {
2833: $docudom = $env{'user.domain'};
2834: }
2835: if ($destuname) {
2836: $docuname = $destuname;
2837: } else {
2838: $docuname = $env{'user.name'};
2839: }
2840: if (exists($env{'form.group'})) {
2841: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2842: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2843: }
2844: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2845: if ($context eq 'canceloverwrite') {
2846: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2847: if (-e $tempfile) {
2848: my @info = stat($tempfile);
2849: if ($info[9] eq $env{'form.timestamp'}) {
2850: unlink($tempfile);
2851: }
2852: }
2853: return;
2854: }
2855: }
2856: # Create the directory if not present
2857: my @parts=split(/\//,$filepath);
2858: my $fullpath = $perlvar{'lonDaemons'};
2859: for (my $i=0;$i<@parts;$i++) {
2860: $fullpath .= '/'.$parts[$i];
2861: if ((-e $fullpath)!=1) {
2862: mkdir($fullpath,0777);
2863: }
2864: }
2865: open(my $fh,'>'.$fullpath.'/'.$fname);
2866: print $fh $env{'form.'.$formname};
2867: close($fh);
2868: if ($context eq 'existingfile') {
2869: my @info = stat($fullpath.'/'.$fname);
2870: return ($fullpath.'/'.$fname,$info[9]);
2871: } else {
2872: return $fullpath.'/'.$fname;
2873: }
2874: }
2875: if ($subdir eq 'scantron') {
2876: $fname = 'scantron_orig_'.$fname;
2877: } else {
2878: $fname="$subdir/$fname";
2879: }
2880: if ($context eq 'coursedoc') {
2881: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2882: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2883: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2884: return &finishuserfileupload($docuname,$docudom,
2885: $formname,$fname,$parser,$allfiles,
2886: $codebase,$thumbwidth,$thumbheight,
2887: $resizewidth,$resizeheight,$context,$mimetype);
2888: } else {
2889: $fname=$env{'form.folder'}.'/'.$fname;
2890: return &process_coursefile('uploaddoc',$docuname,$docudom,
2891: $fname,$formname,$parser,
2892: $allfiles,$codebase,$mimetype);
2893: }
2894: } elsif (defined($destuname)) {
2895: my $docuname=$destuname;
2896: my $docudom=$destudom;
2897: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2898: $parser,$allfiles,$codebase,
2899: $thumbwidth,$thumbheight,
2900: $resizewidth,$resizeheight,$context,$mimetype);
2901: } else {
2902: my $docuname=$env{'user.name'};
2903: my $docudom=$env{'user.domain'};
2904: if (exists($env{'form.group'})) {
2905: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2906: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2907: }
2908: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2909: $parser,$allfiles,$codebase,
2910: $thumbwidth,$thumbheight,
2911: $resizewidth,$resizeheight,$context,$mimetype);
2912: }
2913: }
2914:
2915: sub finishuserfileupload {
2916: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2917: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2918: my $path=$docudom.'/'.$docuname.'/';
2919: my $filepath=$perlvar{'lonDocRoot'};
2920:
2921: my ($fnamepath,$file,$fetchthumb);
2922: $file=$fname;
2923: if ($fname=~m|/|) {
2924: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2925: $path.=$fnamepath.'/';
2926: }
2927: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2928: my $count;
2929: for ($count=4;$count<=$#parts;$count++) {
2930: $filepath.="/$parts[$count]";
2931: if ((-e $filepath)!=1) {
2932: mkdir($filepath,0777);
2933: }
2934: }
2935:
2936: # Save the file
2937: {
2938: if (!open(FH,'>'.$filepath.'/'.$file)) {
2939: &logthis('Failed to create '.$filepath.'/'.$file);
2940: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2941: return '/adm/notfound.html';
2942: }
2943: if ($context eq 'overwrite') {
2944: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2945: my $target = $filepath.'/'.$file;
2946: if (-e $source) {
2947: my @info = stat($source);
2948: if ($info[9] eq $env{'form.timestamp'}) {
2949: unless (&File::Copy::move($source,$target)) {
2950: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2951: return "Moving from $source failed";
2952: }
2953: } else {
2954: return "Temporary file: $source had unexpected date/time for last modification";
2955: }
2956: } else {
2957: return "Temporary file: $source missing";
2958: }
2959: } elsif (!print FH ($env{'form.'.$formname})) {
2960: &logthis('Failed to write to '.$filepath.'/'.$file);
2961: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2962: return '/adm/notfound.html';
2963: }
2964: close(FH);
2965: if ($resizewidth && $resizeheight) {
2966: my $mm = new File::MMagic;
2967: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2968: if ($mime_type =~ m{^image/}) {
2969: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2970: }
2971: }
2972: }
2973: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2974: if (ref($mimetype)) {
2975: if ($$mimetype eq '') {
2976: my $mm = new File::MMagic;
2977: my $type = $mm->checktype_filename($filepath.'/'.$file);
2978: $$mimetype = $type;
2979: }
2980: }
2981: }
2982: if ($parser eq 'parse') {
2983: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
2984: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2985: $allfiles,$codebase);
2986: unless ($parse_result eq 'ok') {
2987: &logthis('Failed to parse '.$filepath.$file.
2988: ' for embedded media: '.$parse_result);
2989: }
2990: }
2991: }
2992: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2993: my $input = $filepath.'/'.$file;
2994: my $output = $filepath.'/'.'tn-'.$file;
2995: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2996: system("convert -sample $thumbsize $input $output");
2997: if (-e $filepath.'/'.'tn-'.$file) {
2998: $fetchthumb = 1;
2999: }
3000: }
3001:
3002: # Notify homeserver to grep it
3003: #
3004: my $docuhome=&homeserver($docuname,$docudom);
3005: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3006: if ($fetchresult eq 'ok') {
3007: if ($fetchthumb) {
3008: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3009: if ($thumbresult ne 'ok') {
3010: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3011: $docuhome.': '.$thumbresult);
3012: }
3013: }
3014: #
3015: # Return the URL to it
3016: return '/uploaded/'.$path.$file;
3017: } else {
3018: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3019: ': '.$fetchresult);
3020: return '/adm/notfound.html';
3021: }
3022: }
3023:
3024: sub extract_embedded_items {
3025: my ($fullpath,$allfiles,$codebase,$content) = @_;
3026: my @state = ();
3027: my %javafiles = (
3028: codebase => '',
3029: code => '',
3030: archive => ''
3031: );
3032: my %mediafiles = (
3033: src => '',
3034: movie => '',
3035: );
3036: my $p;
3037: if ($content) {
3038: $p = HTML::LCParser->new($content);
3039: } else {
3040: $p = HTML::LCParser->new($fullpath);
3041: }
3042: while (my $t=$p->get_token()) {
3043: if ($t->[0] eq 'S') {
3044: my ($tagname, $attr) = ($t->[1],$t->[2]);
3045: push(@state, $tagname);
3046: if (lc($tagname) eq 'allow') {
3047: &add_filetype($allfiles,$attr->{'src'},'src');
3048: }
3049: if (lc($tagname) eq 'img') {
3050: &add_filetype($allfiles,$attr->{'src'},'src');
3051: }
3052: if (lc($tagname) eq 'a') {
3053: &add_filetype($allfiles,$attr->{'href'},'href');
3054: }
3055: if (lc($tagname) eq 'script') {
3056: if ($attr->{'archive'} =~ /\.jar$/i) {
3057: &add_filetype($allfiles,$attr->{'archive'},'archive');
3058: } else {
3059: &add_filetype($allfiles,$attr->{'src'},'src');
3060: }
3061: }
3062: if (lc($tagname) eq 'link') {
3063: if (lc($attr->{'rel'}) eq 'stylesheet') {
3064: &add_filetype($allfiles,$attr->{'href'},'href');
3065: }
3066: }
3067: if (lc($tagname) eq 'object' ||
3068: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3069: foreach my $item (keys(%javafiles)) {
3070: $javafiles{$item} = '';
3071: }
3072: }
3073: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3074: my $name = lc($attr->{'name'});
3075: foreach my $item (keys(%javafiles)) {
3076: if ($name eq $item) {
3077: $javafiles{$item} = $attr->{'value'};
3078: last;
3079: }
3080: }
3081: foreach my $item (keys(%mediafiles)) {
3082: if ($name eq $item) {
3083: &add_filetype($allfiles, $attr->{'value'}, 'value');
3084: last;
3085: }
3086: }
3087: }
3088: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3089: foreach my $item (keys(%javafiles)) {
3090: if ($attr->{$item}) {
3091: $javafiles{$item} = $attr->{$item};
3092: last;
3093: }
3094: }
3095: foreach my $item (keys(%mediafiles)) {
3096: if ($attr->{$item}) {
3097: &add_filetype($allfiles,$attr->{$item},$item);
3098: last;
3099: }
3100: }
3101: }
3102: } elsif ($t->[0] eq 'E') {
3103: my ($tagname) = ($t->[1]);
3104: if ($javafiles{'codebase'} ne '') {
3105: $javafiles{'codebase'} .= '/';
3106: }
3107: if (lc($tagname) eq 'applet' ||
3108: lc($tagname) eq 'object' ||
3109: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3110: ) {
3111: foreach my $item (keys(%javafiles)) {
3112: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3113: my $file=$javafiles{'codebase'}.$javafiles{$item};
3114: &add_filetype($allfiles,$file,$item);
3115: }
3116: }
3117: }
3118: pop @state;
3119: }
3120: }
3121: return 'ok';
3122: }
3123:
3124: sub add_filetype {
3125: my ($allfiles,$file,$type)=@_;
3126: if (exists($allfiles->{$file})) {
3127: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3128: push(@{$allfiles->{$file}}, &escape($type));
3129: }
3130: } else {
3131: @{$allfiles->{$file}} = (&escape($type));
3132: }
3133: }
3134:
3135: sub removeuploadedurl {
3136: my ($url)=@_;
3137: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3138: return &removeuserfile($uname,$udom,$fname);
3139: }
3140:
3141: sub removeuserfile {
3142: my ($docuname,$docudom,$fname)=@_;
3143: my $home=&homeserver($docuname,$docudom);
3144: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3145: if ($result eq 'ok') {
3146: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3147: my $metafile = $fname.'.meta';
3148: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3149: my $url = "/uploaded/$docudom/$docuname/$fname";
3150: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3151: my $sqlresult =
3152: &update_portfolio_table($docuname,$docudom,$file,
3153: 'portfolio_metadata',$group,
3154: 'delete');
3155: }
3156: }
3157: return $result;
3158: }
3159:
3160: sub mkdiruserfile {
3161: my ($docuname,$docudom,$dir)=@_;
3162: my $home=&homeserver($docuname,$docudom);
3163: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3164: }
3165:
3166: sub renameuserfile {
3167: my ($docuname,$docudom,$old,$new)=@_;
3168: my $home=&homeserver($docuname,$docudom);
3169: my $result = &reply("renameuserfile:$docudom:$docuname:".
3170: &escape("$old").':'.&escape("$new"),$home);
3171: if ($result eq 'ok') {
3172: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3173: my $oldmeta = $old.'.meta';
3174: my $newmeta = $new.'.meta';
3175: my $metaresult =
3176: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3177: my $url = "/uploaded/$docudom/$docuname/$old";
3178: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3179: my $sqlresult =
3180: &update_portfolio_table($docuname,$docudom,$file,
3181: 'portfolio_metadata',$group,
3182: 'delete');
3183: }
3184: }
3185: return $result;
3186: }
3187:
3188: # ------------------------------------------------------------------------- Log
3189:
3190: sub log {
3191: my ($dom,$nam,$hom,$what)=@_;
3192: return critical("log:$dom:$nam:$what",$hom);
3193: }
3194:
3195: # ------------------------------------------------------------------ Course Log
3196: #
3197: # This routine flushes several buffers of non-mission-critical nature
3198: #
3199:
3200: sub flushcourselogs {
3201: &logthis('Flushing log buffers');
3202: #
3203: # course logs
3204: # This is a log of all transactions in a course, which can be used
3205: # for data mining purposes
3206: #
3207: # It also collects the courseid database, which lists last transaction
3208: # times and course titles for all courseids
3209: #
3210: my %courseidbuffer=();
3211: foreach my $crsid (keys(%courselogs)) {
3212: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3213: &escape($courselogs{$crsid}),
3214: $coursehombuf{$crsid}) eq 'ok') {
3215: delete $courselogs{$crsid};
3216: } else {
3217: &logthis('Failed to flush log buffer for '.$crsid);
3218: if (length($courselogs{$crsid})>40000) {
3219: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3220: " exceeded maximum size, deleting.</font>");
3221: delete $courselogs{$crsid};
3222: }
3223: }
3224: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3225: 'description' => $coursedescrbuf{$crsid},
3226: 'inst_code' => $courseinstcodebuf{$crsid},
3227: 'type' => $coursetypebuf{$crsid},
3228: 'owner' => $courseownerbuf{$crsid},
3229: };
3230: }
3231: #
3232: # Write course id database (reverse lookup) to homeserver of courses
3233: # Is used in pickcourse
3234: #
3235: foreach my $crs_home (keys(%courseidbuffer)) {
3236: my $response = &courseidput(&host_domain($crs_home),
3237: $courseidbuffer{$crs_home},
3238: $crs_home,'timeonly');
3239: }
3240: #
3241: # File accesses
3242: # Writes to the dynamic metadata of resources to get hit counts, etc.
3243: #
3244: foreach my $entry (keys(%accesshash)) {
3245: if ($entry =~ /___count$/) {
3246: my ($dom,$name);
3247: ($dom,$name,undef)=
3248: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3249: if (! defined($dom) || $dom eq '' ||
3250: ! defined($name) || $name eq '') {
3251: my $cid = $env{'request.course.id'};
3252: $dom = $env{'request.'.$cid.'.domain'};
3253: $name = $env{'request.'.$cid.'.num'};
3254: }
3255: my $value = $accesshash{$entry};
3256: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3257: my %temphash=($url => $value);
3258: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3259: if ($result eq 'ok') {
3260: delete $accesshash{$entry};
3261: } elsif ($result eq 'unknown_cmd') {
3262: # Target server has old code running on it.
3263: my %temphash=($entry => $value);
3264: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3265: delete $accesshash{$entry};
3266: }
3267: }
3268: } else {
3269: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3270: my %temphash=($entry => $accesshash{$entry});
3271: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3272: delete $accesshash{$entry};
3273: }
3274: }
3275: }
3276: #
3277: # Roles
3278: # Reverse lookup of user roles for course faculty/staff and co-authorship
3279: #
3280: foreach my $entry (keys(%userrolehash)) {
3281: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3282: split(/\:/,$entry);
3283: if (&Apache::lonnet::put('nohist_userroles',
3284: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3285: $rudom,$runame) eq 'ok') {
3286: delete $userrolehash{$entry};
3287: }
3288: }
3289: #
3290: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3291: #
3292: my %domrolebuffer = ();
3293: foreach my $entry (keys(%domainrolehash)) {
3294: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3295: if ($domrolebuffer{$rudom}) {
3296: $domrolebuffer{$rudom}.='&'.&escape($entry).
3297: '='.&escape($domainrolehash{$entry});
3298: } else {
3299: $domrolebuffer{$rudom}.=&escape($entry).
3300: '='.&escape($domainrolehash{$entry});
3301: }
3302: delete $domainrolehash{$entry};
3303: }
3304: foreach my $dom (keys(%domrolebuffer)) {
3305: my %servers = &get_servers($dom,'library');
3306: foreach my $tryserver (keys(%servers)) {
3307: unless (&reply('domroleput:'.$dom.':'.
3308: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3309: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3310: }
3311: }
3312: }
3313: $dumpcount++;
3314: }
3315:
3316: sub courselog {
3317: my $what=shift;
3318: $what=time.':'.$what;
3319: unless ($env{'request.course.id'}) { return ''; }
3320: $coursedombuf{$env{'request.course.id'}}=
3321: $env{'course.'.$env{'request.course.id'}.'.domain'};
3322: $coursenumbuf{$env{'request.course.id'}}=
3323: $env{'course.'.$env{'request.course.id'}.'.num'};
3324: $coursehombuf{$env{'request.course.id'}}=
3325: $env{'course.'.$env{'request.course.id'}.'.home'};
3326: $coursedescrbuf{$env{'request.course.id'}}=
3327: $env{'course.'.$env{'request.course.id'}.'.description'};
3328: $courseinstcodebuf{$env{'request.course.id'}}=
3329: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3330: $courseownerbuf{$env{'request.course.id'}}=
3331: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3332: $coursetypebuf{$env{'request.course.id'}}=
3333: $env{'course.'.$env{'request.course.id'}.'.type'};
3334: if (defined $courselogs{$env{'request.course.id'}}) {
3335: $courselogs{$env{'request.course.id'}}.='&'.$what;
3336: } else {
3337: $courselogs{$env{'request.course.id'}}.=$what;
3338: }
3339: if (length($courselogs{$env{'request.course.id'}})>4048) {
3340: &flushcourselogs();
3341: }
3342: }
3343:
3344: sub courseacclog {
3345: my $fnsymb=shift;
3346: unless ($env{'request.course.id'}) { return ''; }
3347: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3348: if ($fnsymb=~/$LONCAPA::assess_re/) {
3349: $what.=':POST';
3350: # FIXME: Probably ought to escape things....
3351: foreach my $key (keys(%env)) {
3352: if ($key=~/^form\.(.*)/) {
3353: my $formitem = $1;
3354: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3355: $what.=':'.$formitem.'='.$env{$key};
3356: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3357: $what.=':'.$formitem.'='.$env{$key};
3358: }
3359: }
3360: }
3361: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3362: # FIXME: We should not be depending on a form parameter that someone
3363: # editing lonsearchcat.pm might change in the future.
3364: if ($env{'form.phase'} eq 'course_search') {
3365: $what.= ':POST';
3366: # FIXME: Probably ought to escape things....
3367: foreach my $element ('courseexp','crsfulltext','crsrelated',
3368: 'crsdiscuss') {
3369: $what.=':'.$element.'='.$env{'form.'.$element};
3370: }
3371: }
3372: }
3373: &courselog($what);
3374: }
3375:
3376: sub countacc {
3377: my $url=&declutter(shift);
3378: return if (! defined($url) || $url eq '');
3379: unless ($env{'request.course.id'}) { return ''; }
3380: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3381: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3382: $accesshash{$key}++;
3383: }
3384:
3385: sub linklog {
3386: my ($from,$to)=@_;
3387: $from=&declutter($from);
3388: $to=&declutter($to);
3389: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3390: $accesshash{$to.'___'.$from.'___goto'}=1;
3391: }
3392:
3393: sub userrolelog {
3394: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3395: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
3396: ($trole=~/^in/) || ($trole=~/^cc/) ||
3397: ($trole=~/^ep/) || ($trole=~/^cr/) ||
3398: ($trole=~/^ta/) || ($trole=~/^co/)) {
3399: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3400: $userrolehash
3401: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3402: =$tend.':'.$tstart;
3403: }
3404: if (($env{'request.role'} =~ /dc\./) &&
3405: (($trole=~/^au/) || ($trole=~/^in/) ||
3406: ($trole=~/^cc/) || ($trole=~/^ep/) ||
3407: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3408: ($trole=~/^co/))) {
3409: $userrolehash
3410: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3411: =$tend.':'.$tstart;
3412: }
3413: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3414: ($trole=~/^li/) || ($trole=~/^li/) ||
3415: ($trole=~/^au/) || ($trole=~/^dg/) ||
3416: ($trole=~/^sc/)) {
3417: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3418: $domainrolehash
3419: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3420: = $tend.':'.$tstart;
3421: }
3422: }
3423:
3424: sub courserolelog {
3425: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3426: if (($trole eq 'cc') || ($trole eq 'in') ||
3427: ($trole eq 'ep') || ($trole eq 'ad') ||
3428: ($trole eq 'ta') || ($trole eq 'st') ||
3429: ($trole=~/^cr/) || ($trole eq 'gr') ||
3430: ($trole eq 'co')) {
3431: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3432: my $cdom = $1;
3433: my $cnum = $2;
3434: my $sec = $3;
3435: my $namespace = 'rolelog';
3436: my %storehash = (
3437: role => $trole,
3438: start => $tstart,
3439: end => $tend,
3440: selfenroll => $selfenroll,
3441: context => $context,
3442: );
3443: if ($trole eq 'gr') {
3444: $namespace = 'groupslog';
3445: $storehash{'group'} = $sec;
3446: } else {
3447: $storehash{'section'} = $sec;
3448: }
3449: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3450: if (($trole ne 'st') || ($sec ne '')) {
3451: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3452: }
3453: }
3454: }
3455: return;
3456: }
3457:
3458: sub get_course_adv_roles {
3459: my ($cid,$codes) = @_;
3460: $cid=$env{'request.course.id'} unless (defined($cid));
3461: my %coursehash=&coursedescription($cid);
3462: my $crstype = &Apache::loncommon::course_type($cid);
3463: my %nothide=();
3464: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3465: if ($user !~ /:/) {
3466: $nothide{join(':',split(/[\@]/,$user))}=1;
3467: } else {
3468: $nothide{$user}=1;
3469: }
3470: }
3471: my %returnhash=();
3472: my %dumphash=
3473: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3474: my $now=time;
3475: my %privileged;
3476: foreach my $entry (keys(%dumphash)) {
3477: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3478: if (($tstart) && ($tstart<0)) { next; }
3479: if (($tend) && ($tend<$now)) { next; }
3480: if (($tstart) && ($now<$tstart)) { next; }
3481: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3482: if ($username eq '' || $domain eq '') { next; }
3483: unless (ref($privileged{$domain}) eq 'HASH') {
3484: my %dompersonnel =
3485: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3486: $privileged{$domain} = {};
3487: foreach my $server (keys(%dompersonnel)) {
3488: if (ref($dompersonnel{$server}) eq 'HASH') {
3489: foreach my $user (keys(%{$dompersonnel{$server}})) {
3490: my ($trole,$uname,$udom) = split(/:/,$user);
3491: $privileged{$udom}{$uname} = 1;
3492: }
3493: }
3494: }
3495: }
3496: if ((exists($privileged{$domain}{$username})) &&
3497: (!$nothide{$username.':'.$domain})) { next; }
3498: if ($role eq 'cr') { next; }
3499: if ($codes) {
3500: if ($section) { $role .= ':'.$section; }
3501: if ($returnhash{$role}) {
3502: $returnhash{$role}.=','.$username.':'.$domain;
3503: } else {
3504: $returnhash{$role}=$username.':'.$domain;
3505: }
3506: } else {
3507: my $key=&plaintext($role,$crstype);
3508: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3509: if ($returnhash{$key}) {
3510: $returnhash{$key}.=','.$username.':'.$domain;
3511: } else {
3512: $returnhash{$key}=$username.':'.$domain;
3513: }
3514: }
3515: }
3516: return %returnhash;
3517: }
3518:
3519: sub get_my_roles {
3520: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3521: unless (defined($uname)) { $uname=$env{'user.name'}; }
3522: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3523: my (%dumphash,%nothide);
3524: if ($context eq 'userroles') {
3525: my $extra = &freeze_escape({'skipcheck' => 1});
3526: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
3527: } else {
3528: %dumphash=
3529: &dump('nohist_userroles',$udom,$uname);
3530: if ($hidepriv) {
3531: my %coursehash=&coursedescription($udom.'_'.$uname);
3532: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3533: if ($user !~ /:/) {
3534: $nothide{join(':',split(/[\@]/,$user))} = 1;
3535: } else {
3536: $nothide{$user} = 1;
3537: }
3538: }
3539: }
3540: }
3541: my %returnhash=();
3542: my $now=time;
3543: my %privileged;
3544: foreach my $entry (keys(%dumphash)) {
3545: my ($role,$tend,$tstart);
3546: if ($context eq 'userroles') {
3547: next if ($entry =~ /^rolesdef/);
3548: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3549: } else {
3550: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3551: }
3552: if (($tstart) && ($tstart<0)) { next; }
3553: my $status = 'active';
3554: if (($tend) && ($tend<=$now)) {
3555: $status = 'previous';
3556: }
3557: if (($tstart) && ($now<$tstart)) {
3558: $status = 'future';
3559: }
3560: if (ref($types) eq 'ARRAY') {
3561: if (!grep(/^\Q$status\E$/,@{$types})) {
3562: next;
3563: }
3564: } else {
3565: if ($status ne 'active') {
3566: next;
3567: }
3568: }
3569: my ($rolecode,$username,$domain,$section,$area);
3570: if ($context eq 'userroles') {
3571: ($area,$rolecode) = split(/_/,$entry);
3572: (undef,$domain,$username,$section) = split(/\//,$area);
3573: } else {
3574: ($role,$username,$domain,$section) = split(/\:/,$entry);
3575: }
3576: if (ref($roledoms) eq 'ARRAY') {
3577: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3578: next;
3579: }
3580: }
3581: if (ref($roles) eq 'ARRAY') {
3582: if (!grep(/^\Q$role\E$/,@{$roles})) {
3583: if ($role =~ /^cr\//) {
3584: if (!grep(/^cr$/,@{$roles})) {
3585: next;
3586: }
3587: } elsif ($role =~ /^gr\//) {
3588: if (!grep(/^gr$/,@{$roles})) {
3589: next;
3590: }
3591: } else {
3592: next;
3593: }
3594: }
3595: }
3596: if ($hidepriv) {
3597: if ($context eq 'userroles') {
3598: if ((&privileged($username,$domain)) &&
3599: (!$nothide{$username.':'.$domain})) {
3600: next;
3601: }
3602: } else {
3603: unless (ref($privileged{$domain}) eq 'HASH') {
3604: my %dompersonnel =
3605: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3606: $privileged{$domain} = {};
3607: if (keys(%dompersonnel)) {
3608: foreach my $server (keys(%dompersonnel)) {
3609: if (ref($dompersonnel{$server}) eq 'HASH') {
3610: foreach my $user (keys(%{$dompersonnel{$server}})) {
3611: my ($trole,$uname,$udom) = split(/:/,$user);
3612: $privileged{$udom}{$uname} = $trole;
3613: }
3614: }
3615: }
3616: }
3617: }
3618: if (exists($privileged{$domain}{$username})) {
3619: if (!$nothide{$username.':'.$domain}) {
3620: next;
3621: }
3622: }
3623: }
3624: }
3625: if ($withsec) {
3626: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3627: $tstart.':'.$tend;
3628: } else {
3629: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3630: }
3631: }
3632: return %returnhash;
3633: }
3634:
3635: # ----------------------------------------------------- Frontpage Announcements
3636: #
3637: #
3638:
3639: sub postannounce {
3640: my ($server,$text)=@_;
3641: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3642: unless ($text=~/\w/) { $text=''; }
3643: return &reply('setannounce:'.&escape($text),$server);
3644: }
3645:
3646: sub getannounce {
3647:
3648: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3649: my $announcement='';
3650: while (my $line = <$fh>) { $announcement .= $line; }
3651: close($fh);
3652: if ($announcement=~/\w/) {
3653: return
3654: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3655: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3656: } else {
3657: return '';
3658: }
3659: } else {
3660: return '';
3661: }
3662: }
3663:
3664: # ---------------------------------------------------------- Course ID routines
3665: # Deal with domain's nohist_courseid.db files
3666: #
3667:
3668: sub courseidput {
3669: my ($domain,$storehash,$coursehome,$caller) = @_;
3670: return unless (ref($storehash) eq 'HASH');
3671: my $outcome;
3672: if ($caller eq 'timeonly') {
3673: my $cids = '';
3674: foreach my $item (keys(%$storehash)) {
3675: $cids.=&escape($item).'&';
3676: }
3677: $cids=~s/\&$//;
3678: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3679: $coursehome);
3680: } else {
3681: my $items = '';
3682: foreach my $item (keys(%$storehash)) {
3683: $items.= &escape($item).'='.
3684: &freeze_escape($$storehash{$item}).'&';
3685: }
3686: $items=~s/\&$//;
3687: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3688: $coursehome);
3689: }
3690: if ($outcome eq 'unknown_cmd') {
3691: my $what;
3692: foreach my $cid (keys(%$storehash)) {
3693: $what .= &escape($cid).'=';
3694: foreach my $item ('description','inst_code','owner','type') {
3695: $what .= &escape($storehash->{$cid}{$item}).':';
3696: }
3697: $what =~ s/\:$/&/;
3698: }
3699: $what =~ s/\&$//;
3700: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3701: } else {
3702: return $outcome;
3703: }
3704: }
3705:
3706: sub courseiddump {
3707: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3708: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3709: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3710: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3711: my $as_hash = 1;
3712: my %returnhash;
3713: if (!$domfilter) { $domfilter=''; }
3714: my %libserv = &all_library();
3715: foreach my $tryserver (keys(%libserv)) {
3716: if ( ( $hostidflag == 1
3717: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3718: || (!defined($hostidflag)) ) {
3719:
3720: if (($domfilter eq '') ||
3721: (&host_domain($tryserver) eq $domfilter)) {
3722: my $rep =
3723: &reply('courseiddump:'.&host_domain($tryserver).':'.
3724: $sincefilter.':'.&escape($descfilter).':'.
3725: &escape($instcodefilter).':'.&escape($ownerfilter).
3726: ':'.&escape($coursefilter).':'.&escape($typefilter).
3727: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3728: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3729: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3730: &escape($cc_clone).':'.$cloneonly.':'.
3731: &escape($createdbefore).':'.&escape($createdafter).':'.
3732: &escape($creationcontext).':'.$domcloner,
3733: $tryserver);
3734: my @pairs=split(/\&/,$rep);
3735: foreach my $item (@pairs) {
3736: my ($key,$value)=split(/\=/,$item,2);
3737: $key = &unescape($key);
3738: next if ($key =~ /^error: 2 /);
3739: my $result = &thaw_unescape($value);
3740: if (ref($result) eq 'HASH') {
3741: $returnhash{$key}=$result;
3742: } else {
3743: my @responses = split(/:/,$value);
3744: my @items = ('description','inst_code','owner','type');
3745: for (my $i=0; $i<@responses; $i++) {
3746: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3747: }
3748: }
3749: }
3750: }
3751: }
3752: }
3753: return %returnhash;
3754: }
3755:
3756: sub courselastaccess {
3757: my ($cdom,$cnum,$hostidref) = @_;
3758: my %returnhash;
3759: if ($cdom && $cnum) {
3760: my $chome = &homeserver($cnum,$cdom);
3761: if ($chome ne 'no_host') {
3762: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3763: &extract_lastaccess(\%returnhash,$rep);
3764: }
3765: } else {
3766: if (!$cdom) { $cdom=''; }
3767: my %libserv = &all_library();
3768: foreach my $tryserver (keys(%libserv)) {
3769: if (ref($hostidref) eq 'ARRAY') {
3770: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3771: }
3772: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3773: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3774: &extract_lastaccess(\%returnhash,$rep);
3775: }
3776: }
3777: }
3778: return %returnhash;
3779: }
3780:
3781: sub extract_lastaccess {
3782: my ($returnhash,$rep) = @_;
3783: if (ref($returnhash) eq 'HASH') {
3784: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3785: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3786: $rep eq '') {
3787: my @pairs=split(/\&/,$rep);
3788: foreach my $item (@pairs) {
3789: my ($key,$value)=split(/\=/,$item,2);
3790: $key = &unescape($key);
3791: next if ($key =~ /^error: 2 /);
3792: $returnhash->{$key} = &thaw_unescape($value);
3793: }
3794: }
3795: }
3796: return;
3797: }
3798:
3799: # ---------------------------------------------------------- DC e-mail
3800:
3801: sub dcmailput {
3802: my ($domain,$msgid,$message,$server)=@_;
3803: my $status = &Apache::lonnet::critical(
3804: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3805: &escape($message),$server);
3806: return $status;
3807: }
3808:
3809: sub dcmaildump {
3810: my ($dom,$startdate,$enddate,$senders) = @_;
3811: my %returnhash=();
3812:
3813: if (defined(&domain($dom,'primary'))) {
3814: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3815: &escape($enddate).':';
3816: my @esc_senders=map { &escape($_)} @$senders;
3817: $cmd.=&escape(join('&',@esc_senders));
3818: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3819: my ($key,$value) = split(/\=/,$line,2);
3820: if (($key) && ($value)) {
3821: $returnhash{&unescape($key)} = &unescape($value);
3822: }
3823: }
3824: }
3825: return %returnhash;
3826: }
3827: # ---------------------------------------------------------- Domain roles
3828:
3829: sub get_domain_roles {
3830: my ($dom,$roles,$startdate,$enddate)=@_;
3831: if ((!defined($startdate)) || ($startdate eq '')) {
3832: $startdate = '.';
3833: }
3834: if ((!defined($enddate)) || ($enddate eq '')) {
3835: $enddate = '.';
3836: }
3837: my $rolelist;
3838: if (ref($roles) eq 'ARRAY') {
3839: $rolelist = join(':',@{$roles});
3840: }
3841: my %personnel = ();
3842:
3843: my %servers = &get_servers($dom,'library');
3844: foreach my $tryserver (keys(%servers)) {
3845: %{$personnel{$tryserver}}=();
3846: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3847: &escape($startdate).':'.
3848: &escape($enddate).':'.
3849: &escape($rolelist), $tryserver))) {
3850: my ($key,$value) = split(/\=/,$line,2);
3851: if (($key) && ($value)) {
3852: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3853: }
3854: }
3855: }
3856: return %personnel;
3857: }
3858:
3859: # ----------------------------------------------------------- Interval timing
3860:
3861: sub get_first_access {
3862: my ($type,$argsymb)=@_;
3863: my ($symb,$courseid,$udom,$uname)=&whichuser();
3864: if ($argsymb) { $symb=$argsymb; }
3865: my ($map,$id,$res)=&decode_symb($symb);
3866: if ($type eq 'course') {
3867: $res='course';
3868: } elsif ($type eq 'map') {
3869: $res=&symbread($map);
3870: } else {
3871: $res=$symb;
3872: }
3873: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3874: return $times{"$courseid\0$res"};
3875: }
3876:
3877: sub set_first_access {
3878: my ($type)=@_;
3879: my ($symb,$courseid,$udom,$uname)=&whichuser();
3880: my ($map,$id,$res)=&decode_symb($symb);
3881: if ($type eq 'course') {
3882: $res='course';
3883: } elsif ($type eq 'map') {
3884: $res=&symbread($map);
3885: } else {
3886: $res=$symb;
3887: }
3888: my $firstaccess=&get_first_access($type,$symb);
3889: if (!$firstaccess) {
3890: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3891: }
3892: return 'already_set';
3893: }
3894:
3895: # --------------------------------------------- Set Expire Date for Spreadsheet
3896:
3897: sub expirespread {
3898: my ($uname,$udom,$stype,$usymb)=@_;
3899: my $cid=$env{'request.course.id'};
3900: if ($cid) {
3901: my $now=time;
3902: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3903: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3904: $env{'course.'.$cid.'.num'}.
3905: ':nohist_expirationdates:'.
3906: &escape($key).'='.$now,
3907: $env{'course.'.$cid.'.home'})
3908: }
3909: return 'ok';
3910: }
3911:
3912: # ----------------------------------------------------- Devalidate Spreadsheets
3913:
3914: sub devalidate {
3915: my ($symb,$uname,$udom)=@_;
3916: my $cid=$env{'request.course.id'};
3917: if ($cid) {
3918: # delete the stored spreadsheets for
3919: # - the student level sheet of this user in course's homespace
3920: # - the assessment level sheet for this resource
3921: # for this user in user's homespace
3922: # - current conditional state info
3923: my $key=$uname.':'.$udom.':';
3924: my $status=
3925: &del('nohist_calculatedsheets',
3926: [$key.'studentcalc:'],
3927: $env{'course.'.$cid.'.domain'},
3928: $env{'course.'.$cid.'.num'})
3929: .' '.
3930: &del('nohist_calculatedsheets_'.$cid,
3931: [$key.'assesscalc:'.$symb],$udom,$uname);
3932: unless ($status eq 'ok ok') {
3933: &logthis('Could not devalidate spreadsheet '.
3934: $uname.' at '.$udom.' for '.
3935: $symb.': '.$status);
3936: }
3937: &delenv('user.state.'.$cid);
3938: }
3939: }
3940:
3941: sub get_scalar {
3942: my ($string,$end) = @_;
3943: my $value;
3944: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3945: $value = $1;
3946: } elsif ($$string =~ s/^([^&]*?)&//) {
3947: $value = $1;
3948: }
3949: return &unescape($value);
3950: }
3951:
3952: sub array2str {
3953: my (@array) = @_;
3954: my $result=&arrayref2str(\@array);
3955: $result=~s/^__ARRAY_REF__//;
3956: $result=~s/__END_ARRAY_REF__$//;
3957: return $result;
3958: }
3959:
3960: sub arrayref2str {
3961: my ($arrayref) = @_;
3962: my $result='__ARRAY_REF__';
3963: foreach my $elem (@$arrayref) {
3964: if(ref($elem) eq 'ARRAY') {
3965: $result.=&arrayref2str($elem).'&';
3966: } elsif(ref($elem) eq 'HASH') {
3967: $result.=&hashref2str($elem).'&';
3968: } elsif(ref($elem)) {
3969: #print("Got a ref of ".(ref($elem))." skipping.");
3970: } else {
3971: $result.=&escape($elem).'&';
3972: }
3973: }
3974: $result=~s/\&$//;
3975: $result .= '__END_ARRAY_REF__';
3976: return $result;
3977: }
3978:
3979: sub hash2str {
3980: my (%hash) = @_;
3981: my $result=&hashref2str(\%hash);
3982: $result=~s/^__HASH_REF__//;
3983: $result=~s/__END_HASH_REF__$//;
3984: return $result;
3985: }
3986:
3987: sub hashref2str {
3988: my ($hashref)=@_;
3989: my $result='__HASH_REF__';
3990: foreach my $key (sort(keys(%$hashref))) {
3991: if (ref($key) eq 'ARRAY') {
3992: $result.=&arrayref2str($key).'=';
3993: } elsif (ref($key) eq 'HASH') {
3994: $result.=&hashref2str($key).'=';
3995: } elsif (ref($key)) {
3996: $result.='=';
3997: #print("Got a ref of ".(ref($key))." skipping.");
3998: } else {
3999: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4000: }
4001:
4002: if(ref($hashref->{$key}) eq 'ARRAY') {
4003: $result.=&arrayref2str($hashref->{$key}).'&';
4004: } elsif(ref($hashref->{$key}) eq 'HASH') {
4005: $result.=&hashref2str($hashref->{$key}).'&';
4006: } elsif(ref($hashref->{$key})) {
4007: $result.='&';
4008: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4009: } else {
4010: $result.=&escape($hashref->{$key}).'&';
4011: }
4012: }
4013: $result=~s/\&$//;
4014: $result .= '__END_HASH_REF__';
4015: return $result;
4016: }
4017:
4018: sub str2hash {
4019: my ($string)=@_;
4020: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4021: return %$hash;
4022: }
4023:
4024: sub str2hashref {
4025: my ($string) = @_;
4026:
4027: my %hash;
4028:
4029: if($string !~ /^__HASH_REF__/) {
4030: if (! ($string eq '' || !defined($string))) {
4031: $hash{'error'}='Not hash reference';
4032: }
4033: return (\%hash, $string);
4034: }
4035:
4036: $string =~ s/^__HASH_REF__//;
4037:
4038: while($string !~ /^__END_HASH_REF__/) {
4039: #key
4040: my $key='';
4041: if($string =~ /^__HASH_REF__/) {
4042: ($key, $string)=&str2hashref($string);
4043: if(defined($key->{'error'})) {
4044: $hash{'error'}='Bad data';
4045: return (\%hash, $string);
4046: }
4047: } elsif($string =~ /^__ARRAY_REF__/) {
4048: ($key, $string)=&str2arrayref($string);
4049: if($key->[0] eq 'Array reference error') {
4050: $hash{'error'}='Bad data';
4051: return (\%hash, $string);
4052: }
4053: } else {
4054: $string =~ s/^(.*?)=//;
4055: $key=&unescape($1);
4056: }
4057: $string =~ s/^=//;
4058:
4059: #value
4060: my $value='';
4061: if($string =~ /^__HASH_REF__/) {
4062: ($value, $string)=&str2hashref($string);
4063: if(defined($value->{'error'})) {
4064: $hash{'error'}='Bad data';
4065: return (\%hash, $string);
4066: }
4067: } elsif($string =~ /^__ARRAY_REF__/) {
4068: ($value, $string)=&str2arrayref($string);
4069: if($value->[0] eq 'Array reference error') {
4070: $hash{'error'}='Bad data';
4071: return (\%hash, $string);
4072: }
4073: } else {
4074: $value=&get_scalar(\$string,'__END_HASH_REF__');
4075: }
4076: $string =~ s/^&//;
4077:
4078: $hash{$key}=$value;
4079: }
4080:
4081: $string =~ s/^__END_HASH_REF__//;
4082:
4083: return (\%hash, $string);
4084: }
4085:
4086: sub str2array {
4087: my ($string)=@_;
4088: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4089: return @$array;
4090: }
4091:
4092: sub str2arrayref {
4093: my ($string) = @_;
4094: my @array;
4095:
4096: if($string !~ /^__ARRAY_REF__/) {
4097: if (! ($string eq '' || !defined($string))) {
4098: $array[0]='Array reference error';
4099: }
4100: return (\@array, $string);
4101: }
4102:
4103: $string =~ s/^__ARRAY_REF__//;
4104:
4105: while($string !~ /^__END_ARRAY_REF__/) {
4106: my $value='';
4107: if($string =~ /^__HASH_REF__/) {
4108: ($value, $string)=&str2hashref($string);
4109: if(defined($value->{'error'})) {
4110: $array[0] ='Array reference error';
4111: return (\@array, $string);
4112: }
4113: } elsif($string =~ /^__ARRAY_REF__/) {
4114: ($value, $string)=&str2arrayref($string);
4115: if($value->[0] eq 'Array reference error') {
4116: $array[0] ='Array reference error';
4117: return (\@array, $string);
4118: }
4119: } else {
4120: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4121: }
4122: $string =~ s/^&//;
4123:
4124: push(@array, $value);
4125: }
4126:
4127: $string =~ s/^__END_ARRAY_REF__//;
4128:
4129: return (\@array, $string);
4130: }
4131:
4132: # -------------------------------------------------------------------Temp Store
4133:
4134: sub tmpreset {
4135: my ($symb,$namespace,$domain,$stuname) = @_;
4136: if (!$symb) {
4137: $symb=&symbread();
4138: if (!$symb) { $symb= $env{'request.url'}; }
4139: }
4140: $symb=escape($symb);
4141:
4142: if (!$namespace) { $namespace=$env{'request.state'}; }
4143: $namespace=~s/\//\_/g;
4144: $namespace=~s/\W//g;
4145:
4146: if (!$domain) { $domain=$env{'user.domain'}; }
4147: if (!$stuname) { $stuname=$env{'user.name'}; }
4148: if ($domain eq 'public' && $stuname eq 'public') {
4149: $stuname=$ENV{'REMOTE_ADDR'};
4150: }
4151: my $path=LONCAPA::tempdir();
4152: my %hash;
4153: if (tie(%hash,'GDBM_File',
4154: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4155: &GDBM_WRCREAT(),0640)) {
4156: foreach my $key (keys(%hash)) {
4157: if ($key=~ /:$symb/) {
4158: delete($hash{$key});
4159: }
4160: }
4161: }
4162: }
4163:
4164: sub tmpstore {
4165: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4166:
4167: if (!$symb) {
4168: $symb=&symbread();
4169: if (!$symb) { $symb= $env{'request.url'}; }
4170: }
4171: $symb=escape($symb);
4172:
4173: if (!$namespace) {
4174: # I don't think we would ever want to store this for a course.
4175: # it seems this will only be used if we don't have a course.
4176: #$namespace=$env{'request.course.id'};
4177: #if (!$namespace) {
4178: $namespace=$env{'request.state'};
4179: #}
4180: }
4181: $namespace=~s/\//\_/g;
4182: $namespace=~s/\W//g;
4183: if (!$domain) { $domain=$env{'user.domain'}; }
4184: if (!$stuname) { $stuname=$env{'user.name'}; }
4185: if ($domain eq 'public' && $stuname eq 'public') {
4186: $stuname=$ENV{'REMOTE_ADDR'};
4187: }
4188: my $now=time;
4189: my %hash;
4190: my $path=LONCAPA::tempdir();
4191: if (tie(%hash,'GDBM_File',
4192: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4193: &GDBM_WRCREAT(),0640)) {
4194: $hash{"version:$symb"}++;
4195: my $version=$hash{"version:$symb"};
4196: my $allkeys='';
4197: foreach my $key (keys(%$storehash)) {
4198: $allkeys.=$key.':';
4199: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4200: }
4201: $hash{"$version:$symb:timestamp"}=$now;
4202: $allkeys.='timestamp';
4203: $hash{"$version:keys:$symb"}=$allkeys;
4204: if (untie(%hash)) {
4205: return 'ok';
4206: } else {
4207: return "error:$!";
4208: }
4209: } else {
4210: return "error:$!";
4211: }
4212: }
4213:
4214: # -----------------------------------------------------------------Temp Restore
4215:
4216: sub tmprestore {
4217: my ($symb,$namespace,$domain,$stuname) = @_;
4218:
4219: if (!$symb) {
4220: $symb=&symbread();
4221: if (!$symb) { $symb= $env{'request.url'}; }
4222: }
4223: $symb=escape($symb);
4224:
4225: if (!$namespace) { $namespace=$env{'request.state'}; }
4226:
4227: if (!$domain) { $domain=$env{'user.domain'}; }
4228: if (!$stuname) { $stuname=$env{'user.name'}; }
4229: if ($domain eq 'public' && $stuname eq 'public') {
4230: $stuname=$ENV{'REMOTE_ADDR'};
4231: }
4232: my %returnhash;
4233: $namespace=~s/\//\_/g;
4234: $namespace=~s/\W//g;
4235: my %hash;
4236: my $path=LONCAPA::tempdir();
4237: if (tie(%hash,'GDBM_File',
4238: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4239: &GDBM_READER(),0640)) {
4240: my $version=$hash{"version:$symb"};
4241: $returnhash{'version'}=$version;
4242: my $scope;
4243: for ($scope=1;$scope<=$version;$scope++) {
4244: my $vkeys=$hash{"$scope:keys:$symb"};
4245: my @keys=split(/:/,$vkeys);
4246: my $key;
4247: $returnhash{"$scope:keys"}=$vkeys;
4248: foreach $key (@keys) {
4249: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4250: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4251: }
4252: }
4253: if (!(untie(%hash))) {
4254: return "error:$!";
4255: }
4256: } else {
4257: return "error:$!";
4258: }
4259: return %returnhash;
4260: }
4261:
4262: # ----------------------------------------------------------------------- Store
4263:
4264: sub store {
4265: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4266: my $home='';
4267:
4268: if ($stuname) { $home=&homeserver($stuname,$domain); }
4269:
4270: $symb=&symbclean($symb);
4271: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4272:
4273: if (!$domain) { $domain=$env{'user.domain'}; }
4274: if (!$stuname) { $stuname=$env{'user.name'}; }
4275:
4276: &devalidate($symb,$stuname,$domain);
4277:
4278: $symb=escape($symb);
4279: if (!$namespace) {
4280: unless ($namespace=$env{'request.course.id'}) {
4281: return '';
4282: }
4283: }
4284: if (!$home) { $home=$env{'user.home'}; }
4285:
4286: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4287: $$storehash{'host'}=$perlvar{'lonHostID'};
4288:
4289: my $namevalue='';
4290: foreach my $key (keys(%$storehash)) {
4291: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4292: }
4293: $namevalue=~s/\&$//;
4294: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4295: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4296: }
4297:
4298: # -------------------------------------------------------------- Critical Store
4299:
4300: sub cstore {
4301: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4302: my $home='';
4303:
4304: if ($stuname) { $home=&homeserver($stuname,$domain); }
4305:
4306: $symb=&symbclean($symb);
4307: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4308:
4309: if (!$domain) { $domain=$env{'user.domain'}; }
4310: if (!$stuname) { $stuname=$env{'user.name'}; }
4311:
4312: &devalidate($symb,$stuname,$domain);
4313:
4314: $symb=escape($symb);
4315: if (!$namespace) {
4316: unless ($namespace=$env{'request.course.id'}) {
4317: return '';
4318: }
4319: }
4320: if (!$home) { $home=$env{'user.home'}; }
4321:
4322: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4323: $$storehash{'host'}=$perlvar{'lonHostID'};
4324:
4325: my $namevalue='';
4326: foreach my $key (keys(%$storehash)) {
4327: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4328: }
4329: $namevalue=~s/\&$//;
4330: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4331: return critical
4332: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4333: }
4334:
4335: # --------------------------------------------------------------------- Restore
4336:
4337: sub restore {
4338: my ($symb,$namespace,$domain,$stuname) = @_;
4339: my $home='';
4340:
4341: if ($stuname) { $home=&homeserver($stuname,$domain); }
4342:
4343: if (!$symb) {
4344: unless ($symb=escape(&symbread())) { return ''; }
4345: } else {
4346: $symb=&escape(&symbclean($symb));
4347: }
4348: if (!$namespace) {
4349: unless ($namespace=$env{'request.course.id'}) {
4350: return '';
4351: }
4352: }
4353: if (!$domain) { $domain=$env{'user.domain'}; }
4354: if (!$stuname) { $stuname=$env{'user.name'}; }
4355: if (!$home) { $home=$env{'user.home'}; }
4356: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4357:
4358: my %returnhash=();
4359: foreach my $line (split(/\&/,$answer)) {
4360: my ($name,$value)=split(/\=/,$line);
4361: $returnhash{&unescape($name)}=&thaw_unescape($value);
4362: }
4363: my $version;
4364: for ($version=1;$version<=$returnhash{'version'};$version++) {
4365: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4366: $returnhash{$item}=$returnhash{$version.':'.$item};
4367: }
4368: }
4369: return %returnhash;
4370: }
4371:
4372: # ---------------------------------------------------------- Course Description
4373: #
4374: #
4375:
4376: sub coursedescription {
4377: my ($courseid,$args)=@_;
4378: $courseid=~s/^\///;
4379: $courseid=~s/\_/\//g;
4380: my ($cdomain,$cnum)=split(/\//,$courseid);
4381: my $chome=&homeserver($cnum,$cdomain);
4382: my $normalid=$cdomain.'_'.$cnum;
4383: # need to always cache even if we get errors otherwise we keep
4384: # trying and trying and trying to get the course description.
4385: my %envhash=();
4386: my %returnhash=();
4387:
4388: my $expiretime=600;
4389: if ($env{'request.course.id'} eq $normalid) {
4390: $expiretime=120;
4391: }
4392:
4393: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4394: if (!$args->{'freshen_cache'}
4395: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4396: foreach my $key (keys(%env)) {
4397: next if ($key !~ /^\Q$prefix\E(.*)/);
4398: my ($setting) = $1;
4399: $returnhash{$setting} = $env{$key};
4400: }
4401: return %returnhash;
4402: }
4403:
4404: # get the data again
4405:
4406: if (!$args->{'one_time'}) {
4407: $envhash{'course.'.$normalid.'.last_cache'}=time;
4408: }
4409:
4410: if ($chome ne 'no_host') {
4411: %returnhash=&dump('environment',$cdomain,$cnum);
4412: if (!exists($returnhash{'con_lost'})) {
4413: my $username = $env{'user.name'}; # Defult username
4414: if(defined $args->{'user'}) {
4415: $username = $args->{'user'};
4416: }
4417: $returnhash{'home'}= $chome;
4418: $returnhash{'domain'} = $cdomain;
4419: $returnhash{'num'} = $cnum;
4420: if (!defined($returnhash{'type'})) {
4421: $returnhash{'type'} = 'Course';
4422: }
4423: while (my ($name,$value) = each %returnhash) {
4424: $envhash{'course.'.$normalid.'.'.$name}=$value;
4425: }
4426: $returnhash{'url'}=&clutter($returnhash{'url'});
4427: $returnhash{'fn'}=LONCAPA::tempdir() .
4428: $username.'_'.$cdomain.'_'.$cnum;
4429: $envhash{'course.'.$normalid.'.home'}=$chome;
4430: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4431: $envhash{'course.'.$normalid.'.num'}=$cnum;
4432: }
4433: }
4434: if (!$args->{'one_time'}) {
4435: &appenv(\%envhash);
4436: }
4437: return %returnhash;
4438: }
4439:
4440: sub update_released_required {
4441: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4442: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4443: $cid = $env{'request.course.id'};
4444: $cdom = $env{'course.'.$cid.'.domain'};
4445: $cnum = $env{'course.'.$cid.'.num'};
4446: $chome = $env{'course.'.$cid.'.home'};
4447: }
4448: if ($needsrelease) {
4449: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4450: my $needsupdate;
4451: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4452: $needsupdate = 1;
4453: } else {
4454: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4455: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4456: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4457: $needsupdate = 1;
4458: }
4459: }
4460: if ($needsupdate) {
4461: my %needshash = (
4462: 'internal.releaserequired' => $needsrelease,
4463: );
4464: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4465: if ($putresult eq 'ok') {
4466: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4467: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4468: if (ref($crsinfo{$cid}) eq 'HASH') {
4469: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4470: &courseidput($cdom,\%crsinfo,$chome,'notime');
4471: }
4472: }
4473: }
4474: }
4475: return;
4476: }
4477:
4478: # -------------------------------------------------See if a user is privileged
4479:
4480: sub privileged {
4481: my ($username,$domain)=@_;
4482: my $rolesdump=&reply("dump:$domain:$username:roles",
4483: &homeserver($username,$domain));
4484: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4485: ($rolesdump =~ /^error:/)) {
4486: return 0;
4487: }
4488: my $now=time;
4489: if ($rolesdump ne '') {
4490: foreach my $entry (split(/&/,$rolesdump)) {
4491: if ($entry!~/^rolesdef_/) {
4492: my ($area,$role)=split(/=/,$entry);
4493: $area=~s/\_\w\w$//;
4494: my ($trole,$tend,$tstart)=split(/_/,$role);
4495: if (($trole eq 'dc') || ($trole eq 'su')) {
4496: my $active=1;
4497: if ($tend) {
4498: if ($tend<$now) { $active=0; }
4499: }
4500: if ($tstart) {
4501: if ($tstart>$now) { $active=0; }
4502: }
4503: if ($active) { return 1; }
4504: }
4505: }
4506: }
4507: }
4508: return 0;
4509: }
4510:
4511: # -------------------------------------------------------- Get user privileges
4512:
4513: sub rolesinit {
4514: my ($domain,$username,$authhost)=@_;
4515: my $now=time;
4516: my %userroles = ('user.login.time' => $now);
4517: my $extra = &freeze_escape({'skipcheck' => 1});
4518: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
4519: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4520: ($rolesdump =~ /^error:/)) {
4521: return \%userroles;
4522: }
4523: my %allroles=();
4524: my %allgroups=();
4525:
4526: if ($rolesdump ne '') {
4527: foreach my $entry (split(/&/,$rolesdump)) {
4528: if ($entry!~/^rolesdef_/) {
4529: my ($area,$role)=split(/=/,$entry);
4530: $area=~s/\_\w\w$//;
4531: my ($trole,$tend,$tstart,$group_privs);
4532: if ($role=~/^cr/) {
4533: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4534: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
4535: ($tend,$tstart)=split('_',$trest);
4536: } else {
4537: $trole=$role;
4538: }
4539: } elsif ($role =~ m|^gr/|) {
4540: ($trole,$tend,$tstart) = split(/_/,$role);
4541: next if ($tstart eq '-1');
4542: ($trole,$group_privs) = split(/\//,$trole);
4543: $group_privs = &unescape($group_privs);
4544: } else {
4545: ($trole,$tend,$tstart)=split(/_/,$role);
4546: }
4547: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4548: $username);
4549: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4550: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4551: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
4552: if (($area ne '') && ($trole ne '')) {
4553: my $spec=$trole.'.'.$area;
4554: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4555: if ($trole =~ /^cr\//) {
4556: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4557: } elsif ($trole eq 'gr') {
4558: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4559: } else {
4560: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4561: }
4562: }
4563: }
4564: }
4565: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4566: $userroles{'user.adv'} = $adv;
4567: $userroles{'user.author'} = $author;
4568: $env{'user.adv'}=$adv;
4569: }
4570: return \%userroles;
4571: }
4572:
4573: sub set_arearole {
4574: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4575: # log the associated role with the area
4576: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4577: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4578: }
4579:
4580: sub custom_roleprivs {
4581: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4582: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4583: my $homsvr=homeserver($rauthor,$rdomain);
4584: if (&hostname($homsvr) ne '') {
4585: my ($rdummy,$roledef)=
4586: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4587: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4588: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4589: if (defined($syspriv)) {
4590: if ($trest =~ /^$match_community$/) {
4591: $syspriv =~ s/bre\&S//;
4592: }
4593: $$allroles{'cm./'}.=':'.$syspriv;
4594: $$allroles{$spec.'./'}.=':'.$syspriv;
4595: }
4596: if ($tdomain ne '') {
4597: if (defined($dompriv)) {
4598: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4599: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4600: }
4601: if (($trest ne '') && (defined($coursepriv))) {
4602: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4603: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4604: }
4605: }
4606: }
4607: }
4608: }
4609:
4610: sub group_roleprivs {
4611: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4612: my $access = 1;
4613: my $now = time;
4614: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4615: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4616: if ($access) {
4617: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4618: $$allgroups{$course}{$group} .=':'.$group_privs;
4619: }
4620: }
4621:
4622: sub standard_roleprivs {
4623: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4624: if (defined($pr{$trole.':s'})) {
4625: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4626: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4627: }
4628: if ($tdomain ne '') {
4629: if (defined($pr{$trole.':d'})) {
4630: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4631: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4632: }
4633: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4634: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4635: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4636: }
4637: }
4638: }
4639:
4640: sub set_userprivs {
4641: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4642: my $author=0;
4643: my $adv=0;
4644: my %grouproles = ();
4645: if (keys(%{$allgroups}) > 0) {
4646: my @groupkeys;
4647: foreach my $role (keys(%{$allroles})) {
4648: push(@groupkeys,$role);
4649: }
4650: if (ref($groups_roles) eq 'HASH') {
4651: foreach my $key (keys(%{$groups_roles})) {
4652: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4653: push(@groupkeys,$key);
4654: }
4655: }
4656: }
4657: if (@groupkeys > 0) {
4658: foreach my $role (@groupkeys) {
4659: my ($trole,$area,$sec,$extendedarea);
4660: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4661: $trole = $1;
4662: $area = $2;
4663: $sec = $3;
4664: $extendedarea = $area.$sec;
4665: if (exists($$allgroups{$area})) {
4666: foreach my $group (keys(%{$$allgroups{$area}})) {
4667: my $spec = $trole.'.'.$extendedarea;
4668: $grouproles{$spec.'.'.$area.'/'.$group} =
4669: $$allgroups{$area}{$group};
4670: }
4671: }
4672: }
4673: }
4674: }
4675: }
4676: foreach my $group (keys(%grouproles)) {
4677: $$allroles{$group} = $grouproles{$group};
4678: }
4679: foreach my $role (keys(%{$allroles})) {
4680: my %thesepriv;
4681: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4682: foreach my $item (split(/:/,$$allroles{$role})) {
4683: if ($item ne '') {
4684: my ($privilege,$restrictions)=split(/&/,$item);
4685: if ($restrictions eq '') {
4686: $thesepriv{$privilege}='F';
4687: } elsif ($thesepriv{$privilege} ne 'F') {
4688: $thesepriv{$privilege}.=$restrictions;
4689: }
4690: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4691: }
4692: }
4693: my $thesestr='';
4694: foreach my $priv (sort(keys(%thesepriv))) {
4695: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4696: }
4697: $userroles->{'user.priv.'.$role} = $thesestr;
4698: }
4699: return ($author,$adv);
4700: }
4701:
4702: sub role_status {
4703: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4704: my @pwhere = ();
4705: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4706: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4707: unless (!defined($$role) || $$role eq '') {
4708: $$where=join('.',@pwhere);
4709: $$trolecode=$$role.'.'.$$where;
4710: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4711: $$tstatus='is';
4712: if ($$tstart && $$tstart>$update) {
4713: $$tstatus='future';
4714: if ($$tstart<$now) {
4715: if ($$tstart && $$tstart>$refresh) {
4716: if (($$where ne '') && ($$role ne '')) {
4717: my (%allroles,%allgroups,$group_privs,
4718: %groups_roles,@rolecodes);
4719: my %userroles = (
4720: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4721: );
4722: @rolecodes = ('cm');
4723: my $spec=$$role.'.'.$$where;
4724: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4725: if ($$role =~ /^cr\//) {
4726: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4727: push(@rolecodes,'cr');
4728: } elsif ($$role eq 'gr') {
4729: push(@rolecodes,$$role);
4730: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4731: $env{'user.name'});
4732: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4733: (undef,my $group_privs) = split(/\//,$trole);
4734: $group_privs = &unescape($group_privs);
4735: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4736: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4737: &get_groups_roles($tdomain,$trest,
4738: \%course_roles,\@rolecodes,
4739: \%groups_roles);
4740: } else {
4741: push(@rolecodes,$$role);
4742: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4743: }
4744: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4745: &appenv(\%userroles,\@rolecodes);
4746: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4747: }
4748: }
4749: $$tstatus = 'is';
4750: }
4751: }
4752: if ($$tend) {
4753: if ($$tend<$update) {
4754: $$tstatus='expired';
4755: } elsif ($$tend<$now) {
4756: $$tstatus='will_not';
4757: }
4758: }
4759: }
4760: }
4761: }
4762:
4763: sub get_groups_roles {
4764: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4765: return unless((ref($cdom_courseroles) eq 'HASH') &&
4766: (ref($rolecodes) eq 'ARRAY') &&
4767: (ref($groups_roles) eq 'HASH'));
4768: if (keys(%{$cdom_courseroles}) > 0) {
4769: my ($cnum) = ($rest =~ /^($match_courseid)/);
4770: if ($cdom ne '' && $cnum ne '') {
4771: foreach my $key (keys(%{$cdom_courseroles})) {
4772: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4773: my $crsrole = $1;
4774: my $crssec = $2;
4775: if ($crsrole =~ /^cr/) {
4776: unless (grep(/^cr$/,@{$rolecodes})) {
4777: push(@{$rolecodes},'cr');
4778: }
4779: } else {
4780: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4781: push(@{$rolecodes},$crsrole);
4782: }
4783: }
4784: my $rolekey = "$crsrole./$cdom/$cnum";
4785: if ($crssec ne '') {
4786: $rolekey .= "/$crssec";
4787: }
4788: $rolekey .= './';
4789: $groups_roles->{$rolekey} = $rolecodes;
4790: }
4791: }
4792: }
4793: }
4794: return;
4795: }
4796:
4797: sub delete_env_groupprivs {
4798: my ($where,$courseroles,$possroles) = @_;
4799: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4800: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4801: unless (ref($courseroles->{$udom}) eq 'HASH') {
4802: %{$courseroles->{$udom}} =
4803: &get_my_roles('','','userroles',['active'],
4804: $possroles,[$udom],1);
4805: }
4806: if (ref($courseroles->{$udom}) eq 'HASH') {
4807: foreach my $item (keys(%{$courseroles->{$udom}})) {
4808: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4809: my $area = '/'.$cdom.'/'.$cnum;
4810: my $privkey = "user.priv.$crsrole.$area";
4811: if ($crssec ne '') {
4812: $privkey .= '/'.$crssec;
4813: }
4814: $privkey .= ".$area/$group";
4815: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4816: }
4817: }
4818: return;
4819: }
4820:
4821: sub check_adhoc_privs {
4822: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
4823: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4824: if ($env{$cckey}) {
4825: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4826: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4827: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4828: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4829: }
4830: } else {
4831: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4832: }
4833: }
4834:
4835: sub set_adhoc_privileges {
4836: # role can be cc or ca
4837: my ($dcdom,$pickedcourse,$role,$caller) = @_;
4838: my $area = '/'.$dcdom.'/'.$pickedcourse;
4839: my $spec = $role.'.'.$area;
4840: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4841: $env{'user.name'});
4842: my %ccrole = ();
4843: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4844: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4845: &appenv(\%userroles,[$role,'cm']);
4846: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4847: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4848: &appenv( {'request.role' => $spec,
4849: 'request.role.domain' => $dcdom,
4850: 'request.course.sec' => ''
4851: }
4852: );
4853: my $tadv=0;
4854: if (&allowed('adv') eq 'F') { $tadv=1; }
4855: &appenv({'request.role.adv' => $tadv});
4856: }
4857: }
4858:
4859: # --------------------------------------------------------------- get interface
4860:
4861: sub get {
4862: my ($namespace,$storearr,$udomain,$uname)=@_;
4863: my $items='';
4864: foreach my $item (@$storearr) {
4865: $items.=&escape($item).'&';
4866: }
4867: $items=~s/\&$//;
4868: if (!$udomain) { $udomain=$env{'user.domain'}; }
4869: if (!$uname) { $uname=$env{'user.name'}; }
4870: my $uhome=&homeserver($uname,$udomain);
4871:
4872: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4873: my @pairs=split(/\&/,$rep);
4874: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4875: return @pairs;
4876: }
4877: my %returnhash=();
4878: my $i=0;
4879: foreach my $item (@$storearr) {
4880: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4881: $i++;
4882: }
4883: return %returnhash;
4884: }
4885:
4886: # --------------------------------------------------------------- del interface
4887:
4888: sub del {
4889: my ($namespace,$storearr,$udomain,$uname)=@_;
4890: my $items='';
4891: foreach my $item (@$storearr) {
4892: $items.=&escape($item).'&';
4893: }
4894:
4895: $items=~s/\&$//;
4896: if (!$udomain) { $udomain=$env{'user.domain'}; }
4897: if (!$uname) { $uname=$env{'user.name'}; }
4898: my $uhome=&homeserver($uname,$udomain);
4899: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4900: }
4901:
4902: # -------------------------------------------------------------- dump interface
4903:
4904: sub dump {
4905: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
4906: if (!$udomain) { $udomain=$env{'user.domain'}; }
4907: if (!$uname) { $uname=$env{'user.name'}; }
4908: my $uhome=&homeserver($uname,$udomain);
4909: if ($regexp) {
4910: $regexp=&escape($regexp);
4911: } else {
4912: $regexp='.';
4913: }
4914: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
4915: my @pairs=split(/\&/,$rep);
4916: my %returnhash=();
4917: if (!($rep =~ /^error/ )) {
4918: foreach my $item (@pairs) {
4919: my ($key,$value)=split(/=/,$item,2);
4920: $key = &unescape($key);
4921: next if ($key =~ /^error: 2 /);
4922: $returnhash{$key}=&thaw_unescape($value);
4923: }
4924: }
4925: return %returnhash;
4926: }
4927:
4928:
4929: # --------------------------------------------------------- dumpstore interface
4930:
4931: sub dumpstore {
4932: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4933: if (!$udomain) { $udomain=$env{'user.domain'}; }
4934: if (!$uname) { $uname=$env{'user.name'}; }
4935: my $uhome=&homeserver($uname,$udomain);
4936: if ($regexp) {
4937: $regexp=&escape($regexp);
4938: } else {
4939: $regexp='.';
4940: }
4941: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4942: my @pairs=split(/\&/,$rep);
4943: my %returnhash=();
4944: foreach my $item (@pairs) {
4945: my ($key,$value)=split(/=/,$item,2);
4946: next if ($key =~ /^error: 2 /);
4947: $returnhash{$key}=&thaw_unescape($value);
4948: }
4949: return %returnhash;
4950: }
4951:
4952: # -------------------------------------------------------------- keys interface
4953:
4954: sub getkeys {
4955: my ($namespace,$udomain,$uname)=@_;
4956: if (!$udomain) { $udomain=$env{'user.domain'}; }
4957: if (!$uname) { $uname=$env{'user.name'}; }
4958: my $uhome=&homeserver($uname,$udomain);
4959: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4960: my @keyarray=();
4961: foreach my $key (split(/\&/,$rep)) {
4962: next if ($key =~ /^error: 2 /);
4963: push(@keyarray,&unescape($key));
4964: }
4965: return @keyarray;
4966: }
4967:
4968: # --------------------------------------------------------------- currentdump
4969: sub currentdump {
4970: my ($courseid,$sdom,$sname)=@_;
4971: $courseid = $env{'request.course.id'} if (! defined($courseid));
4972: $sdom = $env{'user.domain'} if (! defined($sdom));
4973: $sname = $env{'user.name'} if (! defined($sname));
4974: my $uhome = &homeserver($sname,$sdom);
4975: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4976: return if ($rep =~ /^(error:|no_such_host)/);
4977: #
4978: my %returnhash=();
4979: #
4980: if ($rep eq "unknown_cmd") {
4981: # an old lond will not know currentdump
4982: # Do a dump and make it look like a currentdump
4983: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4984: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4985: my %hash = @tmp;
4986: @tmp=();
4987: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4988: } else {
4989: my @pairs=split(/\&/,$rep);
4990: foreach my $pair (@pairs) {
4991: my ($key,$value)=split(/=/,$pair,2);
4992: my ($symb,$param) = split(/:/,$key);
4993: $returnhash{&unescape($symb)}->{&unescape($param)} =
4994: &thaw_unescape($value);
4995: }
4996: }
4997: return %returnhash;
4998: }
4999:
5000: sub convert_dump_to_currentdump{
5001: my %hash = %{shift()};
5002: my %returnhash;
5003: # Code ripped from lond, essentially. The only difference
5004: # here is the unescaping done by lonnet::dump(). Conceivably
5005: # we might run in to problems with parameter names =~ /^v\./
5006: while (my ($key,$value) = each(%hash)) {
5007: my ($v,$symb,$param) = split(/:/,$key);
5008: $symb = &unescape($symb);
5009: $param = &unescape($param);
5010: next if ($v eq 'version' || $symb eq 'keys');
5011: next if (exists($returnhash{$symb}) &&
5012: exists($returnhash{$symb}->{$param}) &&
5013: $returnhash{$symb}->{'v.'.$param} > $v);
5014: $returnhash{$symb}->{$param}=$value;
5015: $returnhash{$symb}->{'v.'.$param}=$v;
5016: }
5017: #
5018: # Remove all of the keys in the hashes which keep track of
5019: # the version of the parameter.
5020: while (my ($symb,$param_hash) = each(%returnhash)) {
5021: # use a foreach because we are going to delete from the hash.
5022: foreach my $key (keys(%$param_hash)) {
5023: delete($param_hash->{$key}) if ($key =~ /^v\./);
5024: }
5025: }
5026: return \%returnhash;
5027: }
5028:
5029: # ------------------------------------------------------ critical inc interface
5030:
5031: sub cinc {
5032: return &inc(@_,'critical');
5033: }
5034:
5035: # --------------------------------------------------------------- inc interface
5036:
5037: sub inc {
5038: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5039: if (!$udomain) { $udomain=$env{'user.domain'}; }
5040: if (!$uname) { $uname=$env{'user.name'}; }
5041: my $uhome=&homeserver($uname,$udomain);
5042: my $items='';
5043: if (! ref($store)) {
5044: # got a single value, so use that instead
5045: $items = &escape($store).'=&';
5046: } elsif (ref($store) eq 'SCALAR') {
5047: $items = &escape($$store).'=&';
5048: } elsif (ref($store) eq 'ARRAY') {
5049: $items = join('=&',map {&escape($_);} @{$store});
5050: } elsif (ref($store) eq 'HASH') {
5051: while (my($key,$value) = each(%{$store})) {
5052: $items.= &escape($key).'='.&escape($value).'&';
5053: }
5054: }
5055: $items=~s/\&$//;
5056: if ($critical) {
5057: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5058: } else {
5059: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5060: }
5061: }
5062:
5063: # --------------------------------------------------------------- put interface
5064:
5065: sub put {
5066: my ($namespace,$storehash,$udomain,$uname)=@_;
5067: if (!$udomain) { $udomain=$env{'user.domain'}; }
5068: if (!$uname) { $uname=$env{'user.name'}; }
5069: my $uhome=&homeserver($uname,$udomain);
5070: my $items='';
5071: foreach my $item (keys(%$storehash)) {
5072: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5073: }
5074: $items=~s/\&$//;
5075: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5076: }
5077:
5078: # ------------------------------------------------------------ newput interface
5079:
5080: sub newput {
5081: my ($namespace,$storehash,$udomain,$uname)=@_;
5082: if (!$udomain) { $udomain=$env{'user.domain'}; }
5083: if (!$uname) { $uname=$env{'user.name'}; }
5084: my $uhome=&homeserver($uname,$udomain);
5085: my $items='';
5086: foreach my $key (keys(%$storehash)) {
5087: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5088: }
5089: $items=~s/\&$//;
5090: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5091: }
5092:
5093: # --------------------------------------------------------- putstore interface
5094:
5095: sub putstore {
5096: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5097: if (!$udomain) { $udomain=$env{'user.domain'}; }
5098: if (!$uname) { $uname=$env{'user.name'}; }
5099: my $uhome=&homeserver($uname,$udomain);
5100: my $items='';
5101: foreach my $key (keys(%$storehash)) {
5102: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5103: }
5104: $items=~s/\&$//;
5105: my $esc_symb=&escape($symb);
5106: my $esc_v=&escape($version);
5107: my $reply =
5108: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5109: $uhome);
5110: if ($reply eq 'unknown_cmd') {
5111: # gfall back to way things use to be done
5112: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5113: $uname);
5114: }
5115: return $reply;
5116: }
5117:
5118: sub old_putstore {
5119: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5120: if (!$udomain) { $udomain=$env{'user.domain'}; }
5121: if (!$uname) { $uname=$env{'user.name'}; }
5122: my $uhome=&homeserver($uname,$udomain);
5123: my %newstorehash;
5124: foreach my $item (keys(%$storehash)) {
5125: my $key = $version.':'.&escape($symb).':'.$item;
5126: $newstorehash{$key} = $storehash->{$item};
5127: }
5128: my $items='';
5129: my %allitems = ();
5130: foreach my $item (keys(%newstorehash)) {
5131: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5132: my $key = $1.':keys:'.$2;
5133: $allitems{$key} .= $3.':';
5134: }
5135: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5136: }
5137: foreach my $item (keys(%allitems)) {
5138: $allitems{$item} =~ s/\:$//;
5139: $items.= $item.'='.$allitems{$item}.'&';
5140: }
5141: $items=~s/\&$//;
5142: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5143: }
5144:
5145: # ------------------------------------------------------ critical put interface
5146:
5147: sub cput {
5148: my ($namespace,$storehash,$udomain,$uname)=@_;
5149: if (!$udomain) { $udomain=$env{'user.domain'}; }
5150: if (!$uname) { $uname=$env{'user.name'}; }
5151: my $uhome=&homeserver($uname,$udomain);
5152: my $items='';
5153: foreach my $item (keys(%$storehash)) {
5154: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5155: }
5156: $items=~s/\&$//;
5157: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5158: }
5159:
5160: # -------------------------------------------------------------- eget interface
5161:
5162: sub eget {
5163: my ($namespace,$storearr,$udomain,$uname)=@_;
5164: my $items='';
5165: foreach my $item (@$storearr) {
5166: $items.=&escape($item).'&';
5167: }
5168: $items=~s/\&$//;
5169: if (!$udomain) { $udomain=$env{'user.domain'}; }
5170: if (!$uname) { $uname=$env{'user.name'}; }
5171: my $uhome=&homeserver($uname,$udomain);
5172: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5173: my @pairs=split(/\&/,$rep);
5174: my %returnhash=();
5175: my $i=0;
5176: foreach my $item (@$storearr) {
5177: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5178: $i++;
5179: }
5180: return %returnhash;
5181: }
5182:
5183: # ------------------------------------------------------------ tmpput interface
5184: sub tmpput {
5185: my ($storehash,$server,$context)=@_;
5186: my $items='';
5187: foreach my $item (keys(%$storehash)) {
5188: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5189: }
5190: $items=~s/\&$//;
5191: if (defined($context)) {
5192: $items .= ':'.&escape($context);
5193: }
5194: return &reply("tmpput:$items",$server);
5195: }
5196:
5197: # ------------------------------------------------------------ tmpget interface
5198: sub tmpget {
5199: my ($token,$server)=@_;
5200: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5201: my $rep=&reply("tmpget:$token",$server);
5202: my %returnhash;
5203: foreach my $item (split(/\&/,$rep)) {
5204: my ($key,$value)=split(/=/,$item);
5205: next if ($key =~ /^error: 2 /);
5206: $returnhash{&unescape($key)}=&thaw_unescape($value);
5207: }
5208: return %returnhash;
5209: }
5210:
5211: # ------------------------------------------------------------ tmpdel interface
5212: sub tmpdel {
5213: my ($token,$server)=@_;
5214: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5215: return &reply("tmpdel:$token",$server);
5216: }
5217:
5218: # -------------------------------------------------- portfolio access checking
5219:
5220: sub portfolio_access {
5221: my ($requrl) = @_;
5222: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5223: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5224: if ($result) {
5225: my %setters;
5226: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5227: my ($startblock,$endblock) =
5228: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5229: if ($startblock && $endblock) {
5230: return 'B';
5231: }
5232: } else {
5233: my ($startblock,$endblock) =
5234: &Apache::loncommon::blockcheck(\%setters,'port');
5235: if ($startblock && $endblock) {
5236: return 'B';
5237: }
5238: }
5239: }
5240: if ($result eq 'ok') {
5241: return 'F';
5242: } elsif ($result =~ /^[^:]+:guest_/) {
5243: return 'A';
5244: }
5245: return '';
5246: }
5247:
5248: sub get_portfolio_access {
5249: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5250:
5251: if (!ref($access_hash)) {
5252: my $current_perms = &get_portfile_permissions($udom,$unum);
5253: my %access_controls = &get_access_controls($current_perms,$group,
5254: $file_name);
5255: $access_hash = $access_controls{$file_name};
5256: }
5257:
5258: my ($public,$guest,@domains,@users,@courses,@groups);
5259: my $now = time;
5260: if (ref($access_hash) eq 'HASH') {
5261: foreach my $key (keys(%{$access_hash})) {
5262: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5263: if ($start > $now) {
5264: next;
5265: }
5266: if ($end && $end<$now) {
5267: next;
5268: }
5269: if ($scope eq 'public') {
5270: $public = $key;
5271: last;
5272: } elsif ($scope eq 'guest') {
5273: $guest = $key;
5274: } elsif ($scope eq 'domains') {
5275: push(@domains,$key);
5276: } elsif ($scope eq 'users') {
5277: push(@users,$key);
5278: } elsif ($scope eq 'course') {
5279: push(@courses,$key);
5280: } elsif ($scope eq 'group') {
5281: push(@groups,$key);
5282: }
5283: }
5284: if ($public) {
5285: return 'ok';
5286: }
5287: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5288: if ($guest) {
5289: return $guest;
5290: }
5291: } else {
5292: if (@domains > 0) {
5293: foreach my $domkey (@domains) {
5294: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5295: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5296: return 'ok';
5297: }
5298: }
5299: }
5300: }
5301: if (@users > 0) {
5302: foreach my $userkey (@users) {
5303: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5304: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5305: if (ref($item) eq 'HASH') {
5306: if (($item->{'uname'} eq $env{'user.name'}) &&
5307: ($item->{'udom'} eq $env{'user.domain'})) {
5308: return 'ok';
5309: }
5310: }
5311: }
5312: }
5313: }
5314: }
5315: my %roleshash;
5316: my @courses_and_groups = @courses;
5317: push(@courses_and_groups,@groups);
5318: if (@courses_and_groups > 0) {
5319: my (%allgroups,%allroles);
5320: my ($start,$end,$role,$sec,$group);
5321: foreach my $envkey (%env) {
5322: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5323: my $cid = $2.'_'.$3;
5324: if ($1 eq 'gr') {
5325: $group = $4;
5326: $allgroups{$cid}{$group} = $env{$envkey};
5327: } else {
5328: if ($4 eq '') {
5329: $sec = 'none';
5330: } else {
5331: $sec = $4;
5332: }
5333: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5334: }
5335: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5336: my $cid = $2.'_'.$3;
5337: if ($4 eq '') {
5338: $sec = 'none';
5339: } else {
5340: $sec = $4;
5341: }
5342: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5343: }
5344: }
5345: if (keys(%allroles) == 0) {
5346: return;
5347: }
5348: foreach my $key (@courses_and_groups) {
5349: my %content = %{$$access_hash{$key}};
5350: my $cnum = $content{'number'};
5351: my $cdom = $content{'domain'};
5352: my $cid = $cdom.'_'.$cnum;
5353: if (!exists($allroles{$cid})) {
5354: next;
5355: }
5356: foreach my $role_id (keys(%{$content{'roles'}})) {
5357: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5358: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5359: my @status = @{$content{'roles'}{$role_id}{'access'}};
5360: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5361: foreach my $role (keys(%{$allroles{$cid}})) {
5362: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5363: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5364: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5365: if (grep/^all$/,@sections) {
5366: return 'ok';
5367: } else {
5368: if (grep/^$sec$/,@sections) {
5369: return 'ok';
5370: }
5371: }
5372: }
5373: }
5374: if (keys(%{$allgroups{$cid}}) == 0) {
5375: if (grep/^none$/,@groups) {
5376: return 'ok';
5377: }
5378: } else {
5379: if (grep/^all$/,@groups) {
5380: return 'ok';
5381: }
5382: foreach my $group (keys(%{$allgroups{$cid}})) {
5383: if (grep/^$group$/,@groups) {
5384: return 'ok';
5385: }
5386: }
5387: }
5388: }
5389: }
5390: }
5391: }
5392: }
5393: if ($guest) {
5394: return $guest;
5395: }
5396: }
5397: }
5398: return;
5399: }
5400:
5401: sub course_group_datechecker {
5402: my ($dates,$now,$status) = @_;
5403: my ($start,$end) = split(/\./,$dates);
5404: if (!$start && !$end) {
5405: return 'ok';
5406: }
5407: if (grep/^active$/,@{$status}) {
5408: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5409: return 'ok';
5410: }
5411: }
5412: if (grep/^previous$/,@{$status}) {
5413: if ($end > $now ) {
5414: return 'ok';
5415: }
5416: }
5417: if (grep/^future$/,@{$status}) {
5418: if ($start > $now) {
5419: return 'ok';
5420: }
5421: }
5422: return;
5423: }
5424:
5425: sub parse_portfolio_url {
5426: my ($url) = @_;
5427:
5428: my ($type,$udom,$unum,$group,$file_name);
5429:
5430: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5431: $type = 1;
5432: $udom = $1;
5433: $unum = $2;
5434: $file_name = $3;
5435: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5436: $type = 2;
5437: $udom = $1;
5438: $unum = $2;
5439: $group = $3;
5440: $file_name = $3.'/'.$4;
5441: }
5442: if (wantarray) {
5443: return ($type,$udom,$unum,$file_name,$group);
5444: }
5445: return $type;
5446: }
5447:
5448: sub is_portfolio_url {
5449: my ($url) = @_;
5450: return scalar(&parse_portfolio_url($url));
5451: }
5452:
5453: sub is_portfolio_file {
5454: my ($file) = @_;
5455: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5456: return 1;
5457: }
5458: return;
5459: }
5460:
5461: sub usertools_access {
5462: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
5463: my ($access,%tools);
5464: if ($context eq '') {
5465: $context = 'tools';
5466: }
5467: if ($context eq 'requestcourses') {
5468: %tools = (
5469: official => 1,
5470: unofficial => 1,
5471: community => 1,
5472: );
5473: } else {
5474: %tools = (
5475: aboutme => 1,
5476: blog => 1,
5477: portfolio => 1,
5478: );
5479: }
5480: return if (!defined($tools{$tool}));
5481:
5482: if ((!defined($udom)) || (!defined($uname))) {
5483: $udom = $env{'user.domain'};
5484: $uname = $env{'user.name'};
5485: }
5486:
5487: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5488: if ($action ne 'reload') {
5489: if ($context eq 'requestcourses') {
5490: return $env{'environment.canrequest.'.$tool};
5491: } else {
5492: return $env{'environment.availabletools.'.$tool};
5493: }
5494: }
5495: }
5496:
5497: my ($toolstatus,$inststatus);
5498:
5499: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5500: ($action ne 'reload')) {
5501: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5502: $inststatus = $env{'environment.inststatus'};
5503: } else {
5504: if (ref($userenvref) eq 'HASH') {
5505: $toolstatus = $userenvref->{$context.'.'.$tool};
5506: $inststatus = $userenvref->{'inststatus'};
5507: } else {
5508: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5509: $toolstatus = $userenv{$context.'.'.$tool};
5510: $inststatus = $userenv{'inststatus'};
5511: }
5512: }
5513:
5514: if ($toolstatus ne '') {
5515: if ($toolstatus) {
5516: $access = 1;
5517: } else {
5518: $access = 0;
5519: }
5520: return $access;
5521: }
5522:
5523: my ($is_adv,%domdef);
5524: if (ref($is_advref) eq 'HASH') {
5525: $is_adv = $is_advref->{'is_adv'};
5526: } else {
5527: $is_adv = &is_advanced_user($udom,$uname);
5528: }
5529: if (ref($domdefref) eq 'HASH') {
5530: %domdef = %{$domdefref};
5531: } else {
5532: %domdef = &get_domain_defaults($udom);
5533: }
5534: if (ref($domdef{$tool}) eq 'HASH') {
5535: if ($is_adv) {
5536: if ($domdef{$tool}{'_LC_adv'} ne '') {
5537: if ($domdef{$tool}{'_LC_adv'}) {
5538: $access = 1;
5539: } else {
5540: $access = 0;
5541: }
5542: return $access;
5543: }
5544: }
5545: if ($inststatus ne '') {
5546: my ($hasaccess,$hasnoaccess);
5547: foreach my $affiliation (split(/:/,$inststatus)) {
5548: if ($domdef{$tool}{$affiliation} ne '') {
5549: if ($domdef{$tool}{$affiliation}) {
5550: $hasaccess = 1;
5551: } else {
5552: $hasnoaccess = 1;
5553: }
5554: }
5555: }
5556: if ($hasaccess || $hasnoaccess) {
5557: if ($hasaccess) {
5558: $access = 1;
5559: } elsif ($hasnoaccess) {
5560: $access = 0;
5561: }
5562: return $access;
5563: }
5564: } else {
5565: if ($domdef{$tool}{'default'} ne '') {
5566: if ($domdef{$tool}{'default'}) {
5567: $access = 1;
5568: } elsif ($domdef{$tool}{'default'} == 0) {
5569: $access = 0;
5570: }
5571: return $access;
5572: }
5573: }
5574: } else {
5575: if ($context eq 'tools') {
5576: $access = 1;
5577: } else {
5578: $access = 0;
5579: }
5580: return $access;
5581: }
5582: }
5583:
5584: sub is_course_owner {
5585: my ($cdom,$cnum,$udom,$uname) = @_;
5586: if (($udom eq '') || ($uname eq '')) {
5587: $udom = $env{'user.domain'};
5588: $uname = $env{'user.name'};
5589: }
5590: unless (($udom eq '') || ($uname eq '')) {
5591: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5592: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5593: return 1;
5594: } else {
5595: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5596: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5597: return 1;
5598: }
5599: }
5600: }
5601: }
5602: return;
5603: }
5604:
5605: sub is_advanced_user {
5606: my ($udom,$uname) = @_;
5607: if ($udom ne '' && $uname ne '') {
5608: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5609: if (wantarray) {
5610: return ($env{'user.adv'},$env{'user.author'});
5611: } else {
5612: return $env{'user.adv'};
5613: }
5614: }
5615: }
5616: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5617: my %allroles;
5618: my ($is_adv,$is_author);
5619: foreach my $role (keys(%roleshash)) {
5620: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5621: my $area = '/'.$tdomain.'/'.$trest;
5622: if ($sec ne '') {
5623: $area .= '/'.$sec;
5624: }
5625: if (($area ne '') && ($trole ne '')) {
5626: my $spec=$trole.'.'.$area;
5627: if ($trole =~ /^cr\//) {
5628: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5629: } elsif ($trole ne 'gr') {
5630: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5631: }
5632: if ($trole eq 'au') {
5633: $is_author = 1;
5634: }
5635: }
5636: }
5637: foreach my $role (keys(%allroles)) {
5638: last if ($is_adv);
5639: foreach my $item (split(/:/,$allroles{$role})) {
5640: if ($item ne '') {
5641: my ($privilege,$restrictions)=split(/&/,$item);
5642: if ($privilege eq 'adv') {
5643: $is_adv = 1;
5644: last;
5645: }
5646: }
5647: }
5648: }
5649: if (wantarray) {
5650: return ($is_adv,$is_author);
5651: }
5652: return $is_adv;
5653: }
5654:
5655: sub check_can_request {
5656: my ($dom,$can_request,$request_domains) = @_;
5657: my $canreq = 0;
5658: my ($types,$typename) = &Apache::loncommon::course_types();
5659: my @options = ('approval','validate','autolimit');
5660: my $optregex = join('|',@options);
5661: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5662: foreach my $type (@{$types}) {
5663: if (&usertools_access($env{'user.name'},
5664: $env{'user.domain'},
5665: $type,undef,'requestcourses')) {
5666: $canreq ++;
5667: if (ref($request_domains) eq 'HASH') {
5668: push(@{$request_domains->{$type}},$env{'user.domain'});
5669: }
5670: if ($dom eq $env{'user.domain'}) {
5671: $can_request->{$type} = 1;
5672: }
5673: }
5674: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5675: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5676: if (@curr > 0) {
5677: foreach my $item (@curr) {
5678: if (ref($request_domains) eq 'HASH') {
5679: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5680: if ($otherdom ne '') {
5681: if (ref($request_domains->{$type}) eq 'ARRAY') {
5682: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5683: push(@{$request_domains->{$type}},$otherdom);
5684: }
5685: } else {
5686: push(@{$request_domains->{$type}},$otherdom);
5687: }
5688: }
5689: }
5690: }
5691: unless($dom eq $env{'user.domain'}) {
5692: $canreq ++;
5693: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5694: $can_request->{$type} = 1;
5695: }
5696: }
5697: }
5698: }
5699: }
5700: }
5701: return $canreq;
5702: }
5703:
5704: # ---------------------------------------------- Custom access rule evaluation
5705:
5706: sub customaccess {
5707: my ($priv,$uri)=@_;
5708: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5709: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5710: $udom = &LONCAPA::clean_domain($udom);
5711: $ucrs = &LONCAPA::clean_username($ucrs);
5712: my $access=0;
5713: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5714: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5715: if ($type eq 'user') {
5716: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5717: my ($tdom,$tuname)=split(m{/},$scope);
5718: if ($tdom) {
5719: if ($tdom ne $env{'user.domain'}) { next; }
5720: }
5721: if ($tuname) {
5722: if ($tuname ne $env{'user.name'}) { next; }
5723: }
5724: $access=($effect eq 'allow');
5725: last;
5726: }
5727: } else {
5728: if ($role) {
5729: if ($role ne $urole) { next; }
5730: }
5731: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5732: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5733: if ($tdom) {
5734: if ($tdom ne $udom) { next; }
5735: }
5736: if ($tcrs) {
5737: if ($tcrs ne $ucrs) { next; }
5738: }
5739: if ($tsec) {
5740: if ($tsec ne $usec) { next; }
5741: }
5742: $access=($effect eq 'allow');
5743: last;
5744: }
5745: if ($realm eq '' && $role eq '') {
5746: $access=($effect eq 'allow');
5747: }
5748: }
5749: }
5750: return $access;
5751: }
5752:
5753: # ------------------------------------------------- Check for a user privilege
5754:
5755: sub allowed {
5756: my ($priv,$uri,$symb,$role)=@_;
5757: my $ver_orguri=$uri;
5758: $uri=&deversion($uri);
5759: my $orguri=$uri;
5760: $uri=&declutter($uri);
5761:
5762: if ($priv eq 'evb') {
5763: # Evade communication block restrictions for specified role in a course
5764: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5765: return $1;
5766: } else {
5767: return;
5768: }
5769: }
5770:
5771: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5772: # Free bre access to adm and meta resources
5773: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5774: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5775: && ($priv eq 'bre')) {
5776: return 'F';
5777: }
5778:
5779: # Free bre access to user's own portfolio contents
5780: my ($space,$domain,$name,@dir)=split('/',$uri);
5781: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5782: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5783: my %setters;
5784: my ($startblock,$endblock) =
5785: &Apache::loncommon::blockcheck(\%setters,'port');
5786: if ($startblock && $endblock) {
5787: return 'B';
5788: } else {
5789: return 'F';
5790: }
5791: }
5792:
5793: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5794: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5795: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5796: if (exists($env{'request.course.id'})) {
5797: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5798: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5799: if (($domain eq $cdom) && ($name eq $cnum)) {
5800: my $courseprivid=$env{'request.course.id'};
5801: $courseprivid=~s/\_/\//;
5802: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5803: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5804: return $1;
5805: } else {
5806: if ($env{'request.course.sec'}) {
5807: $courseprivid.='/'.$env{'request.course.sec'};
5808: }
5809: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5810: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5811: return $2;
5812: }
5813: }
5814: }
5815: }
5816: }
5817:
5818: # Free bre to public access
5819:
5820: if ($priv eq 'bre') {
5821: my $copyright=&metadata($uri,'copyright');
5822: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5823: return 'F';
5824: }
5825: if ($copyright eq 'priv') {
5826: $uri=~/([^\/]+)\/([^\/]+)\//;
5827: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5828: return '';
5829: }
5830: }
5831: if ($copyright eq 'domain') {
5832: $uri=~/([^\/]+)\/([^\/]+)\//;
5833: unless (($env{'user.domain'} eq $1) ||
5834: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5835: return '';
5836: }
5837: }
5838: if ($env{'request.role'}=~ /li\.\//) {
5839: # Library role, so allow browsing of resources in this domain.
5840: return 'F';
5841: }
5842: if ($copyright eq 'custom') {
5843: unless (&customaccess($priv,$uri)) { return ''; }
5844: }
5845: }
5846: # Domain coordinator is trying to create a course
5847: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5848: # uri is the requested domain in this case.
5849: # comparison to 'request.role.domain' shows if the user has selected
5850: # a role of dc for the domain in question.
5851: return 'F' if ($uri eq $env{'request.role.domain'});
5852: }
5853:
5854: my $thisallowed='';
5855: my $statecond=0;
5856: my $courseprivid='';
5857:
5858: my $ownaccess;
5859: # Community Coordinator or Assistant Co-author browsing resource space.
5860: if (($priv eq 'bro') && ($env{'user.author'})) {
5861: if ($uri eq '') {
5862: $ownaccess = 1;
5863: } else {
5864: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5865: my $udom = $env{'user.domain'};
5866: my $uname = $env{'user.name'};
5867: if ($uri =~ m{^\Q$udom\E/?$}) {
5868: $ownaccess = 1;
5869: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
5870: unless ($uri =~ m{\.\./}) {
5871: $ownaccess = 1;
5872: }
5873: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5874: my $now = time;
5875: if ($uri =~ m{^([^/]+)/?$}) {
5876: my $adom = $1;
5877: foreach my $key (keys(%env)) {
5878: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
5879: my ($start,$end) = split('.',$env{$key});
5880: if (($now >= $start) && (!$end || $end < $now)) {
5881: $ownaccess = 1;
5882: last;
5883: }
5884: }
5885: }
5886: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5887: my $adom = $1;
5888: my $aname = $2;
5889: foreach my $role ('ca','aa') {
5890: if ($env{"user.role.$role./$adom/$aname"}) {
5891: my ($start,$end) =
5892: split('.',$env{"user.role.$role./$adom/$aname"});
5893: if (($now >= $start) && (!$end || $end < $now)) {
5894: $ownaccess = 1;
5895: last;
5896: }
5897: }
5898: }
5899: }
5900: }
5901: }
5902: }
5903: }
5904:
5905: # Course
5906:
5907: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5908: unless (($priv eq 'bro') && (!$ownaccess)) {
5909: $thisallowed.=$1;
5910: }
5911: }
5912:
5913: # Domain
5914:
5915: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5916: =~/\Q$priv\E\&([^\:]*)/) {
5917: unless (($priv eq 'bro') && (!$ownaccess)) {
5918: $thisallowed.=$1;
5919: }
5920: }
5921:
5922: # User who is not author or co-author might still be able to edit
5923: # resource of an author in the domain (e.g., if Domain Coordinator).
5924: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
5925: (&allowed('mdc',$env{'request.course.id'}))) {
5926: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
5927: $thisallowed.=$1;
5928: }
5929: }
5930:
5931: # Course: uri itself is a course
5932: my $courseuri=$uri;
5933: $courseuri=~s/\_(\d)/\/$1/;
5934: $courseuri=~s/^([^\/])/\/$1/;
5935:
5936: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5937: =~/\Q$priv\E\&([^\:]*)/) {
5938: unless (($priv eq 'bro') && (!$ownaccess)) {
5939: $thisallowed.=$1;
5940: }
5941: }
5942:
5943: # URI is an uploaded document for this course, default permissions don't matter
5944: # not allowing 'edit' access (editupload) to uploaded course docs
5945: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5946: $thisallowed='';
5947: my ($match)=&is_on_map($uri);
5948: if ($match) {
5949: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5950: =~/\Q$priv\E\&([^\:]*)/) {
5951: $thisallowed.=$1;
5952: }
5953: } else {
5954: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5955: if ($refuri) {
5956: if ($refuri =~ m|^/adm/|) {
5957: $thisallowed='F';
5958: } else {
5959: $refuri=&declutter($refuri);
5960: my ($match) = &is_on_map($refuri);
5961: if ($match) {
5962: $thisallowed='F';
5963: }
5964: }
5965: }
5966: }
5967: }
5968:
5969: if ($priv eq 'bre'
5970: && $thisallowed ne 'F'
5971: && $thisallowed ne '2'
5972: && &is_portfolio_url($uri)) {
5973: $thisallowed = &portfolio_access($uri);
5974: }
5975:
5976: # Full access at system, domain or course-wide level? Exit.
5977: if ($thisallowed=~/F/) {
5978: return 'F';
5979: }
5980:
5981: # If this is generating or modifying users, exit with special codes
5982:
5983: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5984: if (($priv eq 'cca') || ($priv eq 'caa')) {
5985: my ($audom,$auname)=split('/',$uri);
5986: # no author name given, so this just checks on the general right to make a co-author in this domain
5987: unless ($auname) { return $thisallowed; }
5988: # an author name is given, so we are about to actually make a co-author for a certain account
5989: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5990: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5991: ($audom ne $env{'request.role.domain'}))) { return ''; }
5992: }
5993: return $thisallowed;
5994: }
5995: #
5996: # Gathered so far: system, domain and course wide privileges
5997: #
5998: # Course: See if uri or referer is an individual resource that is part of
5999: # the course
6000:
6001: if ($env{'request.course.id'}) {
6002:
6003: $courseprivid=$env{'request.course.id'};
6004: if ($env{'request.course.sec'}) {
6005: $courseprivid.='/'.$env{'request.course.sec'};
6006: }
6007: $courseprivid=~s/\_/\//;
6008: my $checkreferer=1;
6009: my ($match,$cond)=&is_on_map($uri);
6010: if ($match) {
6011: $statecond=$cond;
6012: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6013: =~/\Q$priv\E\&([^\:]*)/) {
6014: $thisallowed.=$1;
6015: $checkreferer=0;
6016: }
6017: }
6018:
6019: if ($checkreferer) {
6020: my $refuri=$env{'httpref.'.$orguri};
6021: unless ($refuri) {
6022: foreach my $key (keys(%env)) {
6023: if ($key=~/^httpref\..*\*/) {
6024: my $pattern=$key;
6025: $pattern=~s/^httpref\.\/res\///;
6026: $pattern=~s/\*/\[\^\/\]\+/g;
6027: $pattern=~s/\//\\\//g;
6028: if ($orguri=~/$pattern/) {
6029: $refuri=$env{$key};
6030: }
6031: }
6032: }
6033: }
6034:
6035: if ($refuri) {
6036: $refuri=&declutter($refuri);
6037: my ($match,$cond)=&is_on_map($refuri);
6038: if ($match) {
6039: my $refstatecond=$cond;
6040: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6041: =~/\Q$priv\E\&([^\:]*)/) {
6042: $thisallowed.=$1;
6043: $uri=$refuri;
6044: $statecond=$refstatecond;
6045: }
6046: }
6047: }
6048: }
6049: }
6050:
6051: #
6052: # Gathered now: all privileges that could apply, and condition number
6053: #
6054: #
6055: # Full or no access?
6056: #
6057:
6058: if ($thisallowed=~/F/) {
6059: return 'F';
6060: }
6061:
6062: unless ($thisallowed) {
6063: return '';
6064: }
6065:
6066: # Restrictions exist, deal with them
6067: #
6068: # C:according to course preferences
6069: # R:according to resource settings
6070: # L:unless locked
6071: # X:according to user session state
6072: #
6073:
6074: # Possibly locked functionality, check all courses
6075: # Locks might take effect only after 10 minutes cache expiration for other
6076: # courses, and 2 minutes for current course
6077:
6078: my $envkey;
6079: if ($thisallowed=~/L/) {
6080: foreach $envkey (keys(%env)) {
6081: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6082: my $courseid=$2;
6083: my $roleid=$1.'.'.$2;
6084: $courseid=~s/^\///;
6085: my $expiretime=600;
6086: if ($env{'request.role'} eq $roleid) {
6087: $expiretime=120;
6088: }
6089: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6090: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6091: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6092: &coursedescription($courseid,{'freshen_cache' => 1});
6093: }
6094: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6095: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6096: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6097: &log($env{'user.domain'},$env{'user.name'},
6098: $env{'user.home'},
6099: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6100: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6101: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6102: return '';
6103: }
6104: }
6105: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6106: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6107: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6108: &log($env{'user.domain'},$env{'user.name'},
6109: $env{'user.home'},
6110: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6111: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6112: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6113: return '';
6114: }
6115: }
6116: }
6117: }
6118: }
6119:
6120: #
6121: # Rest of the restrictions depend on selected course
6122: #
6123:
6124: unless ($env{'request.course.id'}) {
6125: if ($thisallowed eq 'A') {
6126: return 'A';
6127: } elsif ($thisallowed eq 'B') {
6128: return 'B';
6129: } else {
6130: return '1';
6131: }
6132: }
6133:
6134: #
6135: # Now user is definitely in a course
6136: #
6137:
6138:
6139: # Course preferences
6140:
6141: if ($thisallowed=~/C/) {
6142: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6143: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6144: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6145: =~/\Q$rolecode\E/) {
6146: if (($priv ne 'pch') && ($priv ne 'plc')) {
6147: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6148: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6149: $env{'request.course.id'});
6150: }
6151: return '';
6152: }
6153:
6154: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6155: =~/\Q$unamedom\E/) {
6156: if (($priv ne 'pch') && ($priv ne 'plc')) {
6157: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6158: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6159: $env{'request.course.id'});
6160: }
6161: return '';
6162: }
6163: }
6164:
6165: # Resource preferences
6166:
6167: if ($thisallowed=~/R/) {
6168: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6169: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6170: if (($priv ne 'pch') && ($priv ne 'plc')) {
6171: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6172: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6173: }
6174: return '';
6175: }
6176: }
6177:
6178: # Restricted by state or randomout?
6179:
6180: if ($thisallowed=~/X/) {
6181: if ($env{'acc.randomout'}) {
6182: if (!$symb) { $symb=&symbread($uri,1); }
6183: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6184: return '';
6185: }
6186: }
6187: if (&condval($statecond)) {
6188: return '2';
6189: } else {
6190: return '';
6191: }
6192: }
6193:
6194: if ($thisallowed eq 'A') {
6195: return 'A';
6196: } elsif ($thisallowed eq 'B') {
6197: return 'B';
6198: }
6199: return 'F';
6200: }
6201: #
6202: # Removes the versino from a URI and
6203: # splits it in to its filename and path to the filename.
6204: # Seems like File::Basename could have done this more clearly.
6205: # Parameters:
6206: # $uri - input URI
6207: # Returns:
6208: # Two element list consisting of
6209: # $pathname - the URI up to and excluding the trailing /
6210: # $filename - The part of the URI following the last /
6211: # NOTE:
6212: # Another realization of this is simply:
6213: # use File::Basename;
6214: # ...
6215: # $uri = shift;
6216: # $filename = basename($uri);
6217: # $path = dirname($uri);
6218: # return ($filename, $path);
6219: #
6220: # The implementation below is probably faster however.
6221: #
6222: sub split_uri_for_cond {
6223: my $uri=&deversion(&declutter(shift));
6224: my @uriparts=split(/\//,$uri);
6225: my $filename=pop(@uriparts);
6226: my $pathname=join('/',@uriparts);
6227: return ($pathname,$filename);
6228: }
6229: # --------------------------------------------------- Is a resource on the map?
6230:
6231: sub is_on_map {
6232: my ($pathname,$filename) = &split_uri_for_cond(shift);
6233: #Trying to find the conditional for the file
6234: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
6235: /\&\Q$filename\E\:([\d\|]+)\&/);
6236: if ($match) {
6237: return (1,$1);
6238: } else {
6239: return (0,0);
6240: }
6241: }
6242:
6243: # --------------------------------------------------------- Get symb from alias
6244:
6245: sub get_symb_from_alias {
6246: my $symb=shift;
6247: my ($map,$resid,$url)=&decode_symb($symb);
6248: # Already is a symb
6249: if ($url) { return $symb; }
6250: # Must be an alias
6251: my $aliassymb='';
6252: my %bighash;
6253: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6254: &GDBM_READER(),0640)) {
6255: my $rid=$bighash{'mapalias_'.$symb};
6256: if ($rid) {
6257: my ($mapid,$resid)=split(/\./,$rid);
6258: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6259: $resid,$bighash{'src_'.$rid});
6260: }
6261: untie %bighash;
6262: }
6263: return $aliassymb;
6264: }
6265:
6266: # ----------------------------------------------------------------- Define Role
6267:
6268: sub definerole {
6269: if (allowed('mcr','/')) {
6270: my ($rolename,$sysrole,$domrole,$courole)=@_;
6271: foreach my $role (split(':',$sysrole)) {
6272: my ($crole,$cqual)=split(/\&/,$role);
6273: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6274: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6275: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6276: return "refused:s:$crole&$cqual";
6277: }
6278: }
6279: }
6280: foreach my $role (split(':',$domrole)) {
6281: my ($crole,$cqual)=split(/\&/,$role);
6282: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6283: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6284: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
6285: return "refused:d:$crole&$cqual";
6286: }
6287: }
6288: }
6289: foreach my $role (split(':',$courole)) {
6290: my ($crole,$cqual)=split(/\&/,$role);
6291: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6292: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6293: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6294: return "refused:c:$crole&$cqual";
6295: }
6296: }
6297: }
6298: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6299: "$env{'user.domain'}:$env{'user.name'}:".
6300: "rolesdef_$rolename=".
6301: escape($sysrole.'_'.$domrole.'_'.$courole);
6302: return reply($command,$env{'user.home'});
6303: } else {
6304: return 'refused';
6305: }
6306: }
6307:
6308: # ---------------- Make a metadata query against the network of library servers
6309:
6310: sub metadata_query {
6311: my ($query,$custom,$customshow,$server_array)=@_;
6312: my %rhash;
6313: my %libserv = &all_library();
6314: my @server_list = (defined($server_array) ? @$server_array
6315: : keys(%libserv) );
6316: for my $server (@server_list) {
6317: unless ($custom or $customshow) {
6318: my $reply=&reply("querysend:".&escape($query),$server);
6319: $rhash{$server}=$reply;
6320: }
6321: else {
6322: my $reply=&reply("querysend:".&escape($query).':'.
6323: &escape($custom).':'.&escape($customshow),
6324: $server);
6325: $rhash{$server}=$reply;
6326: }
6327: }
6328: return \%rhash;
6329: }
6330:
6331: # ----------------------------------------- Send log queries and wait for reply
6332:
6333: sub log_query {
6334: my ($uname,$udom,$query,%filters)=@_;
6335: my $uhome=&homeserver($uname,$udom);
6336: if ($uhome eq 'no_host') { return 'error: no_host'; }
6337: my $uhost=&hostname($uhome);
6338: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
6339: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6340: $uhome);
6341: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
6342: return get_query_reply($queryid);
6343: }
6344:
6345: # -------------------------- Update MySQL table for portfolio file
6346:
6347: sub update_portfolio_table {
6348: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
6349: if ($group ne '') {
6350: $file_name =~s /^\Q$group\E//;
6351: }
6352: my $homeserver = &homeserver($uname,$udom);
6353: my $queryid=
6354: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6355: ':'.&escape($file_name).':'.$action,$homeserver);
6356: my $reply = &get_query_reply($queryid);
6357: return $reply;
6358: }
6359:
6360: # -------------------------- Update MySQL allusers table
6361:
6362: sub update_allusers_table {
6363: my ($uname,$udom,$names) = @_;
6364: my $homeserver = &homeserver($uname,$udom);
6365: my $queryid=
6366: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6367: 'lastname='.&escape($names->{'lastname'}).'%%'.
6368: 'firstname='.&escape($names->{'firstname'}).'%%'.
6369: 'middlename='.&escape($names->{'middlename'}).'%%'.
6370: 'generation='.&escape($names->{'generation'}).'%%'.
6371: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6372: 'id='.&escape($names->{'id'}),$homeserver);
6373: return;
6374: }
6375:
6376: # ------- Request retrieval of institutional classlists for course(s)
6377:
6378: sub fetch_enrollment_query {
6379: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6380: my $homeserver;
6381: my $maxtries = 1;
6382: if ($context eq 'automated') {
6383: $homeserver = $perlvar{'lonHostID'};
6384: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6385: } else {
6386: $homeserver = &homeserver($cnum,$dom);
6387: }
6388: my $host=&hostname($homeserver);
6389: my $cmd = '';
6390: foreach my $affiliate (keys(%{$affiliatesref})) {
6391: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6392: }
6393: $cmd =~ s/%%$//;
6394: $cmd = &escape($cmd);
6395: my $query = 'fetchenrollment';
6396: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6397: unless ($queryid=~/^\Q$host\E\_/) {
6398: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6399: return 'error: '.$queryid;
6400: }
6401: my $reply = &get_query_reply($queryid);
6402: my $tries = 1;
6403: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6404: $reply = &get_query_reply($queryid);
6405: $tries ++;
6406: }
6407: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6408: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6409: } else {
6410: my @responses = split(/:/,$reply);
6411: if ($homeserver eq $perlvar{'lonHostID'}) {
6412: foreach my $line (@responses) {
6413: my ($key,$value) = split(/=/,$line,2);
6414: $$replyref{$key} = $value;
6415: }
6416: } else {
6417: my $pathname = LONCAPA::tempdir();
6418: foreach my $line (@responses) {
6419: my ($key,$value) = split(/=/,$line);
6420: $$replyref{$key} = $value;
6421: if ($value > 0) {
6422: foreach my $item (@{$$affiliatesref{$key}}) {
6423: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6424: my $destname = $pathname.'/'.$filename;
6425: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6426: if ($xml_classlist =~ /^error/) {
6427: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6428: } else {
6429: if ( open(FILE,">$destname") ) {
6430: print FILE &unescape($xml_classlist);
6431: close(FILE);
6432: } else {
6433: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6434: }
6435: }
6436: }
6437: }
6438: }
6439: }
6440: return 'ok';
6441: }
6442: return 'error';
6443: }
6444:
6445: sub get_query_reply {
6446: my $queryid=shift;
6447: my $replyfile=LONCAPA::tempdir().$queryid;
6448: my $reply='';
6449: for (1..100) {
6450: sleep 2;
6451: if (-e $replyfile.'.end') {
6452: if (open(my $fh,$replyfile)) {
6453: $reply = join('',<$fh>);
6454: close($fh);
6455: } else { return 'error: reply_file_error'; }
6456: return &unescape($reply);
6457: }
6458: }
6459: return 'timeout:'.$queryid;
6460: }
6461:
6462: sub courselog_query {
6463: #
6464: # possible filters:
6465: # url: url or symb
6466: # username
6467: # domain
6468: # action: view, submit, grade
6469: # start: timestamp
6470: # end: timestamp
6471: #
6472: my (%filters)=@_;
6473: unless ($env{'request.course.id'}) { return 'no_course'; }
6474: if ($filters{'url'}) {
6475: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6476: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6477: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6478: }
6479: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6480: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6481: return &log_query($cname,$cdom,'courselog',%filters);
6482: }
6483:
6484: sub userlog_query {
6485: #
6486: # possible filters:
6487: # action: log check role
6488: # start: timestamp
6489: # end: timestamp
6490: #
6491: my ($uname,$udom,%filters)=@_;
6492: return &log_query($uname,$udom,'userlog',%filters);
6493: }
6494:
6495: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6496:
6497: sub auto_run {
6498: my ($cnum,$cdom) = @_;
6499: my $response = 0;
6500: my $settings;
6501: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6502: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6503: $settings = $domconfig{'autoenroll'};
6504: if ($settings->{'run'} eq '1') {
6505: $response = 1;
6506: }
6507: } else {
6508: my $homeserver;
6509: if (&is_course($cdom,$cnum)) {
6510: $homeserver = &homeserver($cnum,$cdom);
6511: } else {
6512: $homeserver = &domain($cdom,'primary');
6513: }
6514: if ($homeserver ne 'no_host') {
6515: $response = &reply('autorun:'.$cdom,$homeserver);
6516: }
6517: }
6518: return $response;
6519: }
6520:
6521: sub auto_get_sections {
6522: my ($cnum,$cdom,$inst_coursecode) = @_;
6523: my $homeserver;
6524: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6525: $homeserver = &homeserver($cnum,$cdom);
6526: }
6527: if (!defined($homeserver)) {
6528: if ($cdom =~ /^$match_domain$/) {
6529: $homeserver = &domain($cdom,'primary');
6530: }
6531: }
6532: my @secs;
6533: if (defined($homeserver)) {
6534: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6535: unless ($response eq 'refused') {
6536: @secs = split(/:/,$response);
6537: }
6538: }
6539: return @secs;
6540: }
6541:
6542: sub auto_new_course {
6543: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6544: my $homeserver = &homeserver($cnum,$cdom);
6545: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6546: return $response;
6547: }
6548:
6549: sub auto_validate_courseID {
6550: my ($cnum,$cdom,$inst_course_id) = @_;
6551: my $homeserver = &homeserver($cnum,$cdom);
6552: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6553: return $response;
6554: }
6555:
6556: sub auto_validate_instcode {
6557: my ($cnum,$cdom,$instcode,$owner) = @_;
6558: my ($homeserver,$response);
6559: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6560: $homeserver = &homeserver($cnum,$cdom);
6561: }
6562: if (!defined($homeserver)) {
6563: if ($cdom =~ /^$match_domain$/) {
6564: $homeserver = &domain($cdom,'primary');
6565: }
6566: }
6567: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6568: &escape($instcode).':'.&escape($owner),$homeserver));
6569: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6570: return ($outcome,$description);
6571: }
6572:
6573: sub auto_create_password {
6574: my ($cnum,$cdom,$authparam,$udom) = @_;
6575: my ($homeserver,$response);
6576: my $create_passwd = 0;
6577: my $authchk = '';
6578: if ($udom =~ /^$match_domain$/) {
6579: $homeserver = &domain($udom,'primary');
6580: }
6581: if ($homeserver eq '') {
6582: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6583: $homeserver = &homeserver($cnum,$cdom);
6584: }
6585: }
6586: if ($homeserver eq '') {
6587: $authchk = 'nodomain';
6588: } else {
6589: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6590: if ($response eq 'refused') {
6591: $authchk = 'refused';
6592: } else {
6593: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6594: }
6595: }
6596: return ($authparam,$create_passwd,$authchk);
6597: }
6598:
6599: sub auto_photo_permission {
6600: my ($cnum,$cdom,$students) = @_;
6601: my $homeserver = &homeserver($cnum,$cdom);
6602: my ($outcome,$perm_reqd,$conditions) =
6603: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6604: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6605: return (undef,undef);
6606: }
6607: return ($outcome,$perm_reqd,$conditions);
6608: }
6609:
6610: sub auto_checkphotos {
6611: my ($uname,$udom,$pid) = @_;
6612: my $homeserver = &homeserver($uname,$udom);
6613: my ($result,$resulttype);
6614: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6615: &escape($uname).':'.&escape($pid),
6616: $homeserver));
6617: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6618: return (undef,undef);
6619: }
6620: if ($outcome) {
6621: ($result,$resulttype) = split(/:/,$outcome);
6622: }
6623: return ($result,$resulttype);
6624: }
6625:
6626: sub auto_photochoice {
6627: my ($cnum,$cdom) = @_;
6628: my $homeserver = &homeserver($cnum,$cdom);
6629: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6630: &escape($cdom),
6631: $homeserver)));
6632: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6633: return (undef,undef);
6634: }
6635: return ($update,$comment);
6636: }
6637:
6638: sub auto_photoupdate {
6639: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6640: my $homeserver = &homeserver($cnum,$dom);
6641: my $host=&hostname($homeserver);
6642: my $cmd = '';
6643: my $maxtries = 1;
6644: foreach my $affiliate (keys(%{$affiliatesref})) {
6645: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6646: }
6647: $cmd =~ s/%%$//;
6648: $cmd = &escape($cmd);
6649: my $query = 'institutionalphotos';
6650: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6651: unless ($queryid=~/^\Q$host\E\_/) {
6652: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6653: return 'error: '.$queryid;
6654: }
6655: my $reply = &get_query_reply($queryid);
6656: my $tries = 1;
6657: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6658: $reply = &get_query_reply($queryid);
6659: $tries ++;
6660: }
6661: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6662: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6663: } else {
6664: my @responses = split(/:/,$reply);
6665: my $outcome = shift(@responses);
6666: foreach my $item (@responses) {
6667: my ($key,$value) = split(/=/,$item);
6668: $$photo{$key} = $value;
6669: }
6670: return $outcome;
6671: }
6672: return 'error';
6673: }
6674:
6675: sub auto_instcode_format {
6676: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6677: $cat_order) = @_;
6678: my $courses = '';
6679: my @homeservers;
6680: if ($caller eq 'global') {
6681: my %servers = &get_servers($codedom,'library');
6682: foreach my $tryserver (keys(%servers)) {
6683: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6684: push(@homeservers,$tryserver);
6685: }
6686: }
6687: } elsif ($caller eq 'requests') {
6688: if ($codedom =~ /^$match_domain$/) {
6689: my $chome = &domain($codedom,'primary');
6690: unless ($chome eq 'no_host') {
6691: push(@homeservers,$chome);
6692: }
6693: }
6694: } else {
6695: push(@homeservers,&homeserver($caller,$codedom));
6696: }
6697: foreach my $code (keys(%{$instcodes})) {
6698: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
6699: }
6700: chop($courses);
6701: my $ok_response = 0;
6702: my $response;
6703: while (@homeservers > 0 && $ok_response == 0) {
6704: my $server = shift(@homeservers);
6705: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6706: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6707: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
6708: split(/:/,$response);
6709: %{$codes} = (%{$codes},&str2hash($codes_str));
6710: push(@{$codetitles},&str2array($codetitles_str));
6711: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6712: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6713: $ok_response = 1;
6714: }
6715: }
6716: if ($ok_response) {
6717: return 'ok';
6718: } else {
6719: return $response;
6720: }
6721: }
6722:
6723: sub auto_instcode_defaults {
6724: my ($domain,$returnhash,$code_order) = @_;
6725: my @homeservers;
6726:
6727: my %servers = &get_servers($domain,'library');
6728: foreach my $tryserver (keys(%servers)) {
6729: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6730: push(@homeservers,$tryserver);
6731: }
6732: }
6733:
6734: my $response;
6735: foreach my $server (@homeservers) {
6736: $response=&reply('autoinstcodedefaults:'.$domain,$server);
6737: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6738:
6739: foreach my $pair (split(/\&/,$response)) {
6740: my ($name,$value)=split(/\=/,$pair);
6741: if ($name eq 'code_order') {
6742: @{$code_order} = split(/\&/,&unescape($value));
6743: } else {
6744: $returnhash->{&unescape($name)}=&unescape($value);
6745: }
6746: }
6747: return 'ok';
6748: }
6749:
6750: return $response;
6751: }
6752:
6753: sub auto_possible_instcodes {
6754: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6755: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6756: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6757: return;
6758: }
6759: my (@homeservers,$uhome);
6760: if (defined(&domain($domain,'primary'))) {
6761: $uhome=&domain($domain,'primary');
6762: push(@homeservers,&domain($domain,'primary'));
6763: } else {
6764: my %servers = &get_servers($domain,'library');
6765: foreach my $tryserver (keys(%servers)) {
6766: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6767: push(@homeservers,$tryserver);
6768: }
6769: }
6770: }
6771: my $response;
6772: foreach my $server (@homeservers) {
6773: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6774: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6775: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6776: split(':',$response);
6777: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6778: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
6779: foreach my $item (split('&',$cat_title)) {
6780: my ($name,$value)=split('=',$item);
6781: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
6782: }
6783: foreach my $item (split('&',$cat_order)) {
6784: my ($name,$value)=split('=',$item);
6785: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
6786: }
6787: return 'ok';
6788: }
6789: return $response;
6790: }
6791:
6792: sub auto_courserequest_checks {
6793: my ($dom) = @_;
6794: my ($homeserver,%validations);
6795: if ($dom =~ /^$match_domain$/) {
6796: $homeserver = &domain($dom,'primary');
6797: }
6798: unless ($homeserver eq 'no_host') {
6799: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6800: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6801: my @items = split(/&/,$response);
6802: foreach my $item (@items) {
6803: my ($key,$value) = split('=',$item);
6804: $validations{&unescape($key)} = &thaw_unescape($value);
6805: }
6806: }
6807: }
6808: return %validations;
6809: }
6810:
6811: sub auto_courserequest_validation {
6812: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6813: my ($homeserver,$response);
6814: if ($dom =~ /^$match_domain$/) {
6815: $homeserver = &domain($dom,'primary');
6816: }
6817: unless ($homeserver eq 'no_host') {
6818:
6819: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
6820: ':'.&escape($crstype).':'.&escape($inststatuslist).
6821: ':'.&escape($instcode).':'.&escape($instseclist),
6822: $homeserver));
6823: }
6824: return $response;
6825: }
6826:
6827: sub auto_validate_class_sec {
6828: my ($cdom,$cnum,$owners,$inst_class) = @_;
6829: my $homeserver = &homeserver($cnum,$cdom);
6830: my $ownerlist;
6831: if (ref($owners) eq 'ARRAY') {
6832: $ownerlist = join(',',@{$owners});
6833: } else {
6834: $ownerlist = $owners;
6835: }
6836: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
6837: &escape($ownerlist).':'.$cdom,$homeserver);
6838: return $response;
6839: }
6840:
6841: # ------------------------------------------------------- Course Group routines
6842:
6843: sub get_coursegroups {
6844: my ($cdom,$cnum,$group,$namespace) = @_;
6845: return(&dump($namespace,$cdom,$cnum,$group));
6846: }
6847:
6848: sub modify_coursegroup {
6849: my ($cdom,$cnum,$groupsettings) = @_;
6850: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6851: }
6852:
6853: sub toggle_coursegroup_status {
6854: my ($cdom,$cnum,$group,$action) = @_;
6855: my ($from_namespace,$to_namespace);
6856: if ($action eq 'delete') {
6857: $from_namespace = 'coursegroups';
6858: $to_namespace = 'deleted_groups';
6859: } else {
6860: $from_namespace = 'deleted_groups';
6861: $to_namespace = 'coursegroups';
6862: }
6863: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
6864: if (my $tmp = &error(%curr_group)) {
6865: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6866: return ('read error',$tmp);
6867: } else {
6868: my %savedsettings = %curr_group;
6869: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
6870: my $deloutcome;
6871: if ($result eq 'ok') {
6872: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
6873: } else {
6874: return ('write error',$result);
6875: }
6876: if ($deloutcome eq 'ok') {
6877: return 'ok';
6878: } else {
6879: return ('delete error',$deloutcome);
6880: }
6881: }
6882: }
6883:
6884: sub modify_group_roles {
6885: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
6886: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6887: my $role = 'gr/'.&escape($userprivs);
6888: my ($uname,$udom) = split(/:/,$user);
6889: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
6890: if ($result eq 'ok') {
6891: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6892: }
6893: return $result;
6894: }
6895:
6896: sub modify_coursegroup_membership {
6897: my ($cdom,$cnum,$membership) = @_;
6898: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6899: return $result;
6900: }
6901:
6902: sub get_active_groups {
6903: my ($udom,$uname,$cdom,$cnum) = @_;
6904: my $now = time;
6905: my %groups = ();
6906: foreach my $key (keys(%env)) {
6907: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
6908: my ($start,$end) = split(/\./,$env{$key});
6909: if (($end!=0) && ($end<$now)) { next; }
6910: if (($start!=0) && ($start>$now)) { next; }
6911: if ($1 eq $cdom && $2 eq $cnum) {
6912: $groups{$3} = $env{$key} ;
6913: }
6914: }
6915: }
6916: return %groups;
6917: }
6918:
6919: sub get_group_membership {
6920: my ($cdom,$cnum,$group) = @_;
6921: return(&dump('groupmembership',$cdom,$cnum,$group));
6922: }
6923:
6924: sub get_users_groups {
6925: my ($udom,$uname,$courseid) = @_;
6926: my @usersgroups;
6927: my $cachetime=1800;
6928:
6929: my $hashid="$udom:$uname:$courseid";
6930: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6931: if (defined($cached)) {
6932: @usersgroups = split(/:/,$grouplist);
6933: } else {
6934: $grouplist = '';
6935: my $courseurl = &courseid_to_courseurl($courseid);
6936: my $extra = &freeze_escape({'skipcheck' => 1});
6937: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
6938: my $access_end = $env{'course.'.$courseid.
6939: '.default_enrollment_end_date'};
6940: my $now = time;
6941: foreach my $key (keys(%roleshash)) {
6942: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6943: my $group = $1;
6944: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6945: my $start = $2;
6946: my $end = $1;
6947: if ($start == -1) { next; } # deleted from group
6948: if (($start!=0) && ($start>$now)) { next; }
6949: if (($end!=0) && ($end<$now)) {
6950: if ($access_end && $access_end < $now) {
6951: if ($access_end - $end < 86400) {
6952: push(@usersgroups,$group);
6953: }
6954: }
6955: next;
6956: }
6957: push(@usersgroups,$group);
6958: }
6959: }
6960: }
6961: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6962: $grouplist = join(':',@usersgroups);
6963: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6964: }
6965: return @usersgroups;
6966: }
6967:
6968: sub devalidate_getgroups_cache {
6969: my ($udom,$uname,$cdom,$cnum)=@_;
6970: my $courseid = $cdom.'_'.$cnum;
6971:
6972: my $hashid="$udom:$uname:$courseid";
6973: &devalidate_cache_new('getgroups',$hashid);
6974: }
6975:
6976: # ------------------------------------------------------------------ Plain Text
6977:
6978: sub plaintext {
6979: my ($short,$type,$cid,$forcedefault) = @_;
6980: if ($short =~ m{^cr/}) {
6981: return (split('/',$short))[-1];
6982: }
6983: if (!defined($cid)) {
6984: $cid = $env{'request.course.id'};
6985: }
6986: my %rolenames = (
6987: Course => 'std',
6988: Community => 'alt1',
6989: );
6990: if ($cid ne '') {
6991: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6992: unless ($forcedefault) {
6993: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6994: &Apache::lonlocal::mt_escape(\$roletext);
6995: return &Apache::lonlocal::mt($roletext);
6996: }
6997: }
6998: }
6999: if ((defined($type)) && (defined($rolenames{$type})) &&
7000: (defined($rolenames{$type})) &&
7001: (defined($prp{$short}{$rolenames{$type}}))) {
7002: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
7003: } elsif ($cid ne '') {
7004: my $crstype = $env{'course.'.$cid.'.type'};
7005: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7006: (defined($prp{$short}{$rolenames{$crstype}}))) {
7007: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7008: }
7009: }
7010: return &Apache::lonlocal::mt($prp{$short}{'std'});
7011: }
7012:
7013: # ----------------------------------------------------------------- Assign Role
7014:
7015: sub assignrole {
7016: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7017: $context)=@_;
7018: my $mrole;
7019: if ($role =~ /^cr\//) {
7020: my $cwosec=$url;
7021: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7022: unless (&allowed('ccr',$cwosec)) {
7023: my $refused = 1;
7024: if ($context eq 'requestcourses') {
7025: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7026: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7027: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7028: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7029: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7030: if ($crsenv{'internal.courseowner'} eq
7031: $env{'user.name'}.':'.$env{'user.domain'}) {
7032: $refused = '';
7033: }
7034: }
7035: }
7036: }
7037: }
7038: if ($refused) {
7039: &logthis('Refused custom assignrole: '.
7040: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7041: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7042: return 'refused';
7043: }
7044: }
7045: $mrole='cr';
7046: } elsif ($role =~ /^gr\//) {
7047: my $cwogrp=$url;
7048: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7049: unless (&allowed('mdg',$cwogrp)) {
7050: &logthis('Refused group assignrole: '.
7051: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7052: $env{'user.name'}.' at '.$env{'user.domain'});
7053: return 'refused';
7054: }
7055: $mrole='gr';
7056: } else {
7057: my $cwosec=$url;
7058: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7059: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7060: my $refused;
7061: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7062: if (!(&allowed('c'.$role,$url))) {
7063: $refused = 1;
7064: }
7065: } else {
7066: $refused = 1;
7067: }
7068: if ($refused) {
7069: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7070: if (!$selfenroll && $context eq 'course') {
7071: my %crsenv;
7072: if ($role eq 'cc' || $role eq 'co') {
7073: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7074: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7075: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7076: if ($crsenv{'internal.courseowner'} eq
7077: $env{'user.name'}.':'.$env{'user.domain'}) {
7078: $refused = '';
7079: }
7080: }
7081: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7082: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7083: if ($crsenv{'internal.courseowner'} eq
7084: $env{'user.name'}.':'.$env{'user.domain'}) {
7085: $refused = '';
7086: }
7087: }
7088: }
7089: }
7090: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7091: $refused = '';
7092: } elsif ($context eq 'requestcourses') {
7093: my @possroles = ('st','ta','ep','in','cc','co');
7094: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7095: my $wrongcc;
7096: if ($cnum =~ /^$match_community$/) {
7097: $wrongcc = 1 if ($role eq 'cc');
7098: } else {
7099: $wrongcc = 1 if ($role eq 'co');
7100: }
7101: unless ($wrongcc) {
7102: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7103: if ($crsenv{'internal.courseowner'} eq
7104: $env{'user.name'}.':'.$env{'user.domain'}) {
7105: $refused = '';
7106: }
7107: }
7108: }
7109: }
7110: if ($refused) {
7111: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7112: ' '.$role.' '.$end.' '.$start.' by '.
7113: $env{'user.name'}.' at '.$env{'user.domain'});
7114: return 'refused';
7115: }
7116: }
7117: } elsif ($role eq 'au') {
7118: if ($url ne '/'.$udom.'/') {
7119: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7120: ' to assign author role for '.$uname.':'.$udom.
7121: ' in domain: '.$url.' refused (wrong domain).');
7122: return 'refused';
7123: }
7124: }
7125: $mrole=$role;
7126: }
7127: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7128: "$udom:$uname:$url".'_'."$mrole=$role";
7129: if ($end) { $command.='_'.$end; }
7130: if ($start) {
7131: if ($end) {
7132: $command.='_'.$start;
7133: } else {
7134: $command.='_0_'.$start;
7135: }
7136: }
7137: my $origstart = $start;
7138: my $origend = $end;
7139: my $delflag;
7140: # actually delete
7141: if ($deleteflag) {
7142: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
7143: # modify command to delete the role
7144: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
7145: "$udom:$uname:$url".'_'."$mrole";
7146: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
7147: # set start and finish to negative values for userrolelog
7148: $start=-1;
7149: $end=-1;
7150: $delflag = 1;
7151: }
7152: }
7153: # send command
7154: my $answer=&reply($command,&homeserver($uname,$udom));
7155: # log new user role if status is ok
7156: if ($answer eq 'ok') {
7157: &userrolelog($role,$uname,$udom,$url,$start,$end);
7158: # for course roles, perform group memberships changes triggered by role change.
7159: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
7160: unless ($role =~ /^gr/) {
7161: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
7162: $origstart,$selfenroll,$context);
7163: }
7164: if ($role eq 'cc') {
7165: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7166: }
7167: }
7168: return $answer;
7169: }
7170:
7171: sub autoupdate_coowners {
7172: my ($url,$end,$start,$uname,$udom) = @_;
7173: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7174: if (($cdom ne '') && ($cnum ne '')) {
7175: my $now = time;
7176: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7177: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7178: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7179: my $instcode = $coursehash{'internal.coursecode'};
7180: if ($instcode ne '') {
7181: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7182: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
7183: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
7184: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7185: if ($result eq 'valid') {
7186: if ($coursehash{'internal.co-owners'}) {
7187: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7188: push(@newcoowners,$coowner);
7189: }
7190: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7191: push(@newcoowners,$uname.':'.$udom);
7192: }
7193: @newcoowners = sort(@newcoowners);
7194: } else {
7195: push(@newcoowners,$uname.':'.$udom);
7196: }
7197: } else {
7198: if ($coursehash{'internal.co-owners'}) {
7199: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7200: unless ($coowner eq $uname.':'.$udom) {
7201: push(@newcoowners,$coowner);
7202: }
7203: }
7204: unless (@newcoowners > 0) {
7205: $delcoowners = 1;
7206: $coowners = '';
7207: }
7208: }
7209: }
7210: if (@newcoowners || $delcoowners) {
7211: &store_coowners($cdom,$cnum,$coursehash{'home'},
7212: $delcoowners,@newcoowners);
7213: }
7214: }
7215: }
7216: }
7217: }
7218: }
7219: }
7220:
7221: sub store_coowners {
7222: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7223: my $cid = $cdom.'_'.$cnum;
7224: my ($coowners,$delresult,$putresult);
7225: if (@newcoowners) {
7226: $coowners = join(',',@newcoowners);
7227: my %coownershash = (
7228: 'internal.co-owners' => $coowners,
7229: );
7230: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7231: if ($putresult eq 'ok') {
7232: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7233: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7234: }
7235: }
7236: }
7237: if ($delcoowners) {
7238: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7239: if ($delresult eq 'ok') {
7240: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7241: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7242: }
7243: }
7244: }
7245: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7246: my %crsinfo =
7247: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7248: if (ref($crsinfo{$cid}) eq 'HASH') {
7249: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7250: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7251: }
7252: }
7253: }
7254:
7255: # -------------------------------------------------- Modify user authentication
7256: # Overrides without validation
7257:
7258: sub modifyuserauth {
7259: my ($udom,$uname,$umode,$upass)=@_;
7260: my $uhome=&homeserver($uname,$udom);
7261: unless (&allowed('mau',$udom)) { return 'refused'; }
7262: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
7263: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7264: ' in domain '.$env{'request.role.domain'});
7265: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7266: &escape($upass),$uhome);
7267: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
7268: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7269: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7270: &log($udom,,$uname,$uhome,
7271: 'Authentication changed by '.$env{'user.domain'}.', '.
7272: $env{'user.name'}.', '.$umode.
7273: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7274: unless ($reply eq 'ok') {
7275: &logthis('Authentication mode error: '.$reply);
7276: return 'error: '.$reply;
7277: }
7278: return 'ok';
7279: }
7280:
7281: # --------------------------------------------------------------- Modify a user
7282:
7283: sub modifyuser {
7284: my ($udom, $uname, $uid,
7285: $umode, $upass, $first,
7286: $middle, $last, $gene,
7287: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
7288: $udom= &LONCAPA::clean_domain($udom);
7289: $uname=&LONCAPA::clean_username($uname);
7290: my $showcandelete = 'none';
7291: if (ref($candelete) eq 'ARRAY') {
7292: if (@{$candelete} > 0) {
7293: $showcandelete = join(', ',@{$candelete});
7294: }
7295: }
7296: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
7297: $umode.', '.$first.', '.$middle.', '.
7298: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
7299: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7300: ' desiredhome not specified').
7301: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7302: ' in domain '.$env{'request.role.domain'});
7303: my $uhome=&homeserver($uname,$udom,'true');
7304: my $newuser;
7305: if ($uhome eq 'no_host') {
7306: $newuser = 1;
7307: }
7308: # ----------------------------------------------------------------- Create User
7309: if (($uhome eq 'no_host') &&
7310: (($umode && $upass) || ($umode eq 'localauth'))) {
7311: my $unhome='';
7312: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
7313: $unhome = $desiredhome;
7314: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7315: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
7316: } else { # load balancing routine for determining $unhome
7317: my $loadm=10000000;
7318: my %servers = &get_servers($udom,'library');
7319: foreach my $tryserver (keys(%servers)) {
7320: my $answer=reply('load',$tryserver);
7321: if (($answer=~/\d+/) && ($answer<$loadm)) {
7322: $loadm=$answer;
7323: $unhome=$tryserver;
7324: }
7325: }
7326: }
7327: if (($unhome eq '') || ($unhome eq 'no_host')) {
7328: return 'error: unable to find a home server for '.$uname.
7329: ' in domain '.$udom;
7330: }
7331: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7332: &escape($upass),$unhome);
7333: unless ($reply eq 'ok') {
7334: return 'error: '.$reply;
7335: }
7336: $uhome=&homeserver($uname,$udom,'true');
7337: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
7338: return 'error: unable verify users home machine.';
7339: }
7340: } # End of creation of new user
7341: # ---------------------------------------------------------------------- Add ID
7342: if ($uid) {
7343: $uid=~tr/A-Z/a-z/;
7344: my %uidhash=&idrget($udom,$uname);
7345: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7346: && (!$forceid)) {
7347: unless ($uid eq $uidhash{$uname}) {
7348: return 'error: user id "'.$uid.'" does not match '.
7349: 'current user id "'.$uidhash{$uname}.'".';
7350: }
7351: } else {
7352: &idput($udom,($uname => $uid));
7353: }
7354: }
7355: # -------------------------------------------------------------- Add names, etc
7356: my @tmp=&get('environment',
7357: ['firstname','middlename','lastname','generation','id',
7358: 'permanentemail','inststatus'],
7359: $udom,$uname);
7360: my (%names,%oldnames);
7361: if ($tmp[0] =~ m/^error:.*/) {
7362: %names=();
7363: } else {
7364: %names = @tmp;
7365: %oldnames = %names;
7366: }
7367: #
7368: # If name, email and/or uid are blank (e.g., because an uploaded file
7369: # of users did not contain them), do not overwrite existing values
7370: # unless field is in $candelete array ref.
7371: #
7372:
7373: my @fields = ('firstname','middlename','lastname','generation',
7374: 'permanentemail','id');
7375: my %newvalues;
7376: if (ref($candelete) eq 'ARRAY') {
7377: foreach my $field (@fields) {
7378: if (grep(/^\Q$field\E$/,@{$candelete})) {
7379: if ($field eq 'firstname') {
7380: $names{$field} = $first;
7381: } elsif ($field eq 'middlename') {
7382: $names{$field} = $middle;
7383: } elsif ($field eq 'lastname') {
7384: $names{$field} = $last;
7385: } elsif ($field eq 'generation') {
7386: $names{$field} = $gene;
7387: } elsif ($field eq 'permanentemail') {
7388: $names{$field} = $email;
7389: } elsif ($field eq 'id') {
7390: $names{$field} = $uid;
7391: }
7392: }
7393: }
7394: }
7395: if ($first) { $names{'firstname'} = $first; }
7396: if (defined($middle)) { $names{'middlename'} = $middle; }
7397: if ($last) { $names{'lastname'} = $last; }
7398: if (defined($gene)) { $names{'generation'} = $gene; }
7399: if ($email) {
7400: $email=~s/[^\w\@\.\-\,]//gs;
7401: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7402: }
7403: if ($uid) { $names{'id'} = $uid; }
7404: if (defined($inststatus)) {
7405: $names{'inststatus'} = '';
7406: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7407: if (ref($usertypes) eq 'HASH') {
7408: my @okstatuses;
7409: foreach my $item (split(/:/,$inststatus)) {
7410: if (defined($usertypes->{$item})) {
7411: push(@okstatuses,$item);
7412: }
7413: }
7414: if (@okstatuses) {
7415: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7416: }
7417: }
7418: }
7419: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7420: $umode.', '.$first.', '.$middle.', '.
7421: $last.', '.$gene.', '.$email.', '.$inststatus;
7422: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7423: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7424: } else {
7425: $logmsg .= ' during self creation';
7426: }
7427: my $changed;
7428: if ($newuser) {
7429: $changed = 1;
7430: } else {
7431: foreach my $field (@fields) {
7432: if ($names{$field} ne $oldnames{$field}) {
7433: $changed = 1;
7434: last;
7435: }
7436: }
7437: }
7438: unless ($changed) {
7439: $logmsg = 'No changes in user information needed for: '.$logmsg;
7440: &logthis($logmsg);
7441: return 'ok';
7442: }
7443: my $reply = &put('environment', \%names, $udom,$uname);
7444: if ($reply ne 'ok') {
7445: return 'error: '.$reply;
7446: }
7447: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7448: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7449: }
7450: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7451: &devalidate_cache_new('namescache',$uname.':'.$udom);
7452: $logmsg = 'Success modifying user '.$logmsg;
7453: &logthis($logmsg);
7454: return 'ok';
7455: }
7456:
7457: # -------------------------------------------------------------- Modify student
7458:
7459: sub modifystudent {
7460: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7461: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7462: $selfenroll,$context,$inststatus)=@_;
7463: if (!$cid) {
7464: unless ($cid=$env{'request.course.id'}) {
7465: return 'not_in_class';
7466: }
7467: }
7468: # --------------------------------------------------------------- Make the user
7469: my $reply=&modifyuser
7470: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7471: $desiredhome,$email,$inststatus);
7472: unless ($reply eq 'ok') { return $reply; }
7473: # This will cause &modify_student_enrollment to get the uid from the
7474: # students environment
7475: $uid = undef if (!$forceid);
7476: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7477: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7478: return $reply;
7479: }
7480:
7481: sub modify_student_enrollment {
7482: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7483: my ($cdom,$cnum,$chome);
7484: if (!$cid) {
7485: unless ($cid=$env{'request.course.id'}) {
7486: return 'not_in_class';
7487: }
7488: $cdom=$env{'course.'.$cid.'.domain'};
7489: $cnum=$env{'course.'.$cid.'.num'};
7490: } else {
7491: ($cdom,$cnum)=split(/_/,$cid);
7492: }
7493: $chome=$env{'course.'.$cid.'.home'};
7494: if (!$chome) {
7495: $chome=&homeserver($cnum,$cdom);
7496: }
7497: if (!$chome) { return 'unknown_course'; }
7498: # Make sure the user exists
7499: my $uhome=&homeserver($uname,$udom);
7500: if (($uhome eq '') || ($uhome eq 'no_host')) {
7501: return 'error: no such user';
7502: }
7503: # Get student data if we were not given enough information
7504: if (!defined($first) || $first eq '' ||
7505: !defined($last) || $last eq '' ||
7506: !defined($uid) || $uid eq '' ||
7507: !defined($middle) || $middle eq '' ||
7508: !defined($gene) || $gene eq '') {
7509: # They did not supply us with enough data to enroll the student, so
7510: # we need to pick up more information.
7511: my %tmp = &get('environment',
7512: ['firstname','middlename','lastname', 'generation','id']
7513: ,$udom,$uname);
7514:
7515: #foreach my $key (keys(%tmp)) {
7516: # &logthis("key $key = ".$tmp{$key});
7517: #}
7518: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7519: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7520: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7521: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7522: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7523: }
7524: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7525: my $user = "$uname:$udom";
7526: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
7527: my $reply=cput('classlist',
7528: {$user =>
7529: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7530: $cdom,$cnum);
7531: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7532: &devalidate_getsection_cache($udom,$uname,$cid);
7533: } else {
7534: return 'error: '.$reply;
7535: }
7536: # Add student role to user
7537: my $uurl='/'.$cid;
7538: $uurl=~s/\_/\//g;
7539: if ($usec) {
7540: $uurl.='/'.$usec;
7541: }
7542: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7543: $selfenroll,$context);
7544: if ($result ne 'ok') {
7545: if ($old_entry{$user} ne '') {
7546: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7547: } else {
7548: $reply = &del('classlist',[$user],$cdom,$cnum);
7549: }
7550: }
7551: return $result;
7552: }
7553:
7554: sub format_name {
7555: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7556: my $name;
7557: if ($first ne 'lastname') {
7558: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7559: } else {
7560: if ($lastname=~/\S/) {
7561: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7562: $name=~s/\s+,/,/;
7563: } else {
7564: $name.= $firstname.' '.$middlename.' '.$generation;
7565: }
7566: }
7567: $name=~s/^\s+//;
7568: $name=~s/\s+$//;
7569: $name=~s/\s+/ /g;
7570: return $name;
7571: }
7572:
7573: # ------------------------------------------------- Write to course preferences
7574:
7575: sub writecoursepref {
7576: my ($courseid,%prefs)=@_;
7577: $courseid=~s/^\///;
7578: $courseid=~s/\_/\//g;
7579: my ($cdomain,$cnum)=split(/\//,$courseid);
7580: my $chome=homeserver($cnum,$cdomain);
7581: if (($chome eq '') || ($chome eq 'no_host')) {
7582: return 'error: no such course';
7583: }
7584: my $cstring='';
7585: foreach my $pref (keys(%prefs)) {
7586: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7587: }
7588: $cstring=~s/\&$//;
7589: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7590: }
7591:
7592: # ---------------------------------------------------------- Make/modify course
7593:
7594: sub createcourse {
7595: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7596: $course_owner,$crstype,$cnum,$context,$category)=@_;
7597: $url=&declutter($url);
7598: my $cid='';
7599: if ($context eq 'requestcourses') {
7600: my $can_create = 0;
7601: my ($ownername,$ownerdom) = split(':',$course_owner);
7602: if ($udom eq $ownerdom) {
7603: if (&usertools_access($ownername,$ownerdom,$category,undef,
7604: $context)) {
7605: $can_create = 1;
7606: }
7607: } else {
7608: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7609: $category);
7610: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7611: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7612: if (@curr > 0) {
7613: my @options = qw(approval validate autolimit);
7614: my $optregex = join('|',@options);
7615: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7616: $can_create = 1;
7617: }
7618: }
7619: }
7620: }
7621: if ($can_create) {
7622: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7623: unless (&allowed('ccc',$udom)) {
7624: return 'refused';
7625: }
7626: }
7627: } else {
7628: return 'refused';
7629: }
7630: } elsif (!&allowed('ccc',$udom)) {
7631: return 'refused';
7632: }
7633: # --------------------------------------------------------------- Get Unique ID
7634: my $uname;
7635: if ($cnum =~ /^$match_courseid$/) {
7636: my $chome=&homeserver($cnum,$udom,'true');
7637: if (($chome eq '') || ($chome eq 'no_host')) {
7638: $uname = $cnum;
7639: } else {
7640: $uname = &generate_coursenum($udom,$crstype);
7641: }
7642: } else {
7643: $uname = &generate_coursenum($udom,$crstype);
7644: }
7645: return $uname if ($uname =~ /^error/);
7646: # -------------------------------------------------- Check supplied server name
7647: if (!defined($course_server)) {
7648: if (defined(&domain($udom,'primary'))) {
7649: $course_server = &domain($udom,'primary');
7650: } else {
7651: $course_server = $env{'user.home'};
7652: }
7653: }
7654: my %host_servers =
7655: &Apache::lonnet::get_servers($udom,'library');
7656: unless ($host_servers{$course_server}) {
7657: return 'error: invalid home server for course: '.$course_server;
7658: }
7659: # ------------------------------------------------------------- Make the course
7660: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
7661: $course_server);
7662: unless ($reply eq 'ok') { return 'error: '.$reply; }
7663: my $uhome=&homeserver($uname,$udom,'true');
7664: if (($uhome eq '') || ($uhome eq 'no_host')) {
7665: return 'error: no such course';
7666: }
7667: # ----------------------------------------------------------------- Course made
7668: # log existence
7669: my $now = time;
7670: my $newcourse = {
7671: $udom.'_'.$uname => {
7672: description => $description,
7673: inst_code => $inst_code,
7674: owner => $course_owner,
7675: type => $crstype,
7676: creator => $env{'user.name'}.':'.
7677: $env{'user.domain'},
7678: created => $now,
7679: context => $context,
7680: },
7681: };
7682: &courseidput($udom,$newcourse,$uhome,'notime');
7683: # set toplevel url
7684: my $topurl=$url;
7685: unless ($nonstandard) {
7686: # ------------------------------------------ For standard courses, make top url
7687: my $mapurl=&clutter($url);
7688: if ($mapurl eq '/res/') { $mapurl=''; }
7689: $env{'form.initmap'}=(<<ENDINITMAP);
7690: <map>
7691: <resource id="1" type="start"></resource>
7692: <resource id="2" src="$mapurl"></resource>
7693: <resource id="3" type="finish"></resource>
7694: <link index="1" from="1" to="2"></link>
7695: <link index="2" from="2" to="3"></link>
7696: </map>
7697: ENDINITMAP
7698: $topurl=&declutter(
7699: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
7700: );
7701: }
7702: # ----------------------------------------------------------- Write preferences
7703: &writecoursepref($udom.'_'.$uname,
7704: ('description' => $description,
7705: 'url' => $topurl,
7706: 'internal.creator' => $env{'user.name'}.':'.
7707: $env{'user.domain'},
7708: 'internal.created' => $now,
7709: 'internal.creationcontext' => $context)
7710: );
7711: return '/'.$udom.'/'.$uname;
7712: }
7713:
7714: # ------------------------------------------------------------------- Create ID
7715: sub generate_coursenum {
7716: my ($udom,$crstype) = @_;
7717: my $domdesc = &domain($udom);
7718: return 'error: invalid domain' if ($domdesc eq '');
7719: my $first;
7720: if ($crstype eq 'Community') {
7721: $first = '0';
7722: } else {
7723: $first = int(1+rand(9));
7724: }
7725: my $uname=$first.
7726: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7727: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7728: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7729: # ----------------------------------------------- Make sure that does not exist
7730: my $uhome=&homeserver($uname,$udom,'true');
7731: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7732: if ($crstype eq 'Community') {
7733: $first = '0';
7734: } else {
7735: $first = int(1+rand(9));
7736: }
7737: $uname=$first.
7738: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7739: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7740: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7741: $uhome=&homeserver($uname,$udom,'true');
7742: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7743: return 'error: unable to generate unique course-ID';
7744: }
7745: }
7746: return $uname;
7747: }
7748:
7749: sub is_course {
7750: my ($cdom,$cnum) = @_;
7751: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
7752: undef,'.');
7753: if (exists($courses{$cdom.'_'.$cnum})) {
7754: return 1;
7755: }
7756: return 0;
7757: }
7758:
7759: sub store_userdata {
7760: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
7761: my $result;
7762: if ($datakey ne '') {
7763: if (ref($storehash) eq 'HASH') {
7764: if ($udom eq '' || $uname eq '') {
7765: $udom = $env{'user.domain'};
7766: $uname = $env{'user.name'};
7767: }
7768: my $uhome=&homeserver($uname,$udom);
7769: if (($uhome eq '') || ($uhome eq 'no_host')) {
7770: $result = 'error: no_host';
7771: } else {
7772: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7773: $storehash->{'host'} = $perlvar{'lonHostID'};
7774:
7775: my $namevalue='';
7776: foreach my $key (keys(%{$storehash})) {
7777: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7778: }
7779: $namevalue=~s/\&$//;
7780: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7781: $namevalue,$uhome);
7782: }
7783: } else {
7784: $result = 'error: data to store was not a hash reference';
7785: }
7786: } else {
7787: $result= 'error: invalid requestkey';
7788: }
7789: return $result;
7790: }
7791:
7792: # ---------------------------------------------------------- Assign Custom Role
7793:
7794: sub assigncustomrole {
7795: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
7796: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
7797: $end,$start,$deleteflag,$selfenroll,$context);
7798: }
7799:
7800: # ----------------------------------------------------------------- Revoke Role
7801:
7802: sub revokerole {
7803: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
7804: my $now=time;
7805: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
7806: }
7807:
7808: # ---------------------------------------------------------- Revoke Custom Role
7809:
7810: sub revokecustomrole {
7811: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
7812: my $now=time;
7813: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
7814: $deleteflag,$selfenroll,$context);
7815: }
7816:
7817: # ------------------------------------------------------------ Disk usage
7818: sub diskusage {
7819: my ($udom,$uname,$directorypath,$getpropath)=@_;
7820: $directorypath =~ s/\/$//;
7821: my $listing=&reply('du2:'.&escape($directorypath).':'
7822: .&escape($getpropath).':'.&escape($uname).':'
7823: .&escape($udom),homeserver($uname,$udom));
7824: if ($listing eq 'unknown_cmd') {
7825: if ($getpropath) {
7826: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7827: }
7828: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7829: }
7830: return $listing;
7831: }
7832:
7833: sub is_locked {
7834: my ($file_name, $domain, $user, $which) = @_;
7835: my @check;
7836: my $is_locked;
7837: push (@check,$file_name);
7838: my %locked = &get('file_permissions',\@check,
7839: $env{'user.domain'},$env{'user.name'});
7840: my ($tmp)=keys(%locked);
7841: if ($tmp=~/^error:/) { undef(%locked); }
7842:
7843: if (ref($locked{$file_name}) eq 'ARRAY') {
7844: $is_locked = 'false';
7845: foreach my $entry (@{$locked{$file_name}}) {
7846: if (ref($entry) eq 'ARRAY') {
7847: $is_locked = 'true';
7848: if (ref($which) eq 'ARRAY') {
7849: push(@{$which},$entry);
7850: } else {
7851: last;
7852: }
7853: }
7854: }
7855: } else {
7856: $is_locked = 'false';
7857: }
7858: return $is_locked;
7859: }
7860:
7861: sub declutter_portfile {
7862: my ($file) = @_;
7863: $file =~ s{^(/portfolio/|portfolio/)}{/};
7864: return $file;
7865: }
7866:
7867: # ------------------------------------------------------------- Mark as Read Only
7868:
7869: sub mark_as_readonly {
7870: my ($domain,$user,$files,$what) = @_;
7871: my %current_permissions = &dump('file_permissions',$domain,$user);
7872: my ($tmp)=keys(%current_permissions);
7873: if ($tmp=~/^error:/) { undef(%current_permissions); }
7874: foreach my $file (@{$files}) {
7875: $file = &declutter_portfile($file);
7876: push(@{$current_permissions{$file}},$what);
7877: }
7878: &put('file_permissions',\%current_permissions,$domain,$user);
7879: return;
7880: }
7881:
7882: # ------------------------------------------------------------Save Selected Files
7883:
7884: sub save_selected_files {
7885: my ($user, $path, @files) = @_;
7886: my $filename = $user."savedfiles";
7887: my @other_files = &files_not_in_path($user, $path);
7888: open (OUT, '>'.$tmpdir.$filename);
7889: foreach my $file (@files) {
7890: print (OUT $env{'form.currentpath'}.$file."\n");
7891: }
7892: foreach my $file (@other_files) {
7893: print (OUT $file."\n");
7894: }
7895: close (OUT);
7896: return 'ok';
7897: }
7898:
7899: sub clear_selected_files {
7900: my ($user) = @_;
7901: my $filename = $user."savedfiles";
7902: open (OUT, '>'.LONCAPA::tempdir().$filename);
7903: print (OUT undef);
7904: close (OUT);
7905: return ("ok");
7906: }
7907:
7908: sub files_in_path {
7909: my ($user, $path) = @_;
7910: my $filename = $user."savedfiles";
7911: my %return_files;
7912: open (IN, '<'.LONCAPA::tempdir().$filename);
7913: while (my $line_in = <IN>) {
7914: chomp ($line_in);
7915: my @paths_and_file = split (m!/!, $line_in);
7916: my $file_part = pop (@paths_and_file);
7917: my $path_part = join ('/', @paths_and_file);
7918: $path_part.='/';
7919: my $path_and_file = $path_part.$file_part;
7920: if ($path_part eq $path) {
7921: $return_files{$file_part}= 'selected';
7922: }
7923: }
7924: close (IN);
7925: return (\%return_files);
7926: }
7927:
7928: # called in portfolio select mode, to show files selected NOT in current directory
7929: sub files_not_in_path {
7930: my ($user, $path) = @_;
7931: my $filename = $user."savedfiles";
7932: my @return_files;
7933: my $path_part;
7934: open(IN, '<'.LONCAPA::.$filename);
7935: while (my $line = <IN>) {
7936: #ok, I know it's clunky, but I want it to work
7937: my @paths_and_file = split(m|/|, $line);
7938: my $file_part = pop(@paths_and_file);
7939: chomp($file_part);
7940: my $path_part = join('/', @paths_and_file);
7941: $path_part .= '/';
7942: my $path_and_file = $path_part.$file_part;
7943: if ($path_part ne $path) {
7944: push(@return_files, ($path_and_file));
7945: }
7946: }
7947: close(OUT);
7948: return (@return_files);
7949: }
7950:
7951: #----------------------------------------------Get portfolio file permissions
7952:
7953: sub get_portfile_permissions {
7954: my ($domain,$user) = @_;
7955: my %current_permissions = &dump('file_permissions',$domain,$user);
7956: my ($tmp)=keys(%current_permissions);
7957: if ($tmp=~/^error:/) { undef(%current_permissions); }
7958: return \%current_permissions;
7959: }
7960:
7961: #---------------------------------------------Get portfolio file access controls
7962:
7963: sub get_access_controls {
7964: my ($current_permissions,$group,$file) = @_;
7965: my %access;
7966: my $real_file = $file;
7967: $file =~ s/\.meta$//;
7968: if (defined($file)) {
7969: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7970: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
7971: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
7972: }
7973: }
7974: } else {
7975: foreach my $key (keys(%{$current_permissions})) {
7976: if ($key =~ /\0accesscontrol$/) {
7977: if (defined($group)) {
7978: if ($key !~ m-^\Q$group\E/-) {
7979: next;
7980: }
7981: }
7982: my ($fullpath) = split(/\0/,$key);
7983: if (ref($$current_permissions{$key}) eq 'HASH') {
7984: foreach my $control (keys(%{$$current_permissions{$key}})) {
7985: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7986: }
7987: }
7988: }
7989: }
7990: }
7991: return %access;
7992: }
7993:
7994: sub modify_access_controls {
7995: my ($file_name,$changes,$domain,$user)=@_;
7996: my ($outcome,$deloutcome);
7997: my %store_permissions;
7998: my %new_values;
7999: my %new_control;
8000: my %translation;
8001: my @deletions = ();
8002: my $now = time;
8003: if (exists($$changes{'activate'})) {
8004: if (ref($$changes{'activate'}) eq 'HASH') {
8005: my @newitems = sort(keys(%{$$changes{'activate'}}));
8006: my $numnew = scalar(@newitems);
8007: for (my $i=0; $i<$numnew; $i++) {
8008: my $newkey = $newitems[$i];
8009: my $newid = &Apache::loncommon::get_cgi_id();
8010: if ($newkey =~ /^\d+:/) {
8011: $newkey =~ s/^(\d+)/$newid/;
8012: $translation{$1} = $newid;
8013: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8014: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8015: $translation{$1} = $newid;
8016: }
8017: $new_values{$file_name."\0".$newkey} =
8018: $$changes{'activate'}{$newitems[$i]};
8019: $new_control{$newkey} = $now;
8020: }
8021: }
8022: }
8023: my %todelete;
8024: my %changed_items;
8025: foreach my $action ('delete','update') {
8026: if (exists($$changes{$action})) {
8027: if (ref($$changes{$action}) eq 'HASH') {
8028: foreach my $key (keys(%{$$changes{$action}})) {
8029: my ($itemnum) = ($key =~ /^([^:]+):/);
8030: if ($action eq 'delete') {
8031: $todelete{$itemnum} = 1;
8032: } else {
8033: $changed_items{$itemnum} = $key;
8034: }
8035: }
8036: }
8037: }
8038: }
8039: # get lock on access controls for file.
8040: my $lockhash = {
8041: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8042: ':'.$env{'user.domain'},
8043: };
8044: my $tries = 0;
8045: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8046:
8047: while (($gotlock ne 'ok') && $tries <3) {
8048: $tries ++;
8049: sleep 1;
8050: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8051: }
8052: if ($gotlock eq 'ok') {
8053: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8054: my ($tmp)=keys(%curr_permissions);
8055: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8056: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8057: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8058: if (ref($curr_controls) eq 'HASH') {
8059: foreach my $control_item (keys(%{$curr_controls})) {
8060: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8061: if (defined($todelete{$itemnum})) {
8062: push(@deletions,$file_name."\0".$control_item);
8063: } else {
8064: if (defined($changed_items{$itemnum})) {
8065: $new_control{$changed_items{$itemnum}} = $now;
8066: push(@deletions,$file_name."\0".$control_item);
8067: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8068: } else {
8069: $new_control{$control_item} = $$curr_controls{$control_item};
8070: }
8071: }
8072: }
8073: }
8074: }
8075: my ($group);
8076: if (&is_course($domain,$user)) {
8077: ($group,my $file) = split(/\//,$file_name,2);
8078: }
8079: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8080: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8081: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8082: # remove lock
8083: my @del_lock = ($file_name."\0".'locked_access_records');
8084: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
8085: my $sqlresult =
8086: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
8087: $group);
8088: } else {
8089: $outcome = "error: could not obtain lockfile\n";
8090: }
8091: return ($outcome,$deloutcome,\%new_values,\%translation);
8092: }
8093:
8094: sub make_public_indefinitely {
8095: my ($requrl) = @_;
8096: my $now = time;
8097: my $action = 'activate';
8098: my $aclnum = 0;
8099: if (&is_portfolio_url($requrl)) {
8100: my (undef,$udom,$unum,$file_name,$group) =
8101: &parse_portfolio_url($requrl);
8102: my $current_perms = &get_portfile_permissions($udom,$unum);
8103: my %access_controls = &get_access_controls($current_perms,
8104: $group,$file_name);
8105: foreach my $key (keys(%{$access_controls{$file_name}})) {
8106: my ($num,$scope,$end,$start) =
8107: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8108: if ($scope eq 'public') {
8109: if ($start <= $now && $end == 0) {
8110: $action = 'none';
8111: } else {
8112: $action = 'update';
8113: $aclnum = $num;
8114: }
8115: last;
8116: }
8117: }
8118: if ($action eq 'none') {
8119: return 'ok';
8120: } else {
8121: my %changes;
8122: my $newend = 0;
8123: my $newstart = $now;
8124: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8125: $changes{$action}{$newkey} = {
8126: type => 'public',
8127: time => {
8128: start => $newstart,
8129: end => $newend,
8130: },
8131: };
8132: my ($outcome,$deloutcome,$new_values,$translation) =
8133: &modify_access_controls($file_name,\%changes,$udom,$unum);
8134: return $outcome;
8135: }
8136: } else {
8137: return 'invalid';
8138: }
8139: }
8140:
8141: #------------------------------------------------------Get Marked as Read Only
8142:
8143: sub get_marked_as_readonly {
8144: my ($domain,$user,$what,$group) = @_;
8145: my $current_permissions = &get_portfile_permissions($domain,$user);
8146: my @readonly_files;
8147: my $cmp1=$what;
8148: if (ref($what)) { $cmp1=join('',@{$what}) };
8149: while (my ($file_name,$value) = each(%{$current_permissions})) {
8150: if (defined($group)) {
8151: if ($file_name !~ m-^\Q$group\E/-) {
8152: next;
8153: }
8154: }
8155: if (ref($value) eq "ARRAY"){
8156: foreach my $stored_what (@{$value}) {
8157: my $cmp2=$stored_what;
8158: if (ref($stored_what) eq 'ARRAY') {
8159: $cmp2=join('',@{$stored_what});
8160: }
8161: if ($cmp1 eq $cmp2) {
8162: push(@readonly_files, $file_name);
8163: last;
8164: } elsif (!defined($what)) {
8165: push(@readonly_files, $file_name);
8166: last;
8167: }
8168: }
8169: }
8170: }
8171: return @readonly_files;
8172: }
8173: #-----------------------------------------------------------Get Marked as Read Only Hash
8174:
8175: sub get_marked_as_readonly_hash {
8176: my ($current_permissions,$group,$what) = @_;
8177: my %readonly_files;
8178: while (my ($file_name,$value) = each(%{$current_permissions})) {
8179: if (defined($group)) {
8180: if ($file_name !~ m-^\Q$group\E/-) {
8181: next;
8182: }
8183: }
8184: if (ref($value) eq "ARRAY"){
8185: foreach my $stored_what (@{$value}) {
8186: if (ref($stored_what) eq 'ARRAY') {
8187: foreach my $lock_descriptor(@{$stored_what}) {
8188: if ($lock_descriptor eq 'graded') {
8189: $readonly_files{$file_name} = 'graded';
8190: } elsif ($lock_descriptor eq 'handback') {
8191: $readonly_files{$file_name} = 'handback';
8192: } else {
8193: if (!exists($readonly_files{$file_name})) {
8194: $readonly_files{$file_name} = 'locked';
8195: }
8196: }
8197: }
8198: }
8199: }
8200: }
8201: }
8202: return %readonly_files;
8203: }
8204: # ------------------------------------------------------------ Unmark as Read Only
8205:
8206: sub unmark_as_readonly {
8207: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8208: # for portfolio submissions, $what contains [$symb,$crsid]
8209: my ($domain,$user,$what,$file_name,$group) = @_;
8210: $file_name = &declutter_portfile($file_name);
8211: my $symb_crs = $what;
8212: if (ref($what)) { $symb_crs=join('',@$what); }
8213: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
8214: my ($tmp)=keys(%current_permissions);
8215: if ($tmp=~/^error:/) { undef(%current_permissions); }
8216: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
8217: foreach my $file (@readonly_files) {
8218: my $clean_file = &declutter_portfile($file);
8219: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
8220: my $current_locks = $current_permissions{$file};
8221: my @new_locks;
8222: my @del_keys;
8223: if (ref($current_locks) eq "ARRAY"){
8224: foreach my $locker (@{$current_locks}) {
8225: my $compare=$locker;
8226: if (ref($locker) eq 'ARRAY') {
8227: $compare=join('',@{$locker});
8228: if ($compare ne $symb_crs) {
8229: push(@new_locks, $locker);
8230: }
8231: }
8232: }
8233: if (scalar(@new_locks) > 0) {
8234: $current_permissions{$file} = \@new_locks;
8235: } else {
8236: push(@del_keys, $file);
8237: &del('file_permissions',\@del_keys, $domain, $user);
8238: delete($current_permissions{$file});
8239: }
8240: }
8241: }
8242: &put('file_permissions',\%current_permissions,$domain,$user);
8243: return;
8244: }
8245:
8246: # ------------------------------------------------------------ Directory lister
8247:
8248: sub dirlist {
8249: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
8250: $uri=~s/^\///;
8251: $uri=~s/\/$//;
8252: my ($udom, $uname);
8253: if ($getuserdir) {
8254: $udom = $userdomain;
8255: $uname = $username;
8256: } else {
8257: (undef,$udom,$uname)=split(/\//,$uri);
8258: if(defined($userdomain)) {
8259: $udom = $userdomain;
8260: }
8261: if(defined($username)) {
8262: $uname = $username;
8263: }
8264: }
8265: my ($dirRoot,$listing,@listing_results);
8266:
8267: $dirRoot = $perlvar{'lonDocRoot'};
8268: if (defined($getpropath)) {
8269: $dirRoot = &propath($udom,$uname);
8270: $dirRoot =~ s/\/$//;
8271: } elsif (defined($getuserdir)) {
8272: my $subdir=$uname.'__';
8273: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8274: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8275: ."/$udom/$subdir/$uname";
8276: } elsif (defined($alternateRoot)) {
8277: $dirRoot = $alternateRoot;
8278: }
8279:
8280: if($udom) {
8281: if($uname) {
8282: my $uhome = &homeserver($uname,$udom);
8283: if ($uhome eq 'no_host') {
8284: return ([],'no_host');
8285: }
8286: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
8287: .$getuserdir.':'.&escape($dirRoot)
8288: .':'.&escape($uname).':'.&escape($udom),$uhome);
8289: if ($listing eq 'unknown_cmd') {
8290: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
8291: } else {
8292: @listing_results = map { &unescape($_); } split(/:/,$listing);
8293: }
8294: if ($listing eq 'unknown_cmd') {
8295: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
8296: @listing_results = split(/:/,$listing);
8297: } else {
8298: @listing_results = map { &unescape($_); } split(/:/,$listing);
8299: }
8300: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8301: ($listing eq 'rejected') || ($listing eq 'refused') ||
8302: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8303: return ([],$listing);
8304: } else {
8305: return (\@listing_results);
8306: }
8307: } elsif(!$alternateRoot) {
8308: my (%allusers,%listerror);
8309: my %servers = &get_servers($udom,'library');
8310: foreach my $tryserver (keys(%servers)) {
8311: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8312: &escape($udom),$tryserver);
8313: if ($listing eq 'unknown_cmd') {
8314: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8315: $udom, $tryserver);
8316: } else {
8317: @listing_results = map { &unescape($_); } split(/:/,$listing);
8318: }
8319: if ($listing eq 'unknown_cmd') {
8320: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8321: $udom, $tryserver);
8322: @listing_results = split(/:/,$listing);
8323: } else {
8324: @listing_results =
8325: map { &unescape($_); } split(/:/,$listing);
8326: }
8327: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8328: ($listing eq 'rejected') || ($listing eq 'refused') ||
8329: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8330: $listerror{$tryserver} = $listing;
8331: } else {
8332: foreach my $line (@listing_results) {
8333: my ($entry) = split(/&/,$line,2);
8334: $allusers{$entry} = 1;
8335: }
8336: }
8337: }
8338: my @alluserslist=();
8339: foreach my $user (sort(keys(%allusers))) {
8340: push(@alluserslist,$user.'&user');
8341: }
8342: return (\@alluserslist);
8343: } else {
8344: return ([],'missing username');
8345: }
8346: } elsif(!defined($getpropath)) {
8347: my $path = $perlvar{'lonDocRoot'}.'/res/';
8348: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8349: return (\@all_domains);
8350: } else {
8351: return ([],'missing domain');
8352: }
8353: }
8354:
8355: # --------------------------------------------- GetFileTimestamp
8356: # This function utilizes dirlist and returns the date stamp for
8357: # when it was last modified. It will also return an error of -1
8358: # if an error occurs
8359:
8360: sub GetFileTimestamp {
8361: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
8362: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8363: $studentName = &LONCAPA::clean_username($studentName);
8364: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8365: undef,$getuserdir);
8366: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8367: return -1;
8368: }
8369: if (ref($fileref) eq 'ARRAY') {
8370: my @stats = split('&',$fileref->[0]);
8371: # @stats contains first the filename, then the stat output
8372: return $stats[10]; # so this is 10 instead of 9.
8373: } else {
8374: return -1;
8375: }
8376: }
8377:
8378: sub stat_file {
8379: my ($uri) = @_;
8380: $uri = &clutter_with_no_wrapper($uri);
8381:
8382: my ($udom,$uname,$file);
8383: if ($uri =~ m-^/(uploaded|editupload)/-) {
8384: ($udom,$uname,$file) =
8385: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8386: $file = 'userfiles/'.$file;
8387: }
8388: if ($uri =~ m-^/res/-) {
8389: ($udom,$uname) =
8390: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8391: $file = $uri;
8392: }
8393:
8394: if (!$udom || !$uname || !$file) {
8395: # unable to handle the uri
8396: return ();
8397: }
8398: my $getpropath;
8399: if ($file =~ /^userfiles\//) {
8400: $getpropath = 1;
8401: }
8402: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8403: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8404: return ();
8405: } else {
8406: if (ref($listref) eq 'ARRAY') {
8407: my @stats = split('&',$listref->[0]);
8408: shift(@stats); #filename is first
8409: return @stats;
8410: }
8411: }
8412: return ();
8413: }
8414:
8415: # -------------------------------------------------------- Value of a Condition
8416:
8417: # gets the value of a specific preevaluated condition
8418: # stored in the string $env{user.state.<cid>}
8419: # or looks up a condition reference in the bighash and if if hasn't
8420: # already been evaluated recurses into docondval to get the value of
8421: # the condition, then memoizing it to
8422: # $env{user.state.<cid>.<condition>}
8423: sub directcondval {
8424: my $number=shift;
8425: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8426: &Apache::lonuserstate::evalstate();
8427: }
8428: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8429: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8430: } elsif ($number =~ /^_/) {
8431: my $sub_condition;
8432: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8433: &GDBM_READER(),0640)) {
8434: $sub_condition=$bighash{'conditions'.$number};
8435: untie(%bighash);
8436: }
8437: my $value = &docondval($sub_condition);
8438: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8439: return $value;
8440: }
8441: if ($env{'user.state.'.$env{'request.course.id'}}) {
8442: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8443: } else {
8444: return 2;
8445: }
8446: }
8447:
8448: # get the collection of conditions for this resource
8449: sub condval {
8450: my $condidx=shift;
8451: my $allpathcond='';
8452: foreach my $cond (split(/\|/,$condidx)) {
8453: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8454: $allpathcond.=
8455: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8456: }
8457: }
8458: $allpathcond=~s/\|$//;
8459: return &docondval($allpathcond);
8460: }
8461:
8462: #evaluates an expression of conditions
8463: sub docondval {
8464: my ($allpathcond) = @_;
8465: my $result=0;
8466: if ($env{'request.course.id'}
8467: && defined($allpathcond)) {
8468: my $operand='|';
8469: my @stack;
8470: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8471: if ($chunk eq '(') {
8472: push @stack,($operand,$result);
8473: } elsif ($chunk eq ')') {
8474: my $before=pop @stack;
8475: if (pop @stack eq '&') {
8476: $result=$result>$before?$before:$result;
8477: } else {
8478: $result=$result>$before?$result:$before;
8479: }
8480: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8481: $operand=$chunk;
8482: } else {
8483: my $new=directcondval($chunk);
8484: if ($operand eq '&') {
8485: $result=$result>$new?$new:$result;
8486: } else {
8487: $result=$result>$new?$result:$new;
8488: }
8489: }
8490: }
8491: }
8492: return $result;
8493: }
8494:
8495: # ---------------------------------------------------- Devalidate courseresdata
8496:
8497: sub devalidatecourseresdata {
8498: my ($coursenum,$coursedomain)=@_;
8499: my $hashid=$coursenum.':'.$coursedomain;
8500: &devalidate_cache_new('courseres',$hashid);
8501: }
8502:
8503:
8504: # --------------------------------------------------- Course Resourcedata Query
8505: #
8506: # Parameters:
8507: # $coursenum - Number of the course.
8508: # $coursedomain - Domain at which the course was created.
8509: # Returns:
8510: # A hash of the course parameters along (I think) with timestamps
8511: # and version info.
8512:
8513: sub get_courseresdata {
8514: my ($coursenum,$coursedomain)=@_;
8515: my $coursehom=&homeserver($coursenum,$coursedomain);
8516: my $hashid=$coursenum.':'.$coursedomain;
8517: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8518: my %dumpreply;
8519: unless (defined($cached)) {
8520: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8521: $result=\%dumpreply;
8522: my ($tmp) = keys(%dumpreply);
8523: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8524: &do_cache_new('courseres',$hashid,$result,600);
8525: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8526: return $tmp;
8527: } elsif ($tmp =~ /^(error)/) {
8528: $result=undef;
8529: &do_cache_new('courseres',$hashid,$result,600);
8530: }
8531: }
8532: return $result;
8533: }
8534:
8535: sub devalidateuserresdata {
8536: my ($uname,$udom)=@_;
8537: my $hashid="$udom:$uname";
8538: &devalidate_cache_new('userres',$hashid);
8539: }
8540:
8541: sub get_userresdata {
8542: my ($uname,$udom)=@_;
8543: #most student don\'t have any data set, check if there is some data
8544: if (&EXT_cache_status($udom,$uname)) { return undef; }
8545:
8546: my $hashid="$udom:$uname";
8547: my ($result,$cached)=&is_cached_new('userres',$hashid);
8548: if (!defined($cached)) {
8549: my %resourcedata=&dump('resourcedata',$udom,$uname);
8550: $result=\%resourcedata;
8551: &do_cache_new('userres',$hashid,$result,600);
8552: }
8553: my ($tmp)=keys(%$result);
8554: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8555: return $result;
8556: }
8557: #error 2 occurs when the .db doesn't exist
8558: if ($tmp!~/error: 2 /) {
8559: &logthis("<font color=\"blue\">WARNING:".
8560: " Trying to get resource data for ".
8561: $uname." at ".$udom.": ".
8562: $tmp."</font>");
8563: } elsif ($tmp=~/error: 2 /) {
8564: #&EXT_cache_set($udom,$uname);
8565: &do_cache_new('userres',$hashid,undef,600);
8566: undef($tmp); # not really an error so don't send it back
8567: }
8568: return $tmp;
8569: }
8570: #----------------------------------------------- resdata - return resource data
8571: # Purpose:
8572: # Return resource data for either users or for a course.
8573: # Parameters:
8574: # $name - Course/user name.
8575: # $domain - Name of the domain the user/course is registered on.
8576: # $type - Type of thing $name is (must be 'course' or 'user'
8577: # @which - Array of names of resources desired.
8578: # Returns:
8579: # The value of the first reasource in @which that is found in the
8580: # resource hash.
8581: # Exceptional Conditions:
8582: # If the $type passed in is not valid (not the string 'course' or
8583: # 'user', an undefined reference is returned.
8584: # If none of the resources are found, an undef is returned
8585: sub resdata {
8586: my ($name,$domain,$type,@which)=@_;
8587: my $result;
8588: if ($type eq 'course') {
8589: $result=&get_courseresdata($name,$domain);
8590: } elsif ($type eq 'user') {
8591: $result=&get_userresdata($name,$domain);
8592: }
8593: if (!ref($result)) { return $result; }
8594: foreach my $item (@which) {
8595: if (defined($result->{$item->[0]})) {
8596: return [$result->{$item->[0]},$item->[1]];
8597: }
8598: }
8599: return undef;
8600: }
8601:
8602: #
8603: # EXT resource caching routines
8604: #
8605:
8606: sub clear_EXT_cache_status {
8607: &delenv('cache.EXT.');
8608: }
8609:
8610: sub EXT_cache_status {
8611: my ($target_domain,$target_user) = @_;
8612: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8613: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8614: # We know already the user has no data
8615: return 1;
8616: } else {
8617: return 0;
8618: }
8619: }
8620:
8621: sub EXT_cache_set {
8622: my ($target_domain,$target_user) = @_;
8623: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8624: #&appenv({$cachename => time});
8625: }
8626:
8627: # --------------------------------------------------------- Value of a Variable
8628: sub EXT {
8629:
8630: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8631: unless ($varname) { return ''; }
8632: #get real user name/domain, courseid and symb
8633: my $courseid;
8634: my $publicuser;
8635: if ($symbparm) {
8636: $symbparm=&get_symb_from_alias($symbparm);
8637: }
8638: if (!($uname && $udom)) {
8639: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8640: if (!$symbparm) { $symbparm=$cursymb; }
8641: } else {
8642: $courseid=$env{'request.course.id'};
8643: }
8644: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8645: my $rest;
8646: if (defined($therest[0])) {
8647: $rest=join('.',@therest);
8648: } else {
8649: $rest='';
8650: }
8651:
8652: my $qualifierrest=$qualifier;
8653: if ($rest) { $qualifierrest.='.'.$rest; }
8654: my $spacequalifierrest=$space;
8655: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
8656: if ($realm eq 'user') {
8657: # --------------------------------------------------------------- user.resource
8658: if ($space eq 'resource') {
8659: if ( (defined($Apache::lonhomework::parsing_a_problem)
8660: || defined($Apache::lonhomework::parsing_a_task))
8661: &&
8662: ($symbparm eq &symbread()) ) {
8663: # if we are in the middle of processing the resource the
8664: # get the value we are planning on committing
8665: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8666: return $Apache::lonhomework::results{$qualifierrest};
8667: } else {
8668: return $Apache::lonhomework::history{$qualifierrest};
8669: }
8670: } else {
8671: my %restored;
8672: if ($publicuser || $env{'request.state'} eq 'construct') {
8673: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8674: } else {
8675: %restored=&restore($symbparm,$courseid,$udom,$uname);
8676: }
8677: return $restored{$qualifierrest};
8678: }
8679: # ----------------------------------------------------------------- user.access
8680: } elsif ($space eq 'access') {
8681: # FIXME - not supporting calls for a specific user
8682: return &allowed($qualifier,$rest);
8683: # ------------------------------------------ user.preferences, user.environment
8684: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
8685: if (($uname eq $env{'user.name'}) &&
8686: ($udom eq $env{'user.domain'})) {
8687: return $env{join('.',('environment',$qualifierrest))};
8688: } else {
8689: my %returnhash;
8690: if (!$publicuser) {
8691: %returnhash=&userenvironment($udom,$uname,
8692: $qualifierrest);
8693: }
8694: return $returnhash{$qualifierrest};
8695: }
8696: # ----------------------------------------------------------------- user.course
8697: } elsif ($space eq 'course') {
8698: # FIXME - not supporting calls for a specific user
8699: return $env{join('.',('request.course',$qualifier))};
8700: # ------------------------------------------------------------------- user.role
8701: } elsif ($space eq 'role') {
8702: # FIXME - not supporting calls for a specific user
8703: my ($role,$where)=split(/\./,$env{'request.role'});
8704: if ($qualifier eq 'value') {
8705: return $role;
8706: } elsif ($qualifier eq 'extent') {
8707: return $where;
8708: }
8709: # ----------------------------------------------------------------- user.domain
8710: } elsif ($space eq 'domain') {
8711: return $udom;
8712: # ------------------------------------------------------------------- user.name
8713: } elsif ($space eq 'name') {
8714: return $uname;
8715: # ---------------------------------------------------- Any other user namespace
8716: } else {
8717: my %reply;
8718: if (!$publicuser) {
8719: %reply=&get($space,[$qualifierrest],$udom,$uname);
8720: }
8721: return $reply{$qualifierrest};
8722: }
8723: } elsif ($realm eq 'query') {
8724: # ---------------------------------------------- pull stuff out of query string
8725: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8726: [$spacequalifierrest]);
8727: return $env{'form.'.$spacequalifierrest};
8728: } elsif ($realm eq 'request') {
8729: # ------------------------------------------------------------- request.browser
8730: if ($space eq 'browser') {
8731: return $env{'browser.'.$qualifier};
8732: # ------------------------------------------------------------ request.filename
8733: } else {
8734: return $env{'request.'.$spacequalifierrest};
8735: }
8736: } elsif ($realm eq 'course') {
8737: # ---------------------------------------------------------- course.description
8738: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
8739: } elsif ($realm eq 'resource') {
8740:
8741: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
8742: if (!$symbparm) { $symbparm=&symbread(); }
8743: }
8744:
8745: if ($space eq 'title') {
8746: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8747: return &gettitle($symbparm);
8748: }
8749:
8750: if ($space eq 'map') {
8751: my ($map) = &decode_symb($symbparm);
8752: return &symbread($map);
8753: }
8754: if ($space eq 'filename') {
8755: if ($symbparm) {
8756: return &clutter((&decode_symb($symbparm))[2]);
8757: }
8758: return &hreflocation('',$env{'request.filename'});
8759: }
8760:
8761: my ($section, $group, @groups);
8762: my ($courselevelm,$courselevel);
8763: if ($symbparm && defined($courseid) &&
8764: $courseid eq $env{'request.course.id'}) {
8765:
8766: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
8767:
8768: # ----------------------------------------------------- Cascading lookup scheme
8769: my $symbp=$symbparm;
8770: my $mapp=&deversion((&decode_symb($symbp))[0]);
8771:
8772: my $symbparm=$symbp.'.'.$spacequalifierrest;
8773: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8774:
8775: if (($env{'user.name'} eq $uname) &&
8776: ($env{'user.domain'} eq $udom)) {
8777: $section=$env{'request.course.sec'};
8778: @groups = split(/:/,$env{'request.course.groups'});
8779: @groups=&sort_course_groups($courseid,@groups);
8780: } else {
8781: if (! defined($usection)) {
8782: $section=&getsection($udom,$uname,$courseid);
8783: } else {
8784: $section = $usection;
8785: }
8786: @groups = &get_users_groups($udom,$uname,$courseid);
8787: }
8788:
8789: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8790: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8791: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8792:
8793: $courselevel=$courseid.'.'.$spacequalifierrest;
8794: my $courselevelr=$courseid.'.'.$symbparm;
8795: $courselevelm=$courseid.'.'.$mapparm;
8796:
8797: # ----------------------------------------------------------- first, check user
8798:
8799: my $userreply=&resdata($uname,$udom,'user',
8800: ([$courselevelr,'resource'],
8801: [$courselevelm,'map' ],
8802: [$courselevel, 'course' ]));
8803: if (defined($userreply)) { return &get_reply($userreply); }
8804:
8805: # ------------------------------------------------ second, check some of course
8806: my $coursereply;
8807: if (@groups > 0) {
8808: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8809: $mapparm,$spacequalifierrest);
8810: if (defined($coursereply)) { return &get_reply($coursereply); }
8811: }
8812:
8813: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8814: $env{'course.'.$courseid.'.domain'},
8815: 'course',
8816: ([$seclevelr, 'resource'],
8817: [$seclevelm, 'map' ],
8818: [$seclevel, 'course' ],
8819: [$courselevelr,'resource']));
8820: if (defined($coursereply)) { return &get_reply($coursereply); }
8821:
8822: # ------------------------------------------------------ third, check map parms
8823: my %parmhash=();
8824: my $thisparm='';
8825: if (tie(%parmhash,'GDBM_File',
8826: $env{'request.course.fn'}.'_parms.db',
8827: &GDBM_READER(),0640)) {
8828: $thisparm=$parmhash{$symbparm};
8829: untie(%parmhash);
8830: }
8831: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
8832: }
8833: # ------------------------------------------ fourth, look in resource metadata
8834:
8835: $spacequalifierrest=~s/\./\_/;
8836: my $filename;
8837: if (!$symbparm) { $symbparm=&symbread(); }
8838: if ($symbparm) {
8839: $filename=(&decode_symb($symbparm))[2];
8840: } else {
8841: $filename=$env{'request.filename'};
8842: }
8843: my $metadata=&metadata($filename,$spacequalifierrest);
8844: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8845: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
8846: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8847:
8848: # ---------------------------------------------- fourth, look in rest of course
8849: if ($symbparm && defined($courseid) &&
8850: $courseid eq $env{'request.course.id'}) {
8851: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8852: $env{'course.'.$courseid.'.domain'},
8853: 'course',
8854: ([$courselevelm,'map' ],
8855: [$courselevel, 'course']));
8856: if (defined($coursereply)) { return &get_reply($coursereply); }
8857: }
8858: # ------------------------------------------------------------------ Cascade up
8859: unless ($space eq '0') {
8860: my @parts=split(/_/,$space);
8861: my $id=pop(@parts);
8862: my $part=join('_',@parts);
8863: if ($part eq '') { $part='0'; }
8864: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
8865: $symbparm,$udom,$uname,$section,1);
8866: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
8867: }
8868: if ($recurse) { return undef; }
8869: my $pack_def=&packages_tab_default($filename,$varname);
8870: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
8871: # ---------------------------------------------------- Any other user namespace
8872: } elsif ($realm eq 'environment') {
8873: # ----------------------------------------------------------------- environment
8874: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8875: return $env{'environment.'.$spacequalifierrest};
8876: } else {
8877: if ($uname eq 'anonymous' && $udom eq '') {
8878: return '';
8879: }
8880: my %returnhash=&userenvironment($udom,$uname,
8881: $spacequalifierrest);
8882: return $returnhash{$spacequalifierrest};
8883: }
8884: } elsif ($realm eq 'system') {
8885: # ----------------------------------------------------------------- system.time
8886: if ($space eq 'time') {
8887: return time;
8888: }
8889: } elsif ($realm eq 'server') {
8890: # ----------------------------------------------------------------- system.time
8891: if ($space eq 'name') {
8892: return $ENV{'SERVER_NAME'};
8893: }
8894: }
8895: return '';
8896: }
8897:
8898: sub get_reply {
8899: my ($reply_value) = @_;
8900: if (ref($reply_value) eq 'ARRAY') {
8901: if (wantarray) {
8902: return @$reply_value;
8903: }
8904: return $reply_value->[0];
8905: } else {
8906: return $reply_value;
8907: }
8908: }
8909:
8910: sub check_group_parms {
8911: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8912: my @groupitems = ();
8913: my $resultitem;
8914: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
8915: foreach my $group (@{$groups}) {
8916: foreach my $level (@levels) {
8917: my $item = $courseid.'.['.$group.'].'.$level->[0];
8918: push(@groupitems,[$item,$level->[1]]);
8919: }
8920: }
8921: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8922: $env{'course.'.$courseid.'.domain'},
8923: 'course',@groupitems);
8924: return $coursereply;
8925: }
8926:
8927: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
8928: my ($courseid,@groups) = @_;
8929: @groups = sort(@groups);
8930: return @groups;
8931: }
8932:
8933: sub packages_tab_default {
8934: my ($uri,$varname)=@_;
8935: my (undef,$part,$name)=split(/\./,$varname);
8936:
8937: my (@extension,@specifics,$do_default);
8938: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
8939: my ($pack_type,$pack_part)=split(/_/,$package,2);
8940: if ($pack_type eq 'default') {
8941: $do_default=1;
8942: } elsif ($pack_type eq 'extension') {
8943: push(@extension,[$package,$pack_type,$pack_part]);
8944: } elsif ($pack_part eq $part || $pack_type eq 'part') {
8945: # only look at packages defaults for packages that this id is
8946: push(@specifics,[$package,$pack_type,$pack_part]);
8947: }
8948: }
8949: # first look for a package that matches the requested part id
8950: foreach my $package (@specifics) {
8951: my (undef,$pack_type,$pack_part)=@{$package};
8952: next if ($pack_part ne $part);
8953: if (defined($packagetab{"$pack_type&$name&default"})) {
8954: return $packagetab{"$pack_type&$name&default"};
8955: }
8956: }
8957: # look for any possible matching non extension_ package
8958: foreach my $package (@specifics) {
8959: my (undef,$pack_type,$pack_part)=@{$package};
8960: if (defined($packagetab{"$pack_type&$name&default"})) {
8961: return $packagetab{"$pack_type&$name&default"};
8962: }
8963: if ($pack_type eq 'part') { $pack_part='0'; }
8964: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8965: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
8966: }
8967: }
8968: # look for any posible extension_ match
8969: foreach my $package (@extension) {
8970: my ($package,$pack_type)=@{$package};
8971: if (defined($packagetab{"$pack_type&$name&default"})) {
8972: return $packagetab{"$pack_type&$name&default"};
8973: }
8974: if (defined($packagetab{$package."&$name&default"})) {
8975: return $packagetab{$package."&$name&default"};
8976: }
8977: }
8978: # look for a global default setting
8979: if ($do_default && defined($packagetab{"default&$name&default"})) {
8980: return $packagetab{"default&$name&default"};
8981: }
8982: return undef;
8983: }
8984:
8985: sub add_prefix_and_part {
8986: my ($prefix,$part)=@_;
8987: my $keyroot;
8988: if (defined($prefix) && $prefix !~ /^__/) {
8989: # prefix that has a part already
8990: $keyroot=$prefix;
8991: } elsif (defined($prefix)) {
8992: # prefix that is missing a part
8993: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8994: } else {
8995: # no prefix at all
8996: if (defined($part)) { $keyroot='_'.$part; }
8997: }
8998: return $keyroot;
8999: }
9000:
9001: # ---------------------------------------------------------------- Get metadata
9002:
9003: my %metaentry;
9004: my %importedpartids;
9005: sub metadata {
9006: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
9007: $uri=&declutter($uri);
9008: # if it is a non metadata possible uri return quickly
9009: if (($uri eq '') ||
9010: (($uri =~ m|^/*adm/|) &&
9011: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
9012: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
9013: return undef;
9014: }
9015: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
9016: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
9017: return undef;
9018: }
9019: my $filename=$uri;
9020: $uri=~s/\.meta$//;
9021: #
9022: # Is the metadata already cached?
9023: # Look at timestamp of caching
9024: # Everything is cached by the main uri, libraries are never directly cached
9025: #
9026: if (!defined($liburi)) {
9027: my ($result,$cached)=&is_cached_new('meta',$uri);
9028: if (defined($cached)) { return $result->{':'.$what}; }
9029: }
9030: {
9031: # Imported parts would go here
9032: my %importedids=();
9033: my @origfileimportpartids=();
9034: my $importedparts=0;
9035: #
9036: # Is this a recursive call for a library?
9037: #
9038: # if (! exists($metacache{$uri})) {
9039: # $metacache{$uri}={};
9040: # }
9041: my $cachetime = 60*60;
9042: if ($liburi) {
9043: $liburi=&declutter($liburi);
9044: $filename=$liburi;
9045: } else {
9046: &devalidate_cache_new('meta',$uri);
9047: undef(%metaentry);
9048: }
9049: my %metathesekeys=();
9050: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9051: my $metastring;
9052: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
9053: my $which = &hreflocation('','/'.($liburi || $uri));
9054: $metastring =
9055: &Apache::lonnet::ssi_body($which,
9056: ('grade_target' => 'meta'));
9057: $cachetime = 1; # only want this cached in the child not long term
9058: } elsif (($uri !~ m -^(editupload)/-) &&
9059: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9060: my $file=&filelocation('',&clutter($filename));
9061: #push(@{$metaentry{$uri.'.file'}},$file);
9062: $metastring=&getfile($file);
9063: }
9064: my $parser=HTML::LCParser->new(\$metastring);
9065: my $token;
9066: undef %metathesekeys;
9067: while ($token=$parser->get_token) {
9068: if ($token->[0] eq 'S') {
9069: if (defined($token->[2]->{'package'})) {
9070: #
9071: # This is a package - get package info
9072: #
9073: my $package=$token->[2]->{'package'};
9074: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9075: if (defined($token->[2]->{'id'})) {
9076: $keyroot.='_'.$token->[2]->{'id'};
9077: }
9078: if ($metaentry{':packages'}) {
9079: $metaentry{':packages'}.=','.$package.$keyroot;
9080: } else {
9081: $metaentry{':packages'}=$package.$keyroot;
9082: }
9083: foreach my $pack_entry (keys(%packagetab)) {
9084: my $part=$keyroot;
9085: $part=~s/^\_//;
9086: if ($pack_entry=~/^\Q$package\E\&/ ||
9087: $pack_entry=~/^\Q$package\E_0\&/) {
9088: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
9089: # ignore package.tab specified default values
9090: # here &package_tab_default() will fetch those
9091: if ($subp eq 'default') { next; }
9092: my $value=$packagetab{$pack_entry};
9093: my $unikey;
9094: if ($pack =~ /_0$/) {
9095: $unikey='parameter_0_'.$name;
9096: $part=0;
9097: } else {
9098: $unikey='parameter'.$keyroot.'_'.$name;
9099: }
9100: if ($subp eq 'display') {
9101: $value.=' [Part: '.$part.']';
9102: }
9103: $metaentry{':'.$unikey.'.part'}=$part;
9104: $metathesekeys{$unikey}=1;
9105: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9106: $metaentry{':'.$unikey.'.'.$subp}=$value;
9107: }
9108: if (defined($metaentry{':'.$unikey.'.default'})) {
9109: $metaentry{':'.$unikey}=
9110: $metaentry{':'.$unikey.'.default'};
9111: }
9112: }
9113: }
9114: } else {
9115: #
9116: # This is not a package - some other kind of start tag
9117: #
9118: my $entry=$token->[1];
9119: my $unikey='';
9120:
9121: if ($entry eq 'import') {
9122: #
9123: # Importing a library here
9124: #
9125: my $location=$parser->get_text('/import');
9126: my $dir=$filename;
9127: $dir=~s|[^/]*$||;
9128: $location=&filelocation($dir,$location);
9129:
9130: my $importmode=$token->[2]->{'importmode'};
9131: if ($importmode eq 'problem') {
9132: # Import as problem/response
9133: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9134: } elsif ($importmode eq 'part') {
9135: # Import as part(s)
9136: $importedparts=1;
9137: # We need to get the original file and the imported file to get the part order correct
9138: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9139: # Load and inspect original file
9140: if ($#origfileimportpartids<0) {
9141: undef(%importedpartids);
9142: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9143: my $origfile=&getfile($origfilelocation);
9144: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9145: }
9146:
9147: # Load and inspect imported file
9148: my $impfile=&getfile($location);
9149: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9150: if ($#impfilepartids>=0) {
9151: # This problem had parts
9152: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
9153: } else {
9154: # Importing by turning a single problem into a problem part
9155: # It gets the import-tags ID as part-ID
9156: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
9157: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
9158: }
9159: } else {
9160: # Normal import
9161: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9162: if (defined($token->[2]->{'id'})) {
9163: $unikey.='_'.$token->[2]->{'id'};
9164: }
9165: }
9166:
9167: if ($depthcount<20) {
9168: my $metadata =
9169: &metadata($uri,'keys', $location,$unikey,
9170: $depthcount+1);
9171: foreach my $meta (split(',',$metadata)) {
9172: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9173: $metathesekeys{$meta}=1;
9174: }
9175:
9176: }
9177: } else {
9178: #
9179: # Not importing, some other kind of non-package, non-library start tag
9180: #
9181: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9182: if (defined($token->[2]->{'id'})) {
9183: $unikey.='_'.$token->[2]->{'id'};
9184: }
9185: if (defined($token->[2]->{'name'})) {
9186: $unikey.='_'.$token->[2]->{'name'};
9187: }
9188: $metathesekeys{$unikey}=1;
9189: foreach my $param (@{$token->[3]}) {
9190: $metaentry{':'.$unikey.'.'.$param} =
9191: $token->[2]->{$param};
9192: }
9193: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
9194: my $default=$metaentry{':'.$unikey.'.default'};
9195: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9196: # only ws inside the tag, and not in default, so use default
9197: # as value
9198: $metaentry{':'.$unikey}=$default;
9199: } elsif ( $internaltext =~ /\S/ ) {
9200: # something interesting inside the tag
9201: $metaentry{':'.$unikey}=$internaltext;
9202: } else {
9203: # no interesting values, don't set a default
9204: }
9205: # end of not-a-package not-a-library import
9206: }
9207: # end of not-a-package start tag
9208: }
9209: # the next is the end of "start tag"
9210: }
9211: }
9212: my ($extension) = ($uri =~ /\.(\w+)$/);
9213: $extension = lc($extension);
9214: if ($extension eq 'htm') { $extension='html'; }
9215:
9216: foreach my $key (keys(%packagetab)) {
9217: #no specific packages #how's our extension
9218: if ($key!~/^extension_\Q$extension\E&/) { next; }
9219: &metadata_create_package_def($uri,$key,'extension_'.$extension,
9220: \%metathesekeys);
9221: }
9222:
9223: if (!exists($metaentry{':packages'})
9224: || $packagetab{"import_defaults&extension_$extension"}) {
9225: foreach my $key (keys(%packagetab)) {
9226: #no specific packages well let's get default then
9227: if ($key!~/^default&/) { next; }
9228: &metadata_create_package_def($uri,$key,'default',
9229: \%metathesekeys);
9230: }
9231: }
9232: # are there custom rights to evaluate
9233: if ($metaentry{':copyright'} eq 'custom') {
9234:
9235: #
9236: # Importing a rights file here
9237: #
9238: unless ($depthcount) {
9239: my $location=$metaentry{':customdistributionfile'};
9240: my $dir=$filename;
9241: $dir=~s|[^/]*$||;
9242: $location=&filelocation($dir,$location);
9243: my $rights_metadata =
9244: &metadata($uri,'keys',$location,'_rights',
9245: $depthcount+1);
9246: foreach my $rights (split(',',$rights_metadata)) {
9247: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9248: $metathesekeys{$rights}=1;
9249: }
9250: }
9251: }
9252: # uniqifiy package listing
9253: my %seen;
9254: my @uniq_packages =
9255: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9256: $metaentry{':packages'} = join(',',@uniq_packages);
9257:
9258: if ($importedparts) {
9259: # We had imported parts and need to rebuild partorder
9260: $metaentry{':partorder'}='';
9261: $metathesekeys{'partorder'}=1;
9262: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9263: if ($origfileimportpartids[$index] eq 'part') {
9264: # original part, part of the problem
9265: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9266: } else {
9267: # we have imported parts at this position
9268: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9269: }
9270: }
9271: $metaentry{':partorder'}=~s/^\,//;
9272: }
9273:
9274: $metaentry{':keys'} = join(',',keys(%metathesekeys));
9275: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9276: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
9277: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
9278: # this is the end of "was not already recently cached
9279: }
9280: return $metaentry{':'.$what};
9281: }
9282:
9283: sub metadata_create_package_def {
9284: my ($uri,$key,$package,$metathesekeys)=@_;
9285: my ($pack,$name,$subp)=split(/\&/,$key);
9286: if ($subp eq 'default') { next; }
9287:
9288: if (defined($metaentry{':packages'})) {
9289: $metaentry{':packages'}.=','.$package;
9290: } else {
9291: $metaentry{':packages'}=$package;
9292: }
9293: my $value=$packagetab{$key};
9294: my $unikey;
9295: $unikey='parameter_0_'.$name;
9296: $metaentry{':'.$unikey.'.part'}=0;
9297: $$metathesekeys{$unikey}=1;
9298: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9299: $metaentry{':'.$unikey.'.'.$subp}=$value;
9300: }
9301: if (defined($metaentry{':'.$unikey.'.default'})) {
9302: $metaentry{':'.$unikey}=
9303: $metaentry{':'.$unikey.'.default'};
9304: }
9305: }
9306:
9307: sub metadata_generate_part0 {
9308: my ($metadata,$metacache,$uri) = @_;
9309: my %allnames;
9310: foreach my $metakey (keys(%$metadata)) {
9311: if ($metakey=~/^parameter\_(.*)/) {
9312: my $part=$$metacache{':'.$metakey.'.part'};
9313: my $name=$$metacache{':'.$metakey.'.name'};
9314: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
9315: $allnames{$name}=$part;
9316: }
9317: }
9318: }
9319: foreach my $name (keys(%allnames)) {
9320: $$metadata{"parameter_0_$name"}=1;
9321: my $key=":parameter_0_$name";
9322: $$metacache{"$key.part"}='0';
9323: $$metacache{"$key.name"}=$name;
9324: $$metacache{"$key.type"}=$$metacache{':parameter_'.
9325: $allnames{$name}.'_'.$name.
9326: '.type'};
9327: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
9328: '.display'};
9329: my $expr='[Part: '.$allnames{$name}.']';
9330: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
9331: $$metacache{"$key.display"}=$olddis;
9332: }
9333: }
9334:
9335: # ------------------------------------------------------ Devalidate title cache
9336:
9337: sub devalidate_title_cache {
9338: my ($url)=@_;
9339: if (!$env{'request.course.id'}) { return; }
9340: my $symb=&symbread($url);
9341: if (!$symb) { return; }
9342: my $key=$env{'request.course.id'}."\0".$symb;
9343: &devalidate_cache_new('title',$key);
9344: }
9345:
9346: # ------------------------------------------------- Get the title of a course
9347:
9348: sub current_course_title {
9349: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9350: }
9351: # ------------------------------------------------- Get the title of a resource
9352:
9353: sub gettitle {
9354: my $urlsymb=shift;
9355: my $symb=&symbread($urlsymb);
9356: if ($symb) {
9357: my $key=$env{'request.course.id'}."\0".$symb;
9358: my ($result,$cached)=&is_cached_new('title',$key);
9359: if (defined($cached)) {
9360: return $result;
9361: }
9362: my ($map,$resid,$url)=&decode_symb($symb);
9363: my $title='';
9364: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9365: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9366: } else {
9367: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9368: &GDBM_READER(),0640)) {
9369: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9370: $title=$bighash{'title_'.$mapid.'.'.$resid};
9371: untie(%bighash);
9372: }
9373: }
9374: $title=~s/\&colon\;/\:/gs;
9375: if ($title) {
9376: return &do_cache_new('title',$key,$title,600);
9377: }
9378: $urlsymb=$url;
9379: }
9380: my $title=&metadata($urlsymb,'title');
9381: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9382: return $title;
9383: }
9384:
9385: sub get_slot {
9386: my ($which,$cnum,$cdom)=@_;
9387: if (!$cnum || !$cdom) {
9388: (undef,my $courseid)=&whichuser();
9389: $cdom=$env{'course.'.$courseid.'.domain'};
9390: $cnum=$env{'course.'.$courseid.'.num'};
9391: }
9392: my $key=join("\0",'slots',$cdom,$cnum,$which);
9393: my %slotinfo;
9394: if (exists($remembered{$key})) {
9395: $slotinfo{$which} = $remembered{$key};
9396: } else {
9397: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9398: &Apache::lonhomework::showhash(%slotinfo);
9399: my ($tmp)=keys(%slotinfo);
9400: if ($tmp=~/^error:/) { return (); }
9401: $remembered{$key} = $slotinfo{$which};
9402: }
9403: if (ref($slotinfo{$which}) eq 'HASH') {
9404: return %{$slotinfo{$which}};
9405: }
9406: return $slotinfo{$which};
9407: }
9408:
9409: sub get_reservable_slots {
9410: my ($cnum,$cdom,$uname,$udom) = @_;
9411: my $now = time;
9412: my $reservable_info;
9413: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9414: if (exists($remembered{$key})) {
9415: $reservable_info = $remembered{$key};
9416: } else {
9417: my %resv;
9418: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9419: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9420: $reservable_info = \%resv;
9421: $remembered{$key} = $reservable_info;
9422: }
9423: return $reservable_info;
9424: }
9425:
9426: sub get_course_slots {
9427: my ($cnum,$cdom) = @_;
9428: my $hashid=$cnum.':'.$cdom;
9429: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9430: if (defined($cached)) {
9431: if (ref($result) eq 'HASH') {
9432: return %{$result};
9433: }
9434: } else {
9435: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9436: my ($tmp) = keys(%slots);
9437: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9438: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9439: return %slots;
9440: }
9441: }
9442: return;
9443: }
9444:
9445: sub devalidate_slots_cache {
9446: my ($cnum,$cdom)=@_;
9447: my $hashid=$cnum.':'.$cdom;
9448: &devalidate_cache_new('allslots',$hashid);
9449: }
9450:
9451: # ------------------------------------------------- Update symbolic store links
9452:
9453: sub symblist {
9454: my ($mapname,%newhash)=@_;
9455: $mapname=&deversion(&declutter($mapname));
9456: my %hash;
9457: if (($env{'request.course.fn'}) && (%newhash)) {
9458: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9459: &GDBM_WRCREAT(),0640)) {
9460: foreach my $url (keys(%newhash)) {
9461: next if ($url eq 'last_known'
9462: && $env{'form.no_update_last_known'});
9463: $hash{declutter($url)}=&encode_symb($mapname,
9464: $newhash{$url}->[1],
9465: $newhash{$url}->[0]);
9466: }
9467: if (untie(%hash)) {
9468: return 'ok';
9469: }
9470: }
9471: }
9472: return 'error';
9473: }
9474:
9475: # --------------------------------------------------------------- Verify a symb
9476:
9477: sub symbverify {
9478: my ($symb,$thisurl)=@_;
9479: my $thisfn=$thisurl;
9480: $thisfn=&declutter($thisfn);
9481: # direct jump to resource in page or to a sequence - will construct own symbs
9482: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9483: # check URL part
9484: my ($map,$resid,$url)=&decode_symb($symb);
9485:
9486: unless ($url eq $thisfn) { return 0; }
9487:
9488: $symb=&symbclean($symb);
9489: $thisurl=&deversion($thisurl);
9490: $thisfn=&deversion($thisfn);
9491:
9492: my %bighash;
9493: my $okay=0;
9494:
9495: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9496: &GDBM_READER(),0640)) {
9497: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9498: $thisurl =~ s/\?.+$//;
9499: }
9500: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9501: unless ($ids) {
9502: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9503: $ids=$bighash{$idkey};
9504: }
9505: if ($ids) {
9506: # ------------------------------------------------------------------- Has ID(s)
9507: foreach my $id (split(/\,/,$ids)) {
9508: my ($mapid,$resid)=split(/\./,$id);
9509: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9510: $symb =~ s/\?.+$//;
9511: }
9512: if (
9513: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9514: eq $symb) {
9515: if (($env{'request.role.adv'}) ||
9516: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9517: ($thisurl eq '/adm/navmaps')) {
9518: $okay=1;
9519: }
9520: }
9521: }
9522: }
9523: untie(%bighash);
9524: }
9525: return $okay;
9526: }
9527:
9528: # --------------------------------------------------------------- Clean-up symb
9529:
9530: sub symbclean {
9531: my $symb=shift;
9532: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9533: # remove version from map
9534: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9535:
9536: # remove version from URL
9537: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9538:
9539: # remove wrapper
9540:
9541: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9542: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9543: return $symb;
9544: }
9545:
9546: # ---------------------------------------------- Split symb to find map and url
9547:
9548: sub encode_symb {
9549: my ($map,$resid,$url)=@_;
9550: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9551: }
9552:
9553: sub decode_symb {
9554: my $symb=shift;
9555: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9556: my ($map,$resid,$url)=split(/___/,$symb);
9557: return (&fixversion($map),$resid,&fixversion($url));
9558: }
9559:
9560: sub fixversion {
9561: my $fn=shift;
9562: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9563: my %bighash;
9564: my $uri=&clutter($fn);
9565: my $key=$env{'request.course.id'}.'_'.$uri;
9566: # is this cached?
9567: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9568: if (defined($cached)) { return $result; }
9569: # unfortunately not cached, or expired
9570: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9571: &GDBM_READER(),0640)) {
9572: if ($bighash{'version_'.$uri}) {
9573: my $version=$bighash{'version_'.$uri};
9574: unless (($version eq 'mostrecent') ||
9575: ($version==&getversion($uri))) {
9576: $uri=~s/\.(\w+)$/\.$version\.$1/;
9577: }
9578: }
9579: untie %bighash;
9580: }
9581: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9582: }
9583:
9584: sub deversion {
9585: my $url=shift;
9586: $url=~s/\.\d+\.(\w+)$/\.$1/;
9587: return $url;
9588: }
9589:
9590: # ------------------------------------------------------ Return symb list entry
9591:
9592: sub symbread {
9593: my ($thisfn,$donotrecurse)=@_;
9594: my $cache_str='request.symbread.cached.'.$thisfn;
9595: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9596: # no filename provided? try from environment
9597: unless ($thisfn) {
9598: if ($env{'request.symb'}) {
9599: return $env{$cache_str}=&symbclean($env{'request.symb'});
9600: }
9601: $thisfn=$env{'request.filename'};
9602: }
9603: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9604: # is that filename actually a symb? Verify, clean, and return
9605: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9606: if (&symbverify($thisfn,$1)) {
9607: return $env{$cache_str}=&symbclean($thisfn);
9608: }
9609: }
9610: $thisfn=declutter($thisfn);
9611: my %hash;
9612: my %bighash;
9613: my $syval='';
9614: if (($env{'request.course.fn'}) && ($thisfn)) {
9615: my $targetfn = $thisfn;
9616: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9617: $targetfn = 'adm/wrapper/'.$thisfn;
9618: }
9619: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9620: $targetfn=$1;
9621: }
9622: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9623: &GDBM_READER(),0640)) {
9624: $syval=$hash{$targetfn};
9625: untie(%hash);
9626: }
9627: # ---------------------------------------------------------- There was an entry
9628: if ($syval) {
9629: #unless ($syval=~/\_\d+$/) {
9630: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9631: #&appenv({'request.ambiguous' => $thisfn});
9632: #return $env{$cache_str}='';
9633: #}
9634: #$syval.=$1;
9635: #}
9636: } else {
9637: # ------------------------------------------------------- Was not in symb table
9638: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9639: &GDBM_READER(),0640)) {
9640: # ---------------------------------------------- Get ID(s) for current resource
9641: my $ids=$bighash{'ids_'.&clutter($thisfn)};
9642: unless ($ids) {
9643: $ids=$bighash{'ids_/'.$thisfn};
9644: }
9645: unless ($ids) {
9646: # alias?
9647: $ids=$bighash{'mapalias_'.$thisfn};
9648: }
9649: if ($ids) {
9650: # ------------------------------------------------------------------- Has ID(s)
9651: my @possibilities=split(/\,/,$ids);
9652: if ($#possibilities==0) {
9653: # ----------------------------------------------- There is only one possibility
9654: my ($mapid,$resid)=split(/\./,$ids);
9655: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9656: $resid,$thisfn);
9657: } elsif (!$donotrecurse) {
9658: # ------------------------------------------ There is more than one possibility
9659: my $realpossible=0;
9660: foreach my $id (@possibilities) {
9661: my $file=$bighash{'src_'.$id};
9662: if (&allowed('bre',$file)) {
9663: my ($mapid,$resid)=split(/\./,$id);
9664: if ($bighash{'map_type_'.$mapid} ne 'page') {
9665: $realpossible++;
9666: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9667: $resid,$thisfn);
9668: }
9669: }
9670: }
9671: if ($realpossible!=1) { $syval=''; }
9672: } else {
9673: $syval='';
9674: }
9675: }
9676: untie(%bighash)
9677: }
9678: }
9679: if ($syval) {
9680: return $env{$cache_str}=$syval;
9681: }
9682: }
9683: &appenv({'request.ambiguous' => $thisfn});
9684: return $env{$cache_str}='';
9685: }
9686:
9687: # ---------------------------------------------------------- Return random seed
9688:
9689: sub numval {
9690: my $txt=shift;
9691: $txt=~tr/A-J/0-9/;
9692: $txt=~tr/a-j/0-9/;
9693: $txt=~tr/K-T/0-9/;
9694: $txt=~tr/k-t/0-9/;
9695: $txt=~tr/U-Z/0-5/;
9696: $txt=~tr/u-z/0-5/;
9697: $txt=~s/\D//g;
9698: if ($_64bit) { if ($txt > 2**32) { return -1; } }
9699: return int($txt);
9700: }
9701:
9702: sub numval2 {
9703: my $txt=shift;
9704: $txt=~tr/A-J/0-9/;
9705: $txt=~tr/a-j/0-9/;
9706: $txt=~tr/K-T/0-9/;
9707: $txt=~tr/k-t/0-9/;
9708: $txt=~tr/U-Z/0-5/;
9709: $txt=~tr/u-z/0-5/;
9710: $txt=~s/\D//g;
9711: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9712: my $total;
9713: foreach my $val (@txts) { $total+=$val; }
9714: if ($_64bit) { if ($total > 2**32) { return -1; } }
9715: return int($total);
9716: }
9717:
9718: sub numval3 {
9719: use integer;
9720: my $txt=shift;
9721: $txt=~tr/A-J/0-9/;
9722: $txt=~tr/a-j/0-9/;
9723: $txt=~tr/K-T/0-9/;
9724: $txt=~tr/k-t/0-9/;
9725: $txt=~tr/U-Z/0-5/;
9726: $txt=~tr/u-z/0-5/;
9727: $txt=~s/\D//g;
9728: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9729: my $total;
9730: foreach my $val (@txts) { $total+=$val; }
9731: if ($_64bit) { $total=(($total<<32)>>32); }
9732: return $total;
9733: }
9734:
9735: sub digest {
9736: my ($data)=@_;
9737: my $digest=&Digest::MD5::md5($data);
9738: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9739: my ($e,$f);
9740: {
9741: use integer;
9742: $e=($a+$b);
9743: $f=($c+$d);
9744: if ($_64bit) {
9745: $e=(($e<<32)>>32);
9746: $f=(($f<<32)>>32);
9747: }
9748: }
9749: if (wantarray) {
9750: return ($e,$f);
9751: } else {
9752: my $g;
9753: {
9754: use integer;
9755: $g=($e+$f);
9756: if ($_64bit) {
9757: $g=(($g<<32)>>32);
9758: }
9759: }
9760: return $g;
9761: }
9762: }
9763:
9764: sub latest_rnd_algorithm_id {
9765: return '64bit5';
9766: }
9767:
9768: sub get_rand_alg {
9769: my ($courseid)=@_;
9770: if (!$courseid) { $courseid=(&whichuser())[1]; }
9771: if ($courseid) {
9772: return $env{"course.$courseid.rndseed"};
9773: }
9774: return &latest_rnd_algorithm_id();
9775: }
9776:
9777: sub validCODE {
9778: my ($CODE)=@_;
9779: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9780: return 0;
9781: }
9782:
9783: sub getCODE {
9784: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
9785: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9786: defined($Apache::lonhomework::parsing_a_task) ) &&
9787: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
9788: return $Apache::lonhomework::history{'resource.CODE'};
9789: }
9790: return undef;
9791: }
9792: #
9793: # Determines the random seed for a specific context:
9794: #
9795: # parameters:
9796: # symb - in course context the symb for the seed.
9797: # course_id - The course id of the form domain_coursenum.
9798: # domain - Domain for the user.
9799: # course - Course for the user.
9800: # cenv - environment of the course.
9801: #
9802: # NOTE:
9803: # All parameters are picked out of the environment if missing
9804: # or not defined.
9805: # If a symb cannot be determined the current time is used instead.
9806: #
9807: # For a given well defined symb, courside, domain, username,
9808: # and course environment, the seed is reproducible.
9809: #
9810: sub rndseed {
9811: my ($symb,$courseid,$domain,$username, $cenv)=@_;
9812: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
9813: if (!defined($symb)) {
9814: unless ($symb=$wsymb) { return time; }
9815: }
9816: if (!defined $courseid) {
9817: $courseid=$wcourseid;
9818: }
9819: if (!defined $domain) { $domain=$wdomain; }
9820: if (!defined $username) { $username=$wusername }
9821:
9822: my $which;
9823: if (defined($cenv->{'rndseed'})) {
9824: $which = $cenv->{'rndseed'};
9825: } else {
9826: $which =&get_rand_alg($courseid);
9827: }
9828: if (defined(&getCODE())) {
9829:
9830: if ($which eq '64bit5') {
9831: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9832: } elsif ($which eq '64bit4') {
9833: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9834: } else {
9835: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9836: }
9837: } elsif ($which eq '64bit5') {
9838: return &rndseed_64bit5($symb,$courseid,$domain,$username);
9839: } elsif ($which eq '64bit4') {
9840: return &rndseed_64bit4($symb,$courseid,$domain,$username);
9841: } elsif ($which eq '64bit3') {
9842: return &rndseed_64bit3($symb,$courseid,$domain,$username);
9843: } elsif ($which eq '64bit2') {
9844: return &rndseed_64bit2($symb,$courseid,$domain,$username);
9845: } elsif ($which eq '64bit') {
9846: return &rndseed_64bit($symb,$courseid,$domain,$username);
9847: }
9848: return &rndseed_32bit($symb,$courseid,$domain,$username);
9849: }
9850:
9851: sub rndseed_32bit {
9852: my ($symb,$courseid,$domain,$username)=@_;
9853: {
9854: use integer;
9855: my $symbchck=unpack("%32C*",$symb) << 27;
9856: my $symbseed=numval($symb) << 22;
9857: my $namechck=unpack("%32C*",$username) << 17;
9858: my $nameseed=numval($username) << 12;
9859: my $domainseed=unpack("%32C*",$domain) << 7;
9860: my $courseseed=unpack("%32C*",$courseid);
9861: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
9862: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9863: #&logthis("rndseed :$num:$symb");
9864: if ($_64bit) { $num=(($num<<32)>>32); }
9865: return $num;
9866: }
9867: }
9868:
9869: sub rndseed_64bit {
9870: my ($symb,$courseid,$domain,$username)=@_;
9871: {
9872: use integer;
9873: my $symbchck=unpack("%32S*",$symb) << 21;
9874: my $symbseed=numval($symb) << 10;
9875: my $namechck=unpack("%32S*",$username);
9876:
9877: my $nameseed=numval($username) << 21;
9878: my $domainseed=unpack("%32S*",$domain) << 10;
9879: my $courseseed=unpack("%32S*",$courseid);
9880:
9881: my $num1=$symbchck+$symbseed+$namechck;
9882: my $num2=$nameseed+$domainseed+$courseseed;
9883: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9884: #&logthis("rndseed :$num:$symb");
9885: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9886: return "$num1,$num2";
9887: }
9888: }
9889:
9890: sub rndseed_64bit2 {
9891: my ($symb,$courseid,$domain,$username)=@_;
9892: {
9893: use integer;
9894: # strings need to be an even # of cahracters long, it it is odd the
9895: # last characters gets thrown away
9896: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9897: my $symbseed=numval($symb) << 10;
9898: my $namechck=unpack("%32S*",$username.' ');
9899:
9900: my $nameseed=numval($username) << 21;
9901: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9902: my $courseseed=unpack("%32S*",$courseid.' ');
9903:
9904: my $num1=$symbchck+$symbseed+$namechck;
9905: my $num2=$nameseed+$domainseed+$courseseed;
9906: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9907: #&logthis("rndseed :$num:$symb");
9908: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9909: return "$num1,$num2";
9910: }
9911: }
9912:
9913: sub rndseed_64bit3 {
9914: my ($symb,$courseid,$domain,$username)=@_;
9915: {
9916: use integer;
9917: # strings need to be an even # of cahracters long, it it is odd the
9918: # last characters gets thrown away
9919: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9920: my $symbseed=numval2($symb) << 10;
9921: my $namechck=unpack("%32S*",$username.' ');
9922:
9923: my $nameseed=numval2($username) << 21;
9924: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9925: my $courseseed=unpack("%32S*",$courseid.' ');
9926:
9927: my $num1=$symbchck+$symbseed+$namechck;
9928: my $num2=$nameseed+$domainseed+$courseseed;
9929: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9930: #&logthis("rndseed :$num1:$num2:$_64bit");
9931: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9932:
9933: return "$num1:$num2";
9934: }
9935: }
9936:
9937: sub rndseed_64bit4 {
9938: my ($symb,$courseid,$domain,$username)=@_;
9939: {
9940: use integer;
9941: # strings need to be an even # of cahracters long, it it is odd the
9942: # last characters gets thrown away
9943: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9944: my $symbseed=numval3($symb) << 10;
9945: my $namechck=unpack("%32S*",$username.' ');
9946:
9947: my $nameseed=numval3($username) << 21;
9948: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9949: my $courseseed=unpack("%32S*",$courseid.' ');
9950:
9951: my $num1=$symbchck+$symbseed+$namechck;
9952: my $num2=$nameseed+$domainseed+$courseseed;
9953: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9954: #&logthis("rndseed :$num1:$num2:$_64bit");
9955: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9956:
9957: return "$num1:$num2";
9958: }
9959: }
9960:
9961: sub rndseed_64bit5 {
9962: my ($symb,$courseid,$domain,$username)=@_;
9963: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9964: return "$num1:$num2";
9965: }
9966:
9967: sub rndseed_CODE_64bit {
9968: my ($symb,$courseid,$domain,$username)=@_;
9969: {
9970: use integer;
9971: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9972: my $symbseed=numval2($symb);
9973: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9974: my $CODEseed=numval(&getCODE());
9975: my $courseseed=unpack("%32S*",$courseid.' ');
9976: my $num1=$symbseed+$CODEchck;
9977: my $num2=$CODEseed+$courseseed+$symbchck;
9978: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9979: #&logthis("rndseed :$num1:$num2:$symb");
9980: if ($_64bit) { $num1=(($num1<<32)>>32); }
9981: if ($_64bit) { $num2=(($num2<<32)>>32); }
9982: return "$num1:$num2";
9983: }
9984: }
9985:
9986: sub rndseed_CODE_64bit4 {
9987: my ($symb,$courseid,$domain,$username)=@_;
9988: {
9989: use integer;
9990: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9991: my $symbseed=numval3($symb);
9992: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9993: my $CODEseed=numval3(&getCODE());
9994: my $courseseed=unpack("%32S*",$courseid.' ');
9995: my $num1=$symbseed+$CODEchck;
9996: my $num2=$CODEseed+$courseseed+$symbchck;
9997: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9998: #&logthis("rndseed :$num1:$num2:$symb");
9999: if ($_64bit) { $num1=(($num1<<32)>>32); }
10000: if ($_64bit) { $num2=(($num2<<32)>>32); }
10001: return "$num1:$num2";
10002: }
10003: }
10004:
10005: sub rndseed_CODE_64bit5 {
10006: my ($symb,$courseid,$domain,$username)=@_;
10007: my $code = &getCODE();
10008: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10009: return "$num1:$num2";
10010: }
10011:
10012: sub setup_random_from_rndseed {
10013: my ($rndseed)=@_;
10014: if ($rndseed =~/([,:])/) {
10015: my ($num1,$num2)=split(/[,:]/,$rndseed);
10016: &Math::Random::random_set_seed(abs($num1),abs($num2));
10017: } else {
10018: &Math::Random::random_set_seed_from_phrase($rndseed);
10019: }
10020: }
10021:
10022: sub latest_receipt_algorithm_id {
10023: return 'receipt3';
10024: }
10025:
10026: sub recunique {
10027: my $fucourseid=shift;
10028: my $unique;
10029: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10030: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10031: $unique=$env{"course.$fucourseid.internal.encseed"};
10032: } else {
10033: $unique=$perlvar{'lonReceipt'};
10034: }
10035: return unpack("%32C*",$unique);
10036: }
10037:
10038: sub recprefix {
10039: my $fucourseid=shift;
10040: my $prefix;
10041: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10042: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10043: $prefix=$env{"course.$fucourseid.internal.encpref"};
10044: } else {
10045: $prefix=$perlvar{'lonHostID'};
10046: }
10047: return unpack("%32C*",$prefix);
10048: }
10049:
10050: sub ireceipt {
10051: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10052:
10053: my $return =&recprefix($fucourseid).'-';
10054:
10055: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10056: $env{'request.state'} eq 'construct') {
10057: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10058: return $return;
10059: }
10060:
10061: my $cuname=unpack("%32C*",$funame);
10062: my $cudom=unpack("%32C*",$fudom);
10063: my $cucourseid=unpack("%32C*",$fucourseid);
10064: my $cusymb=unpack("%32C*",$fusymb);
10065: my $cunique=&recunique($fucourseid);
10066: my $cpart=unpack("%32S*",$part);
10067: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10068:
10069: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
10070:
10071: $return.= ($cunique%$cuname+
10072: $cunique%$cudom+
10073: $cusymb%$cuname+
10074: $cusymb%$cudom+
10075: $cucourseid%$cuname+
10076: $cucourseid%$cudom+
10077: $cpart%$cuname+
10078: $cpart%$cudom);
10079: } else {
10080: $return.= ($cunique%$cuname+
10081: $cunique%$cudom+
10082: $cusymb%$cuname+
10083: $cusymb%$cudom+
10084: $cucourseid%$cuname+
10085: $cucourseid%$cudom);
10086: }
10087: return $return;
10088: }
10089:
10090: sub receipt {
10091: my ($part)=@_;
10092: my ($symb,$courseid,$domain,$name) = &whichuser();
10093: return &ireceipt($name,$domain,$courseid,$symb,$part);
10094: }
10095:
10096: sub whichuser {
10097: my ($passedsymb)=@_;
10098: my ($symb,$courseid,$domain,$name,$publicuser);
10099: if (defined($env{'form.grade_symb'})) {
10100: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10101: my $allowed=&allowed('vgr',$tmp_courseid);
10102: if (!$allowed &&
10103: exists($env{'request.course.sec'}) &&
10104: $env{'request.course.sec'} !~ /^\s*$/) {
10105: $allowed=&allowed('vgr',$tmp_courseid.
10106: '/'.$env{'request.course.sec'});
10107: }
10108: if ($allowed) {
10109: ($symb)=&get_env_multiple('form.grade_symb');
10110: $courseid=$tmp_courseid;
10111: ($domain)=&get_env_multiple('form.grade_domain');
10112: ($name)=&get_env_multiple('form.grade_username');
10113: return ($symb,$courseid,$domain,$name,$publicuser);
10114: }
10115: }
10116: if (!$passedsymb) {
10117: $symb=&symbread();
10118: } else {
10119: $symb=$passedsymb;
10120: }
10121: $courseid=$env{'request.course.id'};
10122: $domain=$env{'user.domain'};
10123: $name=$env{'user.name'};
10124: if ($name eq 'public' && $domain eq 'public') {
10125: if (!defined($env{'form.username'})) {
10126: $env{'form.username'}.=time.rand(10000000);
10127: }
10128: $name.=$env{'form.username'};
10129: }
10130: return ($symb,$courseid,$domain,$name,$publicuser);
10131:
10132: }
10133:
10134: # ------------------------------------------------------------ Serves up a file
10135: # returns either the contents of the file or
10136: # -1 if the file doesn't exist
10137: #
10138: # if the target is a file that was uploaded via DOCS,
10139: # a check will be made to see if a current copy exists on the local server,
10140: # if it does this will be served, otherwise a copy will be retrieved from
10141: # the home server for the course and stored in /home/httpd/html/userfiles on
10142: # the local server.
10143:
10144: sub getfile {
10145: my ($file) = @_;
10146: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10147: &repcopy($file);
10148: return &readfile($file);
10149: }
10150:
10151: sub repcopy_userfile {
10152: my ($file)=@_;
10153: my $londocroot = $perlvar{'lonDocRoot'};
10154: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10155: if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10156: my ($cdom,$cnum,$filename) =
10157: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10158: my $uri="/uploaded/$cdom/$cnum/$filename";
10159: if (-e "$file") {
10160: # we already have a local copy, check it out
10161: my @fileinfo = stat($file);
10162: my $rtncode;
10163: my $info;
10164: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10165: if ($lwpresp ne 'ok') {
10166: # there is no such file anymore, even though we had a local copy
10167: if ($rtncode eq '404') {
10168: unlink($file);
10169: }
10170: return -1;
10171: }
10172: if ($info < $fileinfo[9]) {
10173: # nice, the file we have is up-to-date, just say okay
10174: return 'ok';
10175: } else {
10176: # the file is outdated, get rid of it
10177: unlink($file);
10178: }
10179: }
10180: # one way or the other, at this point, we don't have the file
10181: # construct the correct path for the file
10182: my @parts = ($cdom,$cnum);
10183: if ($filename =~ m|^(.+)/[^/]+$|) {
10184: push @parts, split(/\//,$1);
10185: }
10186: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10187: foreach my $part (@parts) {
10188: $path .= '/'.$part;
10189: if (!-e $path) {
10190: mkdir($path,0770);
10191: }
10192: }
10193: # now the path exists for sure
10194: # get a user agent
10195: my $ua=new LWP::UserAgent;
10196: my $transferfile=$file.'.in.transfer';
10197: # FIXME: this should flock
10198: if (-e $transferfile) { return 'ok'; }
10199: my $request;
10200: $uri=~s/^\///;
10201: my $homeserver = &homeserver($cnum,$cdom);
10202: my $protocol = $protocol{$homeserver};
10203: $protocol = 'http' if ($protocol ne 'https');
10204: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10205: my $response=$ua->request($request,$transferfile);
10206: # did it work?
10207: if ($response->is_error()) {
10208: unlink($transferfile);
10209: &logthis("Userfile repcopy failed for $uri");
10210: return -1;
10211: }
10212: # worked, rename the transfer file
10213: rename($transferfile,$file);
10214: return 'ok';
10215: }
10216:
10217: sub tokenwrapper {
10218: my $uri=shift;
10219: $uri=~s|^https?\://([^/]+)||;
10220: $uri=~s|^/||;
10221: $env{'user.environment'}=~/\/([^\/]+)\.id/;
10222: my $token=$1;
10223: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10224: if ($udom && $uname && $file) {
10225: $file=~s|(\?\.*)*$||;
10226: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10227: my $homeserver = &homeserver($uname,$udom);
10228: my $protocol = $protocol{$homeserver};
10229: $protocol = 'http' if ($protocol ne 'https');
10230: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10231: (($uri=~/\?/)?'&':'?').'token='.$token.
10232: '&tokenissued='.$perlvar{'lonHostID'};
10233: } else {
10234: return '/adm/notfound.html';
10235: }
10236: }
10237:
10238: # call with reqtype HEAD: get last modification time
10239: # call with reqtype GET: get the file contents
10240: # Do not call this with reqtype GET for large files! It loads everything into memory
10241: #
10242: sub getuploaded {
10243: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10244: $uri=~s/^\///;
10245: my $homeserver = &homeserver($cnum,$cdom);
10246: my $protocol = $protocol{$homeserver};
10247: $protocol = 'http' if ($protocol ne 'https');
10248: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10249: my $ua=new LWP::UserAgent;
10250: my $request=new HTTP::Request($reqtype,$uri);
10251: my $response=$ua->request($request);
10252: $$rtncode = $response->code;
10253: if (! $response->is_success()) {
10254: return 'failed';
10255: }
10256: if ($reqtype eq 'HEAD') {
10257: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10258: } elsif ($reqtype eq 'GET') {
10259: $$info = $response->content;
10260: }
10261: return 'ok';
10262: }
10263:
10264: sub readfile {
10265: my $file = shift;
10266: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10267: my $fh;
10268: open($fh,"<$file");
10269: my $a='';
10270: while (my $line = <$fh>) { $a .= $line; }
10271: return $a;
10272: }
10273:
10274: sub filelocation {
10275: my ($dir,$file) = @_;
10276: my $location;
10277: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10278:
10279: if ($file =~ m-^/adm/-) {
10280: $file=~s-^/adm/wrapper/-/-;
10281: $file=~s-^/adm/coursedocs/showdoc/-/-;
10282: }
10283:
10284: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10285: $location = $file;
10286: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10287: my ($udom,$uname,$filename)=
10288: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10289: my $home=&homeserver($uname,$udom);
10290: my $is_me=0;
10291: my @ids=¤t_machine_ids();
10292: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10293: if ($is_me) {
10294: $location=propath($udom,$uname).'/userfiles/'.$filename;
10295: } else {
10296: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10297: $udom.'/'.$uname.'/'.$filename;
10298: }
10299: } elsif ($file =~ m-^/adm/-) {
10300: $location = $perlvar{'lonDocRoot'}.'/'.$file;
10301: } else {
10302: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10303: $file=~s:^/(res|priv)/:/:;
10304: my $space=$1;
10305: if ( !( $file =~ m:^/:) ) {
10306: $location = $dir. '/'.$file;
10307: } else {
10308: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10309: }
10310: }
10311: $location=~s://+:/:g; # remove duplicate /
10312: while ($location=~m{/\.\./}) {
10313: if ($location =~ m{/[^/]+/\.\./}) {
10314: $location=~ s{/[^/]+/\.\./}{/}g;
10315: } else {
10316: $location=~ s{/\.\./}{/}g;
10317: }
10318: } #remove dir/..
10319: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10320: return $location;
10321: }
10322:
10323: sub hreflocation {
10324: my ($dir,$file)=@_;
10325: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10326: $file=filelocation($dir,$file);
10327: } elsif ($file=~m-^/adm/-) {
10328: $file=~s-^/adm/wrapper/-/-;
10329: $file=~s-^/adm/coursedocs/showdoc/-/-;
10330: }
10331: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10332: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10333: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10334: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10335: {/uploaded/$1/$2/}x;
10336: }
10337: if ($file=~ m{^/userfiles/}) {
10338: $file =~ s{^/userfiles/}{/uploaded/};
10339: }
10340: return $file;
10341: }
10342:
10343:
10344:
10345:
10346:
10347: sub current_machine_domains {
10348: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10349: }
10350:
10351: sub machine_domains {
10352: my ($hostname) = @_;
10353: my @domains;
10354: my %hostname = &all_hostnames();
10355: while( my($id, $name) = each(%hostname)) {
10356: # &logthis("-$id-$name-$hostname-");
10357: if ($hostname eq $name) {
10358: push(@domains,&host_domain($id));
10359: }
10360: }
10361: return @domains;
10362: }
10363:
10364: sub current_machine_ids {
10365: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10366: }
10367:
10368: sub machine_ids {
10369: my ($hostname) = @_;
10370: $hostname ||= &hostname($perlvar{'lonHostID'});
10371: my @ids;
10372: my %name_to_host = &all_names();
10373: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10374: return @{ $name_to_host{$hostname} };
10375: }
10376: return;
10377: }
10378:
10379: sub additional_machine_domains {
10380: my @domains;
10381: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10382: while( my $line = <$fh>) {
10383: $line =~ s/\s//g;
10384: push(@domains,$line);
10385: }
10386: return @domains;
10387: }
10388:
10389: sub default_login_domain {
10390: my $domain = $perlvar{'lonDefDomain'};
10391: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10392: foreach my $posdom (¤t_machine_domains(),
10393: &additional_machine_domains()) {
10394: if (lc($posdom) eq lc($testdomain)) {
10395: $domain=$posdom;
10396: last;
10397: }
10398: }
10399: return $domain;
10400: }
10401:
10402: # ------------------------------------------------------------- Declutters URLs
10403:
10404: sub declutter {
10405: my $thisfn=shift;
10406: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10407: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10408: $thisfn=~s/^\///;
10409: $thisfn=~s|^adm/wrapper/||;
10410: $thisfn=~s|^adm/coursedocs/showdoc/||;
10411: $thisfn=~s/^res\///;
10412: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10413: $thisfn=~s/\?.+$//;
10414: }
10415: return $thisfn;
10416: }
10417:
10418: # ------------------------------------------------------------- Clutter up URLs
10419:
10420: sub clutter {
10421: my $thisfn='/'.&declutter(shift);
10422: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10423: || $thisfn =~ m{^/adm/(includes|pages)} ) {
10424: $thisfn='/res'.$thisfn;
10425: }
10426: if ($thisfn !~m|^/adm|) {
10427: if ($thisfn =~ m|^/ext/|) {
10428: $thisfn='/adm/wrapper'.$thisfn;
10429: } else {
10430: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10431: my $embstyle=&Apache::loncommon::fileembstyle($ext);
10432: if ($embstyle eq 'ssi'
10433: || ($embstyle eq 'hdn')
10434: || ($embstyle eq 'rat')
10435: || ($embstyle eq 'prv')
10436: || ($embstyle eq 'ign')) {
10437: #do nothing with these
10438: } elsif (($embstyle eq 'img')
10439: || ($embstyle eq 'emb')
10440: || ($embstyle eq 'wrp')) {
10441: $thisfn='/adm/wrapper'.$thisfn;
10442: } elsif ($embstyle eq 'unk'
10443: && $thisfn!~/\.(sequence|page)$/) {
10444: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
10445: } else {
10446: # &logthis("Got a blank emb style");
10447: }
10448: }
10449: }
10450: return $thisfn;
10451: }
10452:
10453: sub clutter_with_no_wrapper {
10454: my $uri = &clutter(shift);
10455: if ($uri =~ m-^/adm/-) {
10456: $uri =~ s-^/adm/wrapper/-/-;
10457: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10458: }
10459: return $uri;
10460: }
10461:
10462: sub freeze_escape {
10463: my ($value)=@_;
10464: if (ref($value)) {
10465: $value=&nfreeze($value);
10466: return '__FROZEN__'.&escape($value);
10467: }
10468: return &escape($value);
10469: }
10470:
10471:
10472: sub thaw_unescape {
10473: my ($value)=@_;
10474: if ($value =~ /^__FROZEN__/) {
10475: substr($value,0,10,undef);
10476: $value=&unescape($value);
10477: return &thaw($value);
10478: }
10479: return &unescape($value);
10480: }
10481:
10482: sub correct_line_ends {
10483: my ($result)=@_;
10484: $$result =~s/\r\n/\n/mg;
10485: $$result =~s/\r/\n/mg;
10486: }
10487: # ================================================================ Main Program
10488:
10489: sub goodbye {
10490: &logthis("Starting Shut down");
10491: #not converted to using infrastruture and probably shouldn't be
10492: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10493: #converted
10494: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10495: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10496: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10497: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10498: #1.1 only
10499: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10500: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10501: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10502: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10503: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10504: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10505: &logthis(sprintf("%-20s is %s",'hits',$hits));
10506: &flushcourselogs();
10507: &logthis("Shutting down");
10508: }
10509:
10510: sub get_dns {
10511: my ($url,$func,$ignore_cache) = @_;
10512: if (!$ignore_cache) {
10513: my ($content,$cached)=
10514: &Apache::lonnet::is_cached_new('dns',$url);
10515: if ($cached) {
10516: &$func($content);
10517: return;
10518: }
10519: }
10520:
10521: my %alldns;
10522: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10523: foreach my $dns (<$config>) {
10524: next if ($dns !~ /^\^(\S*)/x);
10525: my $line = $1;
10526: my ($host,$protocol) = split(/:/,$line);
10527: if ($protocol ne 'https') {
10528: $protocol = 'http';
10529: }
10530: $alldns{$host} = $protocol;
10531: }
10532: while (%alldns) {
10533: my ($dns) = keys(%alldns);
10534: my $ua=new LWP::UserAgent;
10535: $ua->timeout(30);
10536: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10537: my $response=$ua->request($request);
10538: delete($alldns{$dns});
10539: next if ($response->is_error());
10540: my @content = split("\n",$response->content);
10541: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10542: &$func(\@content);
10543: return;
10544: }
10545: close($config);
10546: my $which = (split('/',$url))[3];
10547: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10548: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10549: my @content = <$config>;
10550: &$func(\@content);
10551: return;
10552: }
10553: # ------------------------------------------------------------ Read domain file
10554: {
10555: my $loaded;
10556: my %domain;
10557:
10558: sub parse_domain_tab {
10559: my ($lines) = @_;
10560: foreach my $line (@$lines) {
10561: next if ($line =~ /^(\#|\s*$ )/x);
10562:
10563: chomp($line);
10564: my ($name,@elements) = split(/:/,$line,9);
10565: my %this_domain;
10566: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10567: 'lang_def', 'city', 'longi', 'lati',
10568: 'primary') {
10569: $this_domain{$field} = shift(@elements);
10570: }
10571: $domain{$name} = \%this_domain;
10572: }
10573: }
10574:
10575: sub reset_domain_info {
10576: undef($loaded);
10577: undef(%domain);
10578: }
10579:
10580: sub load_domain_tab {
10581: my ($ignore_cache) = @_;
10582: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10583: my $fh;
10584: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10585: my @lines = <$fh>;
10586: &parse_domain_tab(\@lines);
10587: }
10588: close($fh);
10589: $loaded = 1;
10590: }
10591:
10592: sub domain {
10593: &load_domain_tab() if (!$loaded);
10594:
10595: my ($name,$what) = @_;
10596: return if ( !exists($domain{$name}) );
10597:
10598: if (!$what) {
10599: return $domain{$name}{'description'};
10600: }
10601: return $domain{$name}{$what};
10602: }
10603:
10604: sub domain_info {
10605: &load_domain_tab() if (!$loaded);
10606: return %domain;
10607: }
10608:
10609: }
10610:
10611:
10612: # ------------------------------------------------------------- Read hosts file
10613: {
10614: my %hostname;
10615: my %hostdom;
10616: my %libserv;
10617: my $loaded;
10618: my %name_to_host;
10619: my %internetdom;
10620: my %LC_dns_serv;
10621:
10622: sub parse_hosts_tab {
10623: my ($file) = @_;
10624: foreach my $configline (@$file) {
10625: next if ($configline =~ /^(\#|\s*$ )/x);
10626: chomp($configline);
10627: if ($configline =~ /^\^/) {
10628: if ($configline =~ /^\^([\w.\-]+)/) {
10629: $LC_dns_serv{$1} = 1;
10630: }
10631: next;
10632: }
10633: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10634: $name=~s/\s//g;
10635: if ($id && $domain && $role && $name) {
10636: $hostname{$id}=$name;
10637: push(@{$name_to_host{$name}}, $id);
10638: $hostdom{$id}=$domain;
10639: if ($role eq 'library') { $libserv{$id}=$name; }
10640: if (defined($protocol)) {
10641: if ($protocol eq 'https') {
10642: $protocol{$id} = $protocol;
10643: } else {
10644: $protocol{$id} = 'http';
10645: }
10646: } else {
10647: $protocol{$id} = 'http';
10648: }
10649: if (defined($intdom)) {
10650: $internetdom{$id} = $intdom;
10651: }
10652: }
10653: }
10654: }
10655:
10656: sub reset_hosts_info {
10657: &purge_remembered();
10658: &reset_domain_info();
10659: &reset_hosts_ip_info();
10660: undef(%name_to_host);
10661: undef(%hostname);
10662: undef(%hostdom);
10663: undef(%libserv);
10664: undef($loaded);
10665: }
10666:
10667: sub load_hosts_tab {
10668: my ($ignore_cache) = @_;
10669: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10670: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10671: my @config = <$config>;
10672: &parse_hosts_tab(\@config);
10673: close($config);
10674: $loaded=1;
10675: }
10676:
10677: sub hostname {
10678: &load_hosts_tab() if (!$loaded);
10679:
10680: my ($lonid) = @_;
10681: return $hostname{$lonid};
10682: }
10683:
10684: sub all_hostnames {
10685: &load_hosts_tab() if (!$loaded);
10686:
10687: return %hostname;
10688: }
10689:
10690: sub all_names {
10691: &load_hosts_tab() if (!$loaded);
10692:
10693: return %name_to_host;
10694: }
10695:
10696: sub all_host_domain {
10697: &load_hosts_tab() if (!$loaded);
10698: return %hostdom;
10699: }
10700:
10701: sub is_library {
10702: &load_hosts_tab() if (!$loaded);
10703:
10704: return exists($libserv{$_[0]});
10705: }
10706:
10707: sub all_library {
10708: &load_hosts_tab() if (!$loaded);
10709:
10710: return %libserv;
10711: }
10712:
10713: sub unique_library {
10714: #2x reverse removes all hostnames that appear more than once
10715: my %unique = reverse &all_library();
10716: return reverse %unique;
10717: }
10718:
10719: sub get_servers {
10720: &load_hosts_tab() if (!$loaded);
10721:
10722: my ($domain,$type) = @_;
10723: my %possible_hosts = ($type eq 'library') ? %libserv
10724: : %hostname;
10725: my %result;
10726: if (ref($domain) eq 'ARRAY') {
10727: while ( my ($host,$hostname) = each(%possible_hosts)) {
10728: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10729: $result{$host} = $hostname;
10730: }
10731: }
10732: } else {
10733: while ( my ($host,$hostname) = each(%possible_hosts)) {
10734: if ($hostdom{$host} eq $domain) {
10735: $result{$host} = $hostname;
10736: }
10737: }
10738: }
10739: return %result;
10740: }
10741:
10742: sub get_unique_servers {
10743: my %unique = reverse &get_servers(@_);
10744: return reverse %unique;
10745: }
10746:
10747: sub host_domain {
10748: &load_hosts_tab() if (!$loaded);
10749:
10750: my ($lonid) = @_;
10751: return $hostdom{$lonid};
10752: }
10753:
10754: sub all_domains {
10755: &load_hosts_tab() if (!$loaded);
10756:
10757: my %seen;
10758: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10759: return @uniq;
10760: }
10761:
10762: sub internet_dom {
10763: &load_hosts_tab() if (!$loaded);
10764:
10765: my ($lonid) = @_;
10766: return $internetdom{$lonid};
10767: }
10768:
10769: sub is_LC_dns {
10770: &load_hosts_tab() if (!$loaded);
10771:
10772: my ($hostname) = @_;
10773: return exists($LC_dns_serv{$hostname});
10774: }
10775:
10776: }
10777:
10778: {
10779: my %iphost;
10780: my %name_to_ip;
10781: my %lonid_to_ip;
10782:
10783: sub get_hosts_from_ip {
10784: my ($ip) = @_;
10785: my %iphosts = &get_iphost();
10786: if (ref($iphosts{$ip})) {
10787: return @{$iphosts{$ip}};
10788: }
10789: return;
10790: }
10791:
10792: sub reset_hosts_ip_info {
10793: undef(%iphost);
10794: undef(%name_to_ip);
10795: undef(%lonid_to_ip);
10796: }
10797:
10798: sub get_host_ip {
10799: my ($lonid) = @_;
10800: if (exists($lonid_to_ip{$lonid})) {
10801: return $lonid_to_ip{$lonid};
10802: }
10803: my $name=&hostname($lonid);
10804: my $ip = gethostbyname($name);
10805: return if (!$ip || length($ip) ne 4);
10806: $ip=inet_ntoa($ip);
10807: $name_to_ip{$name} = $ip;
10808: $lonid_to_ip{$lonid} = $ip;
10809: return $ip;
10810: }
10811:
10812: sub get_iphost {
10813: my ($ignore_cache) = @_;
10814:
10815: if (!$ignore_cache) {
10816: if (%iphost) {
10817: return %iphost;
10818: }
10819: my ($ip_info,$cached)=
10820: &Apache::lonnet::is_cached_new('iphost','iphost');
10821: if ($cached) {
10822: %iphost = %{$ip_info->[0]};
10823: %name_to_ip = %{$ip_info->[1]};
10824: %lonid_to_ip = %{$ip_info->[2]};
10825: return %iphost;
10826: }
10827: }
10828:
10829: # get yesterday's info for fallback
10830: my %old_name_to_ip;
10831: my ($ip_info,$cached)=
10832: &Apache::lonnet::is_cached_new('iphost','iphost');
10833: if ($cached) {
10834: %old_name_to_ip = %{$ip_info->[1]};
10835: }
10836:
10837: my %name_to_host = &all_names();
10838: foreach my $name (keys(%name_to_host)) {
10839: my $ip;
10840: if (!exists($name_to_ip{$name})) {
10841: $ip = gethostbyname($name);
10842: if (!$ip || length($ip) ne 4) {
10843: if (defined($old_name_to_ip{$name})) {
10844: $ip = $old_name_to_ip{$name};
10845: &logthis("Can't find $name defaulting to old $ip");
10846: } else {
10847: &logthis("Name $name no IP found");
10848: next;
10849: }
10850: } else {
10851: $ip=inet_ntoa($ip);
10852: }
10853: $name_to_ip{$name} = $ip;
10854: } else {
10855: $ip = $name_to_ip{$name};
10856: }
10857: foreach my $id (@{ $name_to_host{$name} }) {
10858: $lonid_to_ip{$id} = $ip;
10859: }
10860: push(@{$iphost{$ip}},@{$name_to_host{$name}});
10861: }
10862: &Apache::lonnet::do_cache_new('iphost','iphost',
10863: [\%iphost,\%name_to_ip,\%lonid_to_ip],
10864: 48*60*60);
10865:
10866: return %iphost;
10867: }
10868:
10869: #
10870: # Given a DNS returns the loncapa host name for that DNS
10871: #
10872: sub host_from_dns {
10873: my ($dns) = @_;
10874: my @hosts;
10875: my $ip;
10876:
10877: if (exists($name_to_ip{$dns})) {
10878: $ip = $name_to_ip{$dns};
10879: }
10880: if (!$ip) {
10881: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10882: if (length($ip) == 4) {
10883: $ip = &IO::Socket::inet_ntoa($ip);
10884: }
10885: }
10886: if ($ip) {
10887: @hosts = get_hosts_from_ip($ip);
10888: return $hosts[0];
10889: }
10890: return undef;
10891: }
10892:
10893: sub get_internet_names {
10894: my ($lonid) = @_;
10895: return if ($lonid eq '');
10896: my ($idnref,$cached)=
10897: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10898: if ($cached) {
10899: return $idnref;
10900: }
10901: my $ip = &get_host_ip($lonid);
10902: my @hosts = &get_hosts_from_ip($ip);
10903: my %iphost = &get_iphost();
10904: my (@idns,%seen);
10905: foreach my $id (@hosts) {
10906: my $dom = &host_domain($id);
10907: my $prim_id = &domain($dom,'primary');
10908: my $prim_ip = &get_host_ip($prim_id);
10909: next if ($seen{$prim_ip});
10910: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10911: foreach my $id (@{$iphost{$prim_ip}}) {
10912: my $intdom = &internet_dom($id);
10913: unless (grep(/^\Q$intdom\E$/,@idns)) {
10914: push(@idns,$intdom);
10915: }
10916: }
10917: }
10918: $seen{$prim_ip} = 1;
10919: }
10920: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10921: }
10922:
10923: }
10924:
10925: sub all_loncaparevs {
10926: 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);
10927: }
10928:
10929: BEGIN {
10930:
10931: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10932: unless ($readit) {
10933: {
10934: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10935: %perlvar = (%perlvar,%{$configvars});
10936: }
10937:
10938:
10939: # ------------------------------------------------------ Read spare server file
10940: {
10941: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10942:
10943: while (my $configline=<$config>) {
10944: chomp($configline);
10945: if ($configline) {
10946: my ($host,$type) = split(':',$configline,2);
10947: if (!defined($type) || $type eq '') { $type = 'default' };
10948: push(@{ $spareid{$type} }, $host);
10949: }
10950: }
10951: close($config);
10952: }
10953: # ------------------------------------------------------------ Read permissions
10954: {
10955: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10956:
10957: while (my $configline=<$config>) {
10958: chomp($configline);
10959: if ($configline) {
10960: my ($role,$perm)=split(/ /,$configline);
10961: if ($perm ne '') { $pr{$role}=$perm; }
10962: }
10963: }
10964: close($config);
10965: }
10966:
10967: # -------------------------------------------- Read plain texts for permissions
10968: {
10969: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10970:
10971: while (my $configline=<$config>) {
10972: chomp($configline);
10973: if ($configline) {
10974: my ($short,@plain)=split(/:/,$configline);
10975: %{$prp{$short}} = ();
10976: if (@plain > 0) {
10977: $prp{$short}{'std'} = $plain[0];
10978: for (my $i=1; $i<@plain; $i++) {
10979: $prp{$short}{'alt'.$i} = $plain[$i];
10980: }
10981: }
10982: }
10983: }
10984: close($config);
10985: }
10986:
10987: # ---------------------------------------------------------- Read package table
10988: {
10989: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10990:
10991: while (my $configline=<$config>) {
10992: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10993: chomp($configline);
10994: my ($short,$plain)=split(/:/,$configline);
10995: my ($pack,$name)=split(/\&/,$short);
10996: if ($plain ne '') {
10997: $packagetab{$pack.'&'.$name.'&name'}=$name;
10998: $packagetab{$short}=$plain;
10999: }
11000: }
11001: close($config);
11002: }
11003:
11004: # ---------------------------------------------------------- Read loncaparev table
11005: {
11006: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11007: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11008: while (my $configline=<$config>) {
11009: chomp($configline);
11010: my ($hostid,$loncaparev)=split(/:/,$configline);
11011: $loncaparevs{$hostid}=$loncaparev;
11012: }
11013: close($config);
11014: }
11015: }
11016: }
11017:
11018: # ---------------------------------------------------------- Read serverhostID table
11019: {
11020: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11021: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11022: while (my $configline=<$config>) {
11023: chomp($configline);
11024: my ($name,$id)=split(/:/,$configline);
11025: $serverhomeIDs{$name}=$id;
11026: }
11027: close($config);
11028: }
11029: }
11030: }
11031:
11032: {
11033: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11034: if (-e $file) {
11035: my $parser = HTML::LCParser->new($file);
11036: while (my $token = $parser->get_token()) {
11037: if ($token->[0] eq 'S') {
11038: my $item = $token->[1];
11039: my $name = $token->[2]{'name'};
11040: my $value = $token->[2]{'value'};
11041: if ($item ne '' && $name ne '' && $value ne '') {
11042: my $release = $parser->get_text();
11043: $release =~ s/(^\s*|\s*$ )//gx;
11044: $needsrelease{$item.':'.$name.':'.$value} = $release;
11045: }
11046: }
11047: }
11048: }
11049: }
11050:
11051: # ---------------------------------------------------------- Read managers table
11052: {
11053: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11054: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11055: while (my $configline=<$config>) {
11056: chomp($configline);
11057: next if ($configline =~ /^\#/);
11058: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11059: $managerstab{$configline} = 1;
11060: }
11061: }
11062: close($config);
11063: }
11064: }
11065: }
11066:
11067: # ------------- set up temporary directory
11068: {
11069: $tmpdir = LONCAPA::tempdir();
11070:
11071: }
11072:
11073: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11074: 'compress_threshold'=> 20_000,
11075: });
11076:
11077: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11078: $dumpcount=0;
11079: $locknum=0;
11080:
11081: &logtouch();
11082: &logthis('<font color="yellow">INFO: Read configuration</font>');
11083: $readit=1;
11084: {
11085: use integer;
11086: my $test=(2**32)+1;
11087: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11088: &logthis(" Detected 64bit platform ($_64bit)");
11089: }
11090: }
11091: }
11092:
11093: 1;
11094: __END__
11095:
11096: =pod
11097:
11098: =head1 NAME
11099:
11100: Apache::lonnet - Subroutines to ask questions about things in the network.
11101:
11102: =head1 SYNOPSIS
11103:
11104: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11105:
11106: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11107:
11108: Common parameters:
11109:
11110: =over 4
11111:
11112: =item *
11113:
11114: $uname : an internal username (if $cname expecting a course Id specifically)
11115:
11116: =item *
11117:
11118: $udom : a domain (if $cdom expecting a course's domain specifically)
11119:
11120: =item *
11121:
11122: $symb : a resource instance identifier
11123:
11124: =item *
11125:
11126: $namespace : the name of a .db file that contains the data needed or
11127: being set.
11128:
11129: =back
11130:
11131: =head1 OVERVIEW
11132:
11133: lonnet provides subroutines which interact with the
11134: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11135: about classes, users, and resources.
11136:
11137: For many of these objects you can also use this to store data about
11138: them or modify them in various ways.
11139:
11140: =head2 Symbs
11141:
11142: To identify a specific instance of a resource, LON-CAPA uses symbols
11143: or "symbs"X<symb>. These identifiers are built from the URL of the
11144: map, the resource number of the resource in the map, and the URL of
11145: the resource itself. The latter is somewhat redundant, but might help
11146: if maps change.
11147:
11148: An example is
11149:
11150: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11151:
11152: The respective map entry is
11153:
11154: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11155: title="Problem 2">
11156: </resource>
11157:
11158: Symbs are used by the random number generator, as well as to store and
11159: restore data specific to a certain instance of for example a problem.
11160:
11161: =head2 Storing And Retrieving Data
11162:
11163: X<store()>X<cstore()>X<restore()>Three of the most important functions
11164: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11165: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11166: is is the non-critical message twin of cstore. These functions are for
11167: handlers to store a perl hash to a user's permanent data space in an
11168: easy manner, and to retrieve it again on another call. It is expected
11169: that a handler would use this once at the beginning to retrieve data,
11170: and then again once at the end to send only the new data back.
11171:
11172: The data is stored in the user's data directory on the user's
11173: homeserver under the ID of the course.
11174:
11175: The hash that is returned by restore will have all of the previous
11176: value for all of the elements of the hash.
11177:
11178: Example:
11179:
11180: #creating a hash
11181: my %hash;
11182: $hash{'foo'}='bar';
11183:
11184: #storing it
11185: &Apache::lonnet::cstore(\%hash);
11186:
11187: #changing a value
11188: $hash{'foo'}='notbar';
11189:
11190: #adding a new value
11191: $hash{'bar'}='foo';
11192: &Apache::lonnet::cstore(\%hash);
11193:
11194: #retrieving the hash
11195: my %history=&Apache::lonnet::restore();
11196:
11197: #print the hash
11198: foreach my $key (sort(keys(%history))) {
11199: print("\%history{$key} = $history{$key}");
11200: }
11201:
11202: Will print out:
11203:
11204: %history{1:foo} = bar
11205: %history{1:keys} = foo:timestamp
11206: %history{1:timestamp} = 990455579
11207: %history{2:bar} = foo
11208: %history{2:foo} = notbar
11209: %history{2:keys} = foo:bar:timestamp
11210: %history{2:timestamp} = 990455580
11211: %history{bar} = foo
11212: %history{foo} = notbar
11213: %history{timestamp} = 990455580
11214: %history{version} = 2
11215:
11216: Note that the special hash entries C<keys>, C<version> and
11217: C<timestamp> were added to the hash. C<version> will be equal to the
11218: total number of versions of the data that have been stored. The
11219: C<timestamp> attribute will be the UNIX time the hash was
11220: stored. C<keys> is available in every historical section to list which
11221: keys were added or changed at a specific historical revision of a
11222: hash.
11223:
11224: B<Warning>: do not store the hash that restore returns directly. This
11225: will cause a mess since it will restore the historical keys as if the
11226: were new keys. I.E. 1:foo will become 1:1:foo etc.
11227:
11228: Calling convention:
11229:
11230: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11231: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11232:
11233: For more detailed information, see lonnet specific documentation.
11234:
11235: =head1 RETURN MESSAGES
11236:
11237: =over 4
11238:
11239: =item * B<con_lost>: unable to contact remote host
11240:
11241: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11242: when the connection is brought back up
11243:
11244: =item * B<con_failed>: unable to contact remote host and unable to save message
11245: for later delivery
11246:
11247: =item * B<error:>: an error a occurred, a description of the error follows the :
11248:
11249: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11250: that was requested
11251:
11252: =back
11253:
11254: =head1 PUBLIC SUBROUTINES
11255:
11256: =head2 Session Environment Functions
11257:
11258: =over 4
11259:
11260: =item *
11261: X<appenv()>
11262: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11263: the user envirnoment file, and will be restored for each access this
11264: user makes during this session, also modifies the %env for the current
11265: process. Optional rolesarrayref - if defined contains a reference to an array
11266: of roles which are exempt from the restriction on modifying user.role entries
11267: in the user's environment.db and in %env.
11268:
11269: =item *
11270: X<delenv()>
11271: B<delenv($delthis,$regexp)>: removes all items from the session
11272: environment file that begin with $delthis. If the
11273: optional second arg - $regexp - is true, $delthis is treated as a
11274: regular expression, otherwise \Q$delthis\E is used.
11275: The values are also deleted from the current processes %env.
11276:
11277: =item * get_env_multiple($name)
11278:
11279: gets $name from the %env hash, it seemlessly handles the cases where multiple
11280: values may be defined and end up as an array ref.
11281:
11282: returns an array of values
11283:
11284: =back
11285:
11286: =head2 User Information
11287:
11288: =over 4
11289:
11290: =item *
11291: X<queryauthenticate()>
11292: B<queryauthenticate($uname,$udom)>: try to determine user's current
11293: authentication scheme
11294:
11295: =item *
11296: X<authenticate()>
11297: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11298: authenticate user from domain's lib servers (first use the current
11299: one). C<$upass> should be the users password.
11300: $checkdefauth is optional (value is 1 if a check should be made to
11301: authenticate user using default authentication method, and allow
11302: account creation if username does not have account in the domain).
11303: $clientcancheckhost is optional (value is 1 if checking whether the
11304: server can host will occur on the client side in lonauth.pm).
11305:
11306: =item *
11307: X<homeserver()>
11308: B<homeserver($uname,$udom)>: find the server which has
11309: the user's directory and files (there must be only one), this caches
11310: the answer, and also caches if there is a borken connection.
11311:
11312: =item *
11313: X<idget()>
11314: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11315: (IDs are a unique resource in a domain, there must be only 1 ID per
11316: username, and only 1 username per ID in a specific domain) (returns
11317: hash: id=>name,id=>name)
11318:
11319: =item *
11320: X<idrget()>
11321: B<idrget($udom,@unames)>: find the IDs behind a list of
11322: usernames (returns hash: name=>id,name=>id)
11323:
11324: =item *
11325: X<idput()>
11326: B<idput($udom,%ids)>: store away a list of names and associated IDs
11327:
11328: =item *
11329: X<rolesinit()>
11330: B<rolesinit($udom,$username,$authhost)>: get user privileges
11331:
11332: =item *
11333: X<getsection()>
11334: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11335: course $cname, return section name/number or '' for "not in course"
11336: and '-1' for "no section"
11337:
11338: =item *
11339: X<userenvironment()>
11340: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11341: passed in @what from the requested user's environment, returns a hash
11342:
11343: =item *
11344: X<userlog_query()>
11345: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11346: activity.log file. %filters defines filters applied when parsing the
11347: log file. These can be start or end timestamps, or the type of action
11348: - log to look for Login or Logout events, check for Checkin or
11349: Checkout, role for role selection. The response is in the form
11350: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11351: escaped strings of the action recorded in the activity.log file.
11352:
11353: =back
11354:
11355: =head2 User Roles
11356:
11357: =over 4
11358:
11359: =item *
11360:
11361: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11362: F: full access
11363: U,I,K: authentication modes (cxx only)
11364: '': forbidden
11365: 1: user needs to choose course
11366: 2: browse allowed
11367: A: passphrase authentication needed
11368:
11369: =item *
11370:
11371: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11372: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11373: and course level
11374:
11375: =item *
11376:
11377: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11378: (rolesplain.tab); plain text explanation of a user role term.
11379: $type is Course (default) or Community.
11380: If $forcedefault evaluates to true, text returned will be default
11381: text for $type. Otherwise, if this is a course, the text returned
11382: will be a custom name for the role (if defined in the course's
11383: environment). If no custom name is defined the default is returned.
11384:
11385: =item *
11386:
11387: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11388: All arguments are optional. Returns a hash of a roles, either for
11389: co-author/assistant author roles for a user's Construction Space
11390: (default), or if $context is 'userroles', roles for the user himself,
11391: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11392: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11393: For each key, value is set to colon-separated start and end times for
11394: the role. If no username and domain are specified, will default to
11395: current user/domain. Types, roles, and roledoms are references to arrays
11396: of role statuses (active, future or previous), roles
11397: (e.g., cc,in, st etc.) and domains of the roles which can be used
11398: to restrict the list of roles reported. If no array ref is
11399: provided for types, will default to return only active roles.
11400:
11401: =back
11402:
11403: =head2 User Modification
11404:
11405: =over 4
11406:
11407: =item *
11408:
11409: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11410: user for the level given by URL. Optional start and end dates (leave empty
11411: string or zero for "no date")
11412:
11413: =item *
11414:
11415: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11416: change a users, password, possible return values are: ok,
11417: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11418: refused
11419:
11420: =item *
11421:
11422: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11423:
11424: =item *
11425:
11426: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11427: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11428:
11429: will update user information (firstname,middlename,lastname,generation,
11430: permanentemail), and if forceid is true, student/employee ID also.
11431: A user's institutional affiliation(s) can also be updated.
11432: User information fields will not be overwritten with empty entries
11433: unless the field is included in the $candelete array reference.
11434: This array is included when a single user is modified via "Manage Users",
11435: or when Autoupdate.pl is run by cron in a domain.
11436:
11437: =item *
11438:
11439: modifystudent
11440:
11441: modify a student's enrollment and identification information.
11442: The course id is resolved based on the current users environment.
11443: This means the envoking user must be a course coordinator or otherwise
11444: associated with a course.
11445:
11446: This call is essentially a wrapper for lonnet::modifyuser and
11447: lonnet::modify_student_enrollment
11448:
11449: Inputs:
11450:
11451: =over 4
11452:
11453: =item B<$udom> Student's loncapa domain
11454:
11455: =item B<$uname> Student's loncapa login name
11456:
11457: =item B<$uid> Student/Employee ID
11458:
11459: =item B<$umode> Student's authentication mode
11460:
11461: =item B<$upass> Student's password
11462:
11463: =item B<$first> Student's first name
11464:
11465: =item B<$middle> Student's middle name
11466:
11467: =item B<$last> Student's last name
11468:
11469: =item B<$gene> Student's generation
11470:
11471: =item B<$usec> Student's section in course
11472:
11473: =item B<$end> Unix time of the roles expiration
11474:
11475: =item B<$start> Unix time of the roles start date
11476:
11477: =item B<$forceid> If defined, allow $uid to be changed
11478:
11479: =item B<$desiredhome> server to use as home server for student
11480:
11481: =item B<$email> Student's permanent e-mail address
11482:
11483: =item B<$type> Type of enrollment (auto or manual)
11484:
11485: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11486:
11487: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11488:
11489: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11490:
11491: =item B<$context> role change context (shown in User Management Logs display in a course)
11492:
11493: =item B<$inststatus> institutional status of user - : separated string of escaped status types
11494:
11495: =back
11496:
11497: =item *
11498:
11499: modify_student_enrollment
11500:
11501: Change a students enrollment status in a class. The environment variable
11502: 'role.request.course' must be defined for this function to proceed.
11503:
11504: Inputs:
11505:
11506: =over 4
11507:
11508: =item $udom, students domain
11509:
11510: =item $uname, students name
11511:
11512: =item $uid, students user id
11513:
11514: =item $first, students first name
11515:
11516: =item $middle
11517:
11518: =item $last
11519:
11520: =item $gene
11521:
11522: =item $usec
11523:
11524: =item $end
11525:
11526: =item $start
11527:
11528: =item $type
11529:
11530: =item $locktype
11531:
11532: =item $cid
11533:
11534: =item $selfenroll
11535:
11536: =item $context
11537:
11538: =back
11539:
11540:
11541: =item *
11542:
11543: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11544: custom role; give a custom role to a user for the level given by URL. Specify
11545: name and domain of role author, and role name
11546:
11547: =item *
11548:
11549: revokerole($udom,$uname,$url,$role) : revoke a role for url
11550:
11551: =item *
11552:
11553: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11554:
11555: =back
11556:
11557: =head2 Course Infomation
11558:
11559: =over 4
11560:
11561: =item *
11562:
11563: coursedescription($courseid,$options) : returns a hash of information about the
11564: specified course id, including all environment settings for the
11565: course, the description of the course will be in the hash under the
11566: key 'description'
11567:
11568: $options is an optional parameter that if supplied is a hash reference that controls
11569: what how this function works. It has the following key/values:
11570:
11571: =over 4
11572:
11573: =item freshen_cache
11574:
11575: If defined, and the environment cache for the course is valid, it is
11576: returned in the returned hash.
11577:
11578: =item one_time
11579:
11580: If defined, the last cache time is set to _now_
11581:
11582: =item user
11583:
11584: If defined, the supplied username is used instead of the current user.
11585:
11586:
11587: =back
11588:
11589: =item *
11590:
11591: resdata($name,$domain,$type,@which) : request for current parameter
11592: setting for a specific $type, where $type is either 'course' or 'user',
11593: @what should be a list of parameters to ask about. This routine caches
11594: answers for 5 minutes.
11595:
11596: =item *
11597:
11598: get_courseresdata($courseid, $domain) : dump the entire course resource
11599: data base, returning a hash that is keyed by the resource name and has
11600: values that are the resource value. I believe that the timestamps and
11601: versions are also returned.
11602:
11603:
11604: =back
11605:
11606: =head2 Course Modification
11607:
11608: =over 4
11609:
11610: =item *
11611:
11612: writecoursepref($courseid,%prefs) : write preferences (environment
11613: database) for a course
11614:
11615: =item *
11616:
11617: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11618:
11619: =item *
11620:
11621: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11622:
11623: =back
11624:
11625: =head2 Resource Subroutines
11626:
11627: =over 4
11628:
11629: =item *
11630:
11631: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11632:
11633: =item *
11634:
11635: repcopy($filename) : subscribes to the requested file, and attempts to
11636: replicate from the owning library server, Might return
11637: 'unavailable', 'not_found', 'forbidden', 'ok', or
11638: 'bad_request', also attempts to grab the metadata for the
11639: resource. Expects the local filesystem pathname
11640: (/home/httpd/html/res/....)
11641:
11642: =back
11643:
11644: =head2 Resource Information
11645:
11646: =over 4
11647:
11648: =item *
11649:
11650: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11651: a vairety of different possible values, $varname should be a request
11652: string, and the other parameters can be used to specify who and what
11653: one is asking about.
11654:
11655: Possible values for $varname are environment.lastname (or other item
11656: from the envirnment hash), user.name (or someother aspect about the
11657: user), resource.0.maxtries (or some other part and parameter of a
11658: resource)
11659:
11660: =item *
11661:
11662: directcondval($number) : get current value of a condition; reads from a state
11663: string
11664:
11665: =item *
11666:
11667: condval($condidx) : value of condition index based on state
11668:
11669: =item *
11670:
11671: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11672: resource's metadata, $what should be either a specific key, or either
11673: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11674: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11675:
11676: this function automatically caches all requests
11677:
11678: =item *
11679:
11680: metadata_query($query,$custom,$customshow) : make a metadata query against the
11681: network of library servers; returns file handle of where SQL and regex results
11682: will be stored for query
11683:
11684: =item *
11685:
11686: symbread($filename) : return symbolic list entry (filename argument optional);
11687: returns the data handle
11688:
11689: =item *
11690:
11691: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11692: a possible symb for the URL in $thisfn, and if is an encryypted
11693: resource that the user accessed using /enc/ returns a 1 on success, 0
11694: on failure, user must be in a course, as it assumes the existance of
11695: the course initial hash, and uses $env('request.course.id'}
11696:
11697:
11698: =item *
11699:
11700: symbclean($symb) : removes versions numbers from a symb, returns the
11701: cleaned symb
11702:
11703: =item *
11704:
11705: is_on_map($uri) : checks if the $uri is somewhere on the current
11706: course map, user must be in a course for it to work.
11707:
11708: =item *
11709:
11710: numval($salt) : return random seed value (addend for rndseed)
11711:
11712: =item *
11713:
11714: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11715: a random seed, all arguments are optional, if they aren't sent it uses the
11716: environment to derive them. Note: if symb isn't sent and it can't get one
11717: from &symbread it will use the current time as its return value
11718:
11719: =item *
11720:
11721: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11722: unfakeable, receipt
11723:
11724: =item *
11725:
11726: receipt() : API to ireceipt working off of env values; given out to users
11727:
11728: =item *
11729:
11730: countacc($url) : count the number of accesses to a given URL
11731:
11732: =item *
11733:
11734: 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
11735:
11736: =item *
11737:
11738: 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)
11739:
11740: =item *
11741:
11742: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11743:
11744: =item *
11745:
11746: devalidate($symb) : devalidate temporary spreadsheet calculations,
11747: forcing spreadsheet to reevaluate the resource scores next time.
11748:
11749: =back
11750:
11751: =head2 Storing/Retreiving Data
11752:
11753: =over 4
11754:
11755: =item *
11756:
11757: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11758: for this url; hashref needs to be given and should be a \%hashname; the
11759: remaining args aren't required and if they aren't passed or are '' they will
11760: be derived from the env
11761:
11762: =item *
11763:
11764: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11765: uses critical subroutine
11766:
11767: =item *
11768:
11769: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11770: all args are optional
11771:
11772: =item *
11773:
11774: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11775: dumps the complete (or key matching regexp) namespace into a hash
11776: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11777: normally &store()ed into
11778:
11779: $range should be either an integer '100' (give me the first 100
11780: matching records)
11781: or be two integers sperated by a - with no spaces
11782: '30-50' (give me the 30th through the 50th matching
11783: records)
11784:
11785:
11786: =item *
11787:
11788: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11789: replaces a &store() version of data with a replacement set of data
11790: for a particular resource in a namespace passed in the $storehash hash
11791: reference
11792:
11793: =item *
11794:
11795: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11796: works very similar to store/cstore, but all data is stored in a
11797: temporary location and can be reset using tmpreset, $storehash should
11798: be a hash reference, returns nothing on success
11799:
11800: =item *
11801:
11802: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11803: similar to restore, but all data is stored in a temporary location and
11804: can be reset using tmpreset. Returns a hash of values on success,
11805: error string otherwise.
11806:
11807: =item *
11808:
11809: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11810: deltes all keys for $symb form the temporary storage hash.
11811:
11812: =item *
11813:
11814: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11815: reference filled in from namesp ($udom and $uname are optional)
11816:
11817: =item *
11818:
11819: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11820: namesp ($udom and $uname are optional)
11821:
11822: =item *
11823:
11824: dump($namespace,$udom,$uname,$regexp,$range) :
11825: dumps the complete (or key matching regexp) namespace into a hash
11826: ($udom, $uname, $regexp, $range are optional)
11827:
11828: $range should be either an integer '100' (give me the first 100
11829: matching records)
11830: or be two integers sperated by a - with no spaces
11831: '30-50' (give me the 30th through the 50th matching
11832: records)
11833: =item *
11834:
11835: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11836: $store can be a scalar, an array reference, or if the amount to be
11837: incremented is > 1, a hash reference.
11838:
11839: ($udom and $uname are optional)
11840:
11841: =item *
11842:
11843: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11844: ($udom and $uname are optional)
11845:
11846: =item *
11847:
11848: cput($namespace,$storehash,$udom,$uname) : critical put
11849: ($udom and $uname are optional)
11850:
11851: =item *
11852:
11853: newput($namespace,$storehash,$udom,$uname) :
11854:
11855: Attempts to store the items in the $storehash, but only if they don't
11856: currently exist, if this succeeds you can be certain that you have
11857: successfully created a new key value pair in the $namespace db.
11858:
11859:
11860: Args:
11861: $namespace: name of database to store values to
11862: $storehash: hashref to store to the db
11863: $udom: (optional) domain of user containing the db
11864: $uname: (optional) name of user caontaining the db
11865:
11866: Returns:
11867: 'ok' -> succeeded in storing all keys of $storehash
11868: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11869: least <key> already existed in the db (other
11870: requested keys may also already exist)
11871: 'error: <msg>' -> unable to tie the DB or other error occurred
11872: 'con_lost' -> unable to contact request server
11873: 'refused' -> action was not allowed by remote machine
11874:
11875:
11876: =item *
11877:
11878: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11879: reference filled in from namesp (encrypts the return communication)
11880: ($udom and $uname are optional)
11881:
11882: =item *
11883:
11884: log($udom,$name,$home,$message) : write to permanent log for user; use
11885: critical subroutine
11886:
11887: =item *
11888:
11889: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11890: array reference filled in from namespace found in domain level on either
11891: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11892:
11893: =item *
11894:
11895: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11896: domain level either on specified domain server ($uhome) or primary domain
11897: server ($udom and $uhome are optional)
11898:
11899: =item *
11900:
11901: get_domain_defaults($target_domain) : returns hash with defaults for
11902: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11903: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11904: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11905: Values are retrieved from cache (if current), or from domain's configuration.db
11906: (if available), or lastly from values in lonTabs/dns_domain,tab,
11907: or lonTabs/domain.tab.
11908:
11909: %domdefaults = &get_auth_defaults($target_domain);
11910:
11911: =back
11912:
11913: =head2 Network Status Functions
11914:
11915: =over 4
11916:
11917: =item *
11918:
11919: dirlist() : return directory list based on URI (first arg).
11920:
11921: Inputs: 1 required, 5 optional.
11922:
11923: =over
11924:
11925: =item
11926: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11927:
11928: =item
11929: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
11930:
11931: =item
11932: $username - username of user/course to be listed. Extracted from $uri if absent.
11933:
11934: =item
11935: $getpropath - boolean: 1 if prepend path using &propath().
11936:
11937: =item
11938: $getuserdir - boolean: 1 if prepend path for "userfiles".
11939:
11940: =item
11941: $alternateRoot - path to prepend in place of path from $uri.
11942:
11943: =back
11944:
11945: Returns: Array of up to two items.
11946:
11947: =over
11948:
11949: a reference to an array of files/subdirectories
11950:
11951: =over
11952:
11953: Each element in the array of files/subdirectories is a & separated list of
11954: item name and the result of running stat on the item. If dirlist was requested
11955: for a file instead of a directory, the item name will be ''. For a directory
11956: listing, if the item is a metadata file, the element will end &N&M
11957: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11958: default copyright set (1).
11959:
11960: =back
11961:
11962: a scalar containing error condition (if encountered).
11963:
11964: =over
11965:
11966: =item
11967: no_host (no homeserver identified for $username:$domain).
11968:
11969: =item
11970: no_such_host (server contacted for listing not identified as valid host).
11971:
11972: =item
11973: con_lost (connection to remote server failed).
11974:
11975: =item
11976: refused (invalid $username:$domain received on lond side).
11977:
11978: =item
11979: no_such_dir (directory at specified path on lond side does not exist).
11980:
11981: =item
11982: empty (directory at specified path on lond side is empty).
11983:
11984: =over
11985:
11986: This is currently not encountered because the &ls3, &ls2,
11987: &ls (_handler) routines on the lond side do not filter out
11988: . and .. from a directory listing.
11989:
11990: =back
11991:
11992: =back
11993:
11994: =back
11995:
11996: =item *
11997:
11998: spareserver() : find server with least workload from spare.tab
11999:
12000:
12001: =item *
12002:
12003: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12004: if there is no corresponding loncapa host.
12005:
12006: =back
12007:
12008:
12009: =head2 Apache Request
12010:
12011: =over 4
12012:
12013: =item *
12014:
12015: ssi($url,%hash) : server side include, does a complete request cycle on url to
12016: localhost, posts hash
12017:
12018: =back
12019:
12020: =head2 Data to String to Data
12021:
12022: =over 4
12023:
12024: =item *
12025:
12026: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12027: and '&' separators, supports elements that are arrayrefs and hashrefs
12028:
12029: =item *
12030:
12031: hashref2str($hashref) : convert a hashref into a string complete with
12032: escaping and '=' and '&' separators, supports elements that are
12033: arrayrefs and hashrefs
12034:
12035: =item *
12036:
12037: arrayref2str($arrayref) : convert an arrayref into a string complete
12038: with escaping and '&' separators, supports elements that are arrayrefs
12039: and hashrefs
12040:
12041: =item *
12042:
12043: str2hash($string) : convert string to hash using unescaping and
12044: splitting on '=' and '&', supports elements that are arrayrefs and
12045: hashrefs
12046:
12047: =item *
12048:
12049: str2array($string) : convert string to hash using unescaping and
12050: splitting on '&', supports elements that are arrayrefs and hashrefs
12051:
12052: =back
12053:
12054: =head2 Logging Routines
12055:
12056:
12057: These routines allow one to make log messages in the lonnet.log and
12058: lonnet.perm logfiles.
12059:
12060: =over 4
12061:
12062: =item *
12063:
12064: logtouch() : make sure the logfile, lonnet.log, exists
12065:
12066: =item *
12067:
12068: logthis() : append message to the normal lonnet.log file, it gets
12069: preiodically rolled over and deleted.
12070:
12071: =item *
12072:
12073: logperm() : append a permanent message to lonnet.perm.log, this log
12074: file never gets deleted by any automated portion of the system, only
12075: messages of critical importance should go in here.
12076:
12077:
12078: =back
12079:
12080: =head2 General File Helper Routines
12081:
12082: =over 4
12083:
12084: =item *
12085:
12086: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12087: (a) files in /uploaded
12088: (i) If a local copy of the file exists -
12089: compares modification date of local copy with last-modified date for
12090: definitive version stored on home server for course. If local copy is
12091: stale, requests a new version from the home server and stores it.
12092: If the original has been removed from the home server, then local copy
12093: is unlinked.
12094: (ii) If local copy does not exist -
12095: requests the file from the home server and stores it.
12096:
12097: If $caller is 'uploadrep':
12098: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12099: for request for files originally uploaded via DOCS.
12100: - returns 'ok' if fresh local copy now available, -1 otherwise.
12101:
12102: Otherwise:
12103: This indicates a call from the content generation phase of the request.
12104: - returns the entire contents of the file or -1.
12105:
12106: (b) files in /res
12107: - returns the entire contents of a file or -1;
12108: it properly subscribes to and replicates the file if neccessary.
12109:
12110:
12111: =item *
12112:
12113: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12114: reference
12115:
12116: returns either a stat() list of data about the file or an empty list
12117: if the file doesn't exist or couldn't find out about it (connection
12118: problems or user unknown)
12119:
12120: =item *
12121:
12122: filelocation($dir,$file) : returns file system location of a file
12123: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12124: directory that relative $file lookups are to looked in ($dir of /a/dir
12125: and a file of ../bob will become /a/bob)
12126:
12127: =item *
12128:
12129: hreflocation($dir,$file) : returns file system location or a URL; same as
12130: filelocation except for hrefs
12131:
12132: =item *
12133:
12134: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12135:
12136: =back
12137:
12138: =head2 Usererfile file routines (/uploaded*)
12139:
12140: =over 4
12141:
12142: =item *
12143:
12144: userfileupload(): main rotine for putting a file in a user or course's
12145: filespace, arguments are,
12146:
12147: formname - required - this is the name of the element in $env where the
12148: filename, and the contents of the file to create/modifed exist
12149: the filename is in $env{'form.'.$formname.'.filename'} and the
12150: contents of the file is located in $env{'form.'.$formname}
12151: context - if coursedoc, store the file in the course of the active role
12152: of the current user;
12153: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12154: if 'canceloverwrite': delete file in tmp/overwrites directory
12155: subdir - required - subdirectory to put the file in under ../userfiles/
12156: if undefined, it will be placed in "unknown"
12157:
12158: (This routine calls clean_filename() to remove any dangerous
12159: characters from the filename, and then calls finuserfileupload() to
12160: complete the transaction)
12161:
12162: returns either the url of the uploaded file (/uploaded/....) if successful
12163: and /adm/notfound.html if unsuccessful
12164:
12165: =item *
12166:
12167: clean_filename(): routine for cleaing a filename up for storage in
12168: userfile space, argument is:
12169:
12170: filename - proposed filename
12171:
12172: returns: the new clean filename
12173:
12174: =item *
12175:
12176: finishuserfileupload(): routine that creates and sends the file to
12177: userspace, probably shouldn't be called directly
12178:
12179: docuname: username or courseid of destination for the file
12180: docudom: domain of user/course of destination for the file
12181: formname: same as for userfileupload()
12182: fname: filename (including subdirectories) for the file
12183: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12184: allfiles: reference to hash used to store objects found by parser
12185: codebase: reference to hash used for codebases of java objects found by parser
12186: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12187: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12188: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12189: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12190: context: if 'overwrite', will move the uploaded file from its temporary location to
12191: userfiles to facilitate overwriting a previously uploaded file with same name.
12192: mimetype: reference to scalar to accommodate mime type determined
12193: from File::MMagic if $parser = parse.
12194:
12195: returns either the url of the uploaded file (/uploaded/....) if successful
12196: and /adm/notfound.html if unsuccessful (or an error message if context
12197: was 'overwrite').
12198:
12199:
12200: =item *
12201:
12202: renameuserfile(): renames an existing userfile to a new name
12203:
12204: Args:
12205: docuname: username or courseid of destination for the file
12206: docudom: domain of user/course of destination for the file
12207: old: current file name (including any subdirs under userfiles)
12208: new: desired file name (including any subdirs under userfiles)
12209:
12210: =item *
12211:
12212: mkdiruserfile(): creates a directory is a userfiles dir
12213:
12214: Args:
12215: docuname: username or courseid of destination for the file
12216: docudom: domain of user/course of destination for the file
12217: dir: dir to create (including any subdirs under userfiles)
12218:
12219: =item *
12220:
12221: removeuserfile(): removes a file that exists in userfiles
12222:
12223: Args:
12224: docuname: username or courseid of destination for the file
12225: docudom: domain of user/course of destination for the file
12226: fname: filname to delete (including any subdirs under userfiles)
12227:
12228: =item *
12229:
12230: removeuploadedurl(): convience function for removeuserfile()
12231:
12232: Args:
12233: url: a full /uploaded/... url to delete
12234:
12235: =item *
12236:
12237: get_portfile_permissions():
12238: Args:
12239: domain: domain of user or course contain the portfolio files
12240: user: name of user or num of course contain the portfolio files
12241: Returns:
12242: hashref of a dump of the proper file_permissions.db
12243:
12244:
12245: =item *
12246:
12247: get_access_controls():
12248:
12249: Args:
12250: current_permissions: the hash ref returned from get_portfile_permissions()
12251: group: (optional) the group you want the files associated with
12252: file: (optional) the file you want access info on
12253:
12254: Returns:
12255: a hash (keys are file names) of hashes containing
12256: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12257: values are XML containing access control settings (see below)
12258:
12259: Internal notes:
12260:
12261: access controls are stored in file_permissions.db as key=value pairs.
12262: key -> path to file/file_name\0uniqueID:scope_end_start
12263: where scope -> public,guest,course,group,domains or users.
12264: end -> UNIX time for end of access (0 -> no end date)
12265: start -> UNIX time for start of access
12266:
12267: value -> XML description of access control
12268: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12269: <start></start>
12270: <end></end>
12271:
12272: <password></password> for scope type = guest
12273:
12274: <domain></domain> for scope type = course or group
12275: <number></number>
12276: <roles id="">
12277: <role></role>
12278: <access></access>
12279: <section></section>
12280: <group></group>
12281: </roles>
12282:
12283: <dom></dom> for scope type = domains
12284:
12285: <users> for scope type = users
12286: <user>
12287: <uname></uname>
12288: <udom></udom>
12289: </user>
12290: </users>
12291: </scope>
12292:
12293: Access data is also aggregated for each file in an additional key=value pair:
12294: key -> path to file/file_name\0accesscontrol
12295: value -> reference to hash
12296: hash contains key = value pairs
12297: where key = uniqueID:scope_end_start
12298: value = UNIX time record was last updated
12299:
12300: Used to improve speed of look-ups of access controls for each file.
12301:
12302: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12303:
12304: modify_access_controls():
12305:
12306: Modifies access controls for a portfolio file
12307: Args
12308: 1. file name
12309: 2. reference to hash of required changes,
12310: 3. domain
12311: 4. username
12312: where domain,username are the domain of the portfolio owner
12313: (either a user or a course)
12314:
12315: Returns:
12316: 1. result of additions or updates ('ok' or 'error', with error message).
12317: 2. result of deletions ('ok' or 'error', with error message).
12318: 3. reference to hash of any new or updated access controls.
12319: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12320: key = integer (inbound ID)
12321: value = uniqueID
12322:
12323: =back
12324:
12325: =head2 HTTP Helper Routines
12326:
12327: =over 4
12328:
12329: =item *
12330:
12331: escape() : unpack non-word characters into CGI-compatible hex codes
12332:
12333: =item *
12334:
12335: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12336:
12337: =back
12338:
12339: =head1 PRIVATE SUBROUTINES
12340:
12341: =head2 Underlying communication routines (Shouldn't call)
12342:
12343: =over 4
12344:
12345: =item *
12346:
12347: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12348:
12349: =item *
12350:
12351: reply() : uses subreply to send a message to remote machine, logs all failures
12352:
12353: =item *
12354:
12355: critical() : passes a critical message to another server; if cannot
12356: get through then place message in connection buffer directory and
12357: returns con_delayed, if incapable of saving message, returns
12358: con_failed
12359:
12360: =item *
12361:
12362: reconlonc() : tries to reconnect lonc client processes.
12363:
12364: =back
12365:
12366: =head2 Resource Access Logging
12367:
12368: =over 4
12369:
12370: =item *
12371:
12372: flushcourselogs() : flush (save) buffer logs and access logs
12373:
12374: =item *
12375:
12376: courselog($what) : save message for course in hash
12377:
12378: =item *
12379:
12380: courseacclog($what) : save message for course using &courselog(). Perform
12381: special processing for specific resource types (problems, exams, quizzes, etc).
12382:
12383: =item *
12384:
12385: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12386: as a PerlChildExitHandler
12387:
12388: =back
12389:
12390: =head2 Other
12391:
12392: =over 4
12393:
12394: =item *
12395:
12396: symblist($mapname,%newhash) : update symbolic storage links
12397:
12398: =back
12399:
12400: =cut
12401:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>